问:
My page is scrolling to right. Why is it happening?
I'm building a web page and working in the layout for small screens (max-width: 600px). When the screen gets narrow, the page gets a bit of horizontal scroll, as you can see in the code snippet, but it is unexpected for me. I am not finding anything wider than the viewport's width in my code. Why is there that scroll?

/* CSS from index_default.css */

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    font-family: 'Open Sans', sans-serif;
}
h2, h3{
    margin-top: 10px;
    margin-bottom: 10px;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 10px;
}
header h1{
    font-family: 'Doppio One', cursive;
    color: rgb(214, 245, 210);
}
nav a{
    color: rgb(230, 245, 229);
}
#menu{
    width: 30px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#lastsection img{
    display: block;
    margin-right: auto;
    margin-left: auto;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    color: rgb(214, 245, 210);
}

/* CSS from index_small.css */

@charset "UTF-8";
body{
    width: 100vw;
    text-align: center;
}
header{
    padding-right: 10px;
    padding-left: 10px;
}
header img:first-of-type{
    width: 40px;
    margin-right: 5px;
}
header ul{
    display: none;
}
#menu{
    margin-left: 15vh;
}
#firstsection{
    background-color: rgb(220, 255, 211);
    height: 40vh;
    padding: 10% 20px 0;
    margin-bottom: 8%;
}
#firstsection div{
    margin-bottom: 30px;
}
#firstsection a{
    position: relative;
    top: 35px;
}
#middlesection{
    margin: 0 5vw;
}
#textboxes div{
    margin-bottom: 8%;
}
#lastsection img{
    width: 90%;
    margin-top: 8vh;
}
#lastsection div{
    position: relative;
    bottom: 18.5vh;
}
#lastsection div h2{
    font-size: 1.2rem;
}
footer img{
    width: 40px;
    margin-right: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="index_default.css">
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 600px)" href="index_small.css">
        <link rel="stylesheet" type="text/css" media="screen and (min-width: 1500px)" href="index_large.css">
    </head>
    <body>
        <header>
            <img src="Images/icons8-fund-accounting-80.png">
            <h1>Finances</h1>
            <nav>
                <ul>
                    <li>Home</li>
                    <li>About</li>
                    <li>Contact us</li>
                    <li>Register</li>
                    <li>Login</li>
                </ul>
                <img src="Images/icons8-menu-50.png" id="menu">
            </nav>
        </header>
        <main>
            <section id="firstsection">
                <div>
                    <h1>Manage your money easily, anywhere, anytime.</h1>
                    Get started
                </div>
            </section>
            <section id="middlesection">
                <div id="textboxes">
                    <div>
                        <img src="Images/icons8-increase-64.png">
                        <h3>Concrete data</h3>
                        <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-navigation-toolbar-left-filled-50 (1).png">
                        <h3>Easy interface</h3>
                        <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-natural-user-interface-2-filled-50.png">
                        <h3>Fast access</h3>
                        <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
                    </div>
                </div>
            </section>
            <section id="lastsection">
                <img src="Images/board-1362851_1280.png">
                <div>
                    <h2>Register now and enjoy<br>the best of Finances.</h2>
                    Create an account
                </div>
            </section>
        </main>
        <footer>
            <img src="Images/icons8-fund-accounting-80.png">
            <div>
                <p>A work of Bruno Sdoukos.</p>
            </div>
        </footer>
    </body>
</html></code>```

答:
It is the width: 100vw given to body which is causing the scroll. This may be happening as you might have given left or right margin to other sections of the page or assigned widths such that it exceeds the viewport.
Now you can inspect them one by one and rectify.
Alternatively, you can adopt any one of these styles for your body tag in addition to what you're using:

Get rid of width: 100vw or

Add max-width:100vw or

Add overflow-x: hidden

Adopting any one of these should fix your issue. Cheers!!

Body:
I'm building a web page and working in the layout for small screens (max-width: 600px). When the screen gets narrow, the page gets a bit of horizontal scroll, as you can see in the code snippet, but it is unexpected for me. I am not finding anything wider than the viewport's width in my code. Why is there that scroll?

/* CSS from index_default.css */

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body{
    font-family: 'Open Sans', sans-serif;
}
h2, h3{
    margin-top: 10px;
    margin-bottom: 10px;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding-top: 10px;
    padding-bottom: 10px;
}
header h1{
    font-family: 'Doppio One', cursive;
    color: rgb(214, 245, 210);
}
nav a{
    color: rgb(230, 245, 229);
}
#menu{
    width: 30px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#lastsection img{
    display: block;
    margin-right: auto;
    margin-left: auto;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    color: rgb(214, 245, 210);
}

/* CSS from index_small.css */

@charset "UTF-8";
body{
    width: 100vw;
    text-align: center;
}
header{
    padding-right: 10px;
    padding-left: 10px;
}
header img:first-of-type{
    width: 40px;
    margin-right: 5px;
}
header ul{
    display: none;
}
#menu{
    margin-left: 15vh;
}
#firstsection{
    background-color: rgb(220, 255, 211);
    height: 40vh;
    padding: 10% 20px 0;
    margin-bottom: 8%;
}
#firstsection div{
    margin-bottom: 30px;
}
#firstsection a{
    position: relative;
    top: 35px;
}
#middlesection{
    margin: 0 5vw;
}
#textboxes div{
    margin-bottom: 8%;
}
#lastsection img{
    width: 90%;
    margin-top: 8vh;
}
#lastsection div{
    position: relative;
    bottom: 18.5vh;
}
#lastsection div h2{
    font-size: 1.2rem;
}
footer img{
    width: 40px;
    margin-right: 8px;
}

<!DOCTYPE html>

        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="index_default.css">
        <link rel="stylesheet" type="text/css" media="screen and (max-width: 600px)" href="index_small.css">
        <link rel="stylesheet" type="text/css" media="screen and (min-width: 1500px)" href="index_large.css">

Finances

Home

About

Contact us

Register

Login

Manage your money easily, anywhere, anytime.

                    Get started

Concrete data

Simple but concrete data that are the answer to all the quesions about your current money, spending and.

Easy interface

An interface easy to use, made to you who want to manage your money faster and with no problems.

Fast access

No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.

Register now and enjoy
the best of Finances.

                    Create an account

A work of Bruno Sdoukos.


来源: stackexchange

问:
Using Bitwise Operators in C
I am a beginner to C language.I have a code for towers of hanoi but can someone explain me what are these bitwise operators doing ie if value of i is 1 what will be the source and target output value ?</p>

```<code>source = (i & i-1) % 3;
target = ((i | i-1) + 1) % 3;
</code>```

答:
A quick overview of bitwise operators:

Each operator takes the bits of both numbers and applies the operation to each bit of it.

& Bitwise AND

True only if both bits are true.

Truth table:

```<code>A | B | A & B
-------------
0 | 0 | 0
1 | 0 | 0
0 | 1 | 0
1 | 1 | 1
</code>```

| Bitwise OR

True if either bit is true.

Truth table:

```<code>A | B | A | B
-------------
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 1
</code>```

^ Bitwise XOR

True if only one bit is true.

Truth table:

```<code>A | B | A ^ B
-------------
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 0
</code>```

~ Bitwise NOT

Inverts each bit. 1 -> 0, 0 -> 1. This is a unary operator.

Truth table:

```<code>A | ~A
------
0 | 1
1 | 0
</code>```

In your case, if i = 1,
the expressions would be evaluated as:

```<code>source = (1 & 1-1) % 3;
target = ((1 | 1-1) + 1) % 3;
// =>
source = (1 & 0) % 3;
target = ((1 | 0) + 1) % 3;
// =>
source = 0 % 3;
target = (1 + 1) % 3;
// =>
source = 0;
target = 2 % 3;
// =>
source = 0;
target = 2;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Using Bitwise Operators in C

Body:
I am a beginner to C language.I have a code for towers of hanoi but can someone explain me what are these bitwise operators doing ie if value of i is 1 what will be the source and target output value ?

source = (i & i-1) % 3;
target = ((i | i-1) + 1) % 3;

Body:
A quick overview of bitwise operators:

Each operator takes the bits of both numbers and applies the operation to each bit of it.

& Bitwise AND

True only if both bits are true.

Truth table:

A | B | A & B
-------------
0 | 0 | 0
1 | 0 | 0
0 | 1 | 0
1 | 1 | 1

| Bitwise OR

True if either bit is true.

Truth table:

A | B | A | B
-------------
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 1

^ Bitwise XOR

True if only one bit is true.

Truth table:

A | B | A ^ B
-------------
0 | 0 | 0
1 | 0 | 1
0 | 1 | 1
1 | 1 | 0

~ Bitwise NOT

Inverts each bit. 1 -> 0, 0 -> 1. This is a unary operator.

Truth table:

A | ~A
------
0 | 1
1 | 0

In your case, if i = 1,
the expressions would be evaluated as:

source = (1 & 1-1) % 3;
target = ((1 | 1-1) + 1) % 3;
// =>
source = (1 & 0) % 3;
target = ((1 | 0) + 1) % 3;
// =>
source = 0 % 3;
target = (1 + 1) % 3;
// =>
source = 0;
target = 2 % 3;
// =>
source = 0;
target = 2;


问:
Discord.py not working after installing
After installing discord.py from the command: -

```<code>python3 -m pip install -U discord.py
</code>```

I cannot access or use the discord library from within any python programs. Is there something else that I have to do first?

Basically it finds an error when importing discord via "import discord".

Thank you

答:
This is a simple problem.

Check these things then come back:

Did you edit your enviromental variable to support pip?

Did you install discord.py through pip?

Are you using the correct version of Python? See this for supported versions

Please read the discord.py docs if you have any other issues.

Thank you.

ContentLicense: CC BY-SA 3.0

Title: Discord.py not working after installing

Body:
After installing discord.py from the command: -

python3 -m pip install -U discord.py

I cannot access or use the discord library from within any python programs. Is there something else that I have to do first?

Basically it finds an error when importing discord via "import discord".

Thank you


问:
Unity 3D: how to freeze frame to explore the collision lines drawn by `Debug.DrawRay`?
I tried this:

Debug.DrawRay(contact.point, collision.relativeVelocity, Color.white);
Time.timeScale = 0.0f;
```

the frame was frozen but the line was not displayed. Also, I tried to freeze in the Update immediately after drawing the line without success as well as after skipping the first Update.

答:
OnCollisionEnter is only called once in the frame when the collision first occures.

Debug.DrawLine has an optional parameter duration of  which by default is 0

How long the line should be visible for.

and

The duration is the time (in seconds) for which the line will be visible after it is first displayed. A duration of zero shows the line for just one frame.

So you could pass e.g. 2 like

Debug.DrawRay(contact.point, collision.relativeVelocity, Color.white, 2.0f);
```

to make it stay visible for 2 seconds.

As alternative I would simply put the code in OnCollisionStay instead so it is called not only once but every frame while the collision occures.

For the question behind it the Unity API usually is a good startpoint:

Collision.impulse

The total impulse applied to this contact pair to resolve the collision.

The total impulse is obtained by summing up impulses applied at all contact points in this collision pair. To work out the total force applied you can divide the total impulse by the last frame's fixedDeltaTime.

Collision.relativeVelocity

The relative linear velocity of the two colliding objects.

So the difference: impulse takes all individual contact/collision points into account where each might have different collision forces and directions while relativeVelocity only is the relative velocity between the object centers/pivot points (it doesn't matter).

Body:
I tried this:

Debug.DrawRay(contact.point, collision.relativeVelocity, Color.white);
Time.timeScale = 0.0f;

the frame was frozen but the line was not displayed. Also, I tried to freeze in the Update immediately after drawing the line without success as well as after skipping the first Update.

Body:
OnCollisionEnter is only called once in the frame when the collision first occures.

Debug.DrawLine has an optional parameter duration of  which by default is 0

How long the line should be visible for.

and

The duration is the time (in seconds) for which the line will be visible after it is first displayed. A duration of zero shows the line for just one frame.

So you could pass e.g. 2 like

Debug.DrawRay(contact.point, collision.relativeVelocity, Color.white, 2.0f);

to make it stay visible for 2 seconds.

As alternative I would simply put the code in OnCollisionStay instead so it is called not only once but every frame while the collision occures.

For the question behind it the Unity API usually is a good startpoint:

Collision.impulse

The total impulse applied to this contact pair to resolve the collision.

The total impulse is obtained by summing up impulses applied at all contact points in this collision pair. To work out the total force applied you can divide the total impulse by the last frame's fixedDeltaTime.

Collision.relativeVelocity

The relative linear velocity of the two colliding objects.

So the difference: impulse takes all individual contact/collision points into account where each might have different collision forces and directions while relativeVelocity only is the relative velocity between the object centers/pivot points (it doesn't matter).


问:
Finding keyword +1 and making new column
Goals:

1) locate word next to keyword (e.g brca)

2) create a new column with this word

Background:

1) I have a list l in which I make into a dataframe df and extract the word brca from it using the following code:

```<code>l = ['carcinoma brca positive completion mastectomy',
     'clinical brca gene mutation',
     'carcinoma brca positive chemotherapy']
df = pd.DataFrame(l, columns=['Text'])
df['Gene'] = df['Text'].str.extract(r"(brca)")
</code>```

Output:

```<code>                                                Text    Gene
0   breast invasive lobular carcinoma brca positiv...   brca
1   clinical history brca gene mutation . gross de...   brca
2   left breast invasive ductal carcinoma brca pos...   brca
</code>```

Problem:

However, I am now trying to find the word next to the word brca for each row and create a new column.

Desired Output:

```<code>                                                Text    Gene  NextWord
0   breast invasive lobular carcinoma brca positiv...   brca  positive
1   clinical history brca gene mutation . gross de...   brca  gene
2   left breast invasive ductal carcinoma brca pos...   brca  positive
</code>```

I have looked python pandas dataframe words in context: get 3 words before and after and PANDAS Finding the exact word and before word in a column of string and append that new column in python (pandas) column but they do not quite work for me.

Question:

How do I accomplish my goals?

答:
We can make use of the built-in method of python called partition

```<code>df['NextWord'] = df['Text'].apply(lambda x: x.partition('brca')[2]).str.split().str[0]
</code>```

Output

```<code>                                            Text  Gene  NextWord
0  carcinoma brca positive completion mastectomy  brca  positive
1                    clinical brca gene mutation  brca      gene
2           carcinoma brca positive chemotherapy  brca  positive
</code>```

Explanation

.partition returns three values:

The string before the keyword

The keyword itself

The string after the keyword

```<code>string = 'carcinoma brca positive completion mastectomy'

before, keyword, after = string.partition('brca')

print(before)
print(keyword)
print(after)
</code>```

Output

```<code>carcinoma
brca
 positive completion mastectomy
</code>```

Speed

I was curious about the speed comparison between the answers, since I used .apply but its a built in method. Unexpectedly, my answer was the fastest:

```<code>dfbig = pd.concat([df]*10000, ignore_index=True)
dfbig.shape

(30000, 2)
</code>```

```<code>%%timeit
dfbig['Text'].apply(lambda x: x.partition('brca')[2]).str.split().str[0]
31.5 ms ± 1.36 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
dfbig['NextWord'] = dfbig['Text'].str.split('brca').str[1].str.split('\s').str[1]
74.5 ms ± 2.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
dfbig['NextWord'] = dfbig['Text'].str.extract(r"(?<=brca)(.+?) ")
40.7 ms ± 2.4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

Body:
Goals:

1) locate word next to keyword (e.g brca)

2) create a new column with this word

Background:

1) I have a list l in which I make into a dataframe df and extract the word brca from it using the following code:

l = ['carcinoma brca positive completion mastectomy',
     'clinical brca gene mutation',
     'carcinoma brca positive chemotherapy']
df = pd.DataFrame(l, columns=['Text'])
df['Gene'] = df['Text'].str.extract(r"(brca)")

Output:

                                                Text    Gene
0   breast invasive lobular carcinoma brca positiv...   brca
1   clinical history brca gene mutation . gross de...   brca
2   left breast invasive ductal carcinoma brca pos...   brca

Problem:

However, I am now trying to find the word next to the word brca for each row and create a new column.

Desired Output:

                                                Text    Gene  NextWord
0   breast invasive lobular carcinoma brca positiv...   brca  positive
1   clinical history brca gene mutation . gross de...   brca  gene
2   left breast invasive ductal carcinoma brca pos...   brca  positive

I have looked python pandas dataframe words in context: get 3 words before and after and PANDAS Finding the exact word and before word in a column of string and append that new column in python (pandas) column but they do not quite work for me.

Question:

How do I accomplish my goals?

Body:
We can make use of the built-in method of python called partition

df['NextWord'] = df['Text'].apply(lambda x: x.partition('brca')[2]).str.split().str[0]

Output

                                            Text  Gene  NextWord
0  carcinoma brca positive completion mastectomy  brca  positive
1                    clinical brca gene mutation  brca      gene
2           carcinoma brca positive chemotherapy  brca  positive

Explanation

.partition returns three values:

The string before the keyword

The keyword itself

The string after the keyword

string = 'carcinoma brca positive completion mastectomy'

before, keyword, after = string.partition('brca')

print(before)
print(keyword)
print(after)

Output

carcinoma
brca
 positive completion mastectomy

Speed

I was curious about the speed comparison between the answers, since I used .apply but its a built in method. Unexpectedly, my answer was the fastest:

dfbig = pd.concat([df]*10000, ignore_index=True)
dfbig.shape

(30000, 2)

%%timeit
dfbig['Text'].apply(lambda x: x.partition('brca')[2]).str.split().str[0]
31.5 ms ± 1.36 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
dfbig['NextWord'] = dfbig['Text'].str.split('brca').str[1].str.split('\s').str[1]
74.5 ms ± 2.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
dfbig['NextWord'] = dfbig['Text'].str.extract(r"(?<=brca)(.+?) ")
40.7 ms ± 2.4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


问:
Problem when trying to plot two histograms using fill aesthetic
I've been trying to plot two histograms by using the fill aesthetic and a specific column with two levels. However, instead of displaying both desired histograms, my code displays one histogram with the whole data and another only for the second classification. I don't know if there is a problem in my syntax neither if this is some kind of tricky issue.

```<code>    library(tidyverse)

    db1 <- data.frame(type=rep("A",100),val=rnorm(n=100,mean=50,sd=10))
    db2 <- data.frame(type=rep("B",150),val=rnorm(n=150,mean=50,sd=10))
    dbf <- bind_rows(db1,db2)

    P1 <- ggplot(db1, aes(x=val)) + geom_histogram()
    P2 <- ggplot(db2, aes(x=val)) + geom_histogram()
    PF <- ggplot(dbf, aes(x=val)) + geom_histogram()
</code>```

I want to get this, P1 and P2

```<code>ggplot(db1, aes(x=val)) + geom_histogram(fill="red", alpha=0.5) + geom_histogram(data=db2, aes(x=val),fill="green", alpha=0.5)
</code>```

What I want

But the code I think should work, P1 and P2 with the fill aesthetic for column val

```<code>ggplot(dbf, aes(x=val)) + geom_histogram(aes(fill=type), alpha=0.5)
</code>```

My code

Produces the combination of PF and P2

```<code>ggplot(dbf, aes(x=val)) + geom_histogram(fill="red", alpha=0.5) + geom_histogram(data=db2, aes(x=val),fill="green", alpha=0.5)
</code>```

What I get

Any help or idea will be highly appreciated!

答:
Is your goal to show the overlap via the color combination? I'm not sure how to force geom_histogram to show the overlap, but geom_density does do what you want. You can play with the bandwidth (bw) to show more or less detail.</p>

```<code>dbf %>% ggplot() +
  aes(x = val, fill = type) +
  geom_density(alpha = .5, bw = .5) +
  scale_fill_manual(values = c("red","green"))
</code>```

Body:
I've been trying to plot two histograms by using the fill aesthetic and a specific column with two levels. However, instead of displaying both desired histograms, my code displays one histogram with the whole data and another only for the second classification. I don't know if there is a problem in my syntax neither if this is some kind of tricky issue.

    library(tidyverse)

    db1 <- data.frame(type=rep("A",100),val=rnorm(n=100,mean=50,sd=10))
    db2 <- data.frame(type=rep("B",150),val=rnorm(n=150,mean=50,sd=10))
    dbf <- bind_rows(db1,db2)

    P1 <- ggplot(db1, aes(x=val)) + geom_histogram()
    P2 <- ggplot(db2, aes(x=val)) + geom_histogram()
    PF <- ggplot(dbf, aes(x=val)) + geom_histogram()

I want to get this, P1 and P2

ggplot(db1, aes(x=val)) + geom_histogram(fill="red", alpha=0.5) + geom_histogram(data=db2, aes(x=val),fill="green", alpha=0.5)

What I want

But the code I think should work, P1 and P2 with the fill aesthetic for column val

ggplot(dbf, aes(x=val)) + geom_histogram(aes(fill=type), alpha=0.5)

My code

Produces the combination of PF and P2

ggplot(dbf, aes(x=val)) + geom_histogram(fill="red", alpha=0.5) + geom_histogram(data=db2, aes(x=val),fill="green", alpha=0.5)

What I get

Any help or idea will be highly appreciated!

Body:
Is your goal to show the overlap via the color combination? I'm not sure how to force geom_histogram to show the overlap, but geom_density does do what you want. You can play with the bandwidth (bw) to show more or less detail.

dbf %>% ggplot() +
  aes(x = val, fill = type) +
  geom_density(alpha = .5, bw = .5) +
  scale_fill_manual(values = c("red","green"))


问:
Container range based constructor efficiency
While doing some test on an algorithm challenge website, I encountered this issue where my std::unordered_set was (somewhat marginally) slowing me down when using the range-base init:

void test(vector<int>& nums1) {
    unordered_set<int> set1(nums1.begin(), nums1.end());
}
```

<p>Is slower than</p>

<pre class="lang-cpp prettyprint-override"><code>vector<int> test(vector<int>& nums1) {
    unordered_set<int> set1;
    for (auto num : nums1) {
        set1.insert(num);
    }
}
</code>```

How to explain this?

Body:
While doing some test on an algorithm challenge website, I encountered this issue where my std::unordered_set was (somewhat marginally) slowing me down when using the range-base init:

void test(vector<int>& nums1) {
    unordered_set<int> set1(nums1.begin(), nums1.end());
}

Is slower than

vector<int> test(vector<int>& nums1) {
    unordered_set<int> set1;
    for (auto num : nums1) {
        set1.insert(num);
    }
}

How to explain this?

Body:
I made a simple benchmark:

--------------------------------------------------------------------
Benchmark                          Time             CPU   Iterations
--------------------------------------------------------------------
from_range<int>/256            13998 ns        13998 ns        50128
from_inserts<int>/256          16543 ns        16542 ns        41822

from_range<int>/512            27573 ns        27573 ns        25060
from_inserts<int>/512          36691 ns        36691 ns        19426

from_range<int>/4096          246584 ns       246584 ns         2881
from_inserts<int>/4096        335115 ns       335111 ns         2111

from_range<int>/32768        2401152 ns      2401123 ns          291
from_inserts<int>/32768      3398496 ns      3398509 ns          204

from_range<int>/262144      29351062 ns     29351113 ns           23
from_inserts<int>/262144    52871572 ns     52871542 ns           12

from_range<int>/1048576    245771472 ns    245772469 ns            3
from_inserts<int>/1048576  445421451 ns    445415603 ns            2

Source code

Compiled with g++ -O3 -m64 -march=native, GCC version 8.3.0.


答:
With heavy use of the pandas Series.str accessor:

```<code>df['NextWord'] = df['Text'].str.split('brca').str[1].str.split('\s').str[1]
df

                                            Text  Gene  NextWord
0  carcinoma brca positive completion mastectomy  brca  positive
1                    clinical brca gene mutation  brca      gene
2           carcinoma brca positive chemotherapy  brca  positive
</code>```

Title: Finding keyword +1 and making new column

Body:
With heavy use of the pandas Series.str accessor:

df['NextWord'] = df['Text'].str.split('brca').str[1].str.split('\s').str[1]
df

                                            Text  Gene  NextWord
0  carcinoma brca positive completion mastectomy  brca  positive
1                    clinical brca gene mutation  brca      gene
2           carcinoma brca positive chemotherapy  brca  positive


答:
i & i-1 turns off the lowest set bit in i (if there are any set). For example, consider i=200:

200 in binary is 1100 1000. (The space is inserted for visual convenience.)

To subtract one, the zeros cause us to “borrow” from the next position until we reach a one, producing 1100 0111. Note that, working from the right, all the zeros became ones, and the first one became a zero.

The & produces the bits that are set in both operands. Since i-1 changed all the bits up to the first one, those bits are clear in the &—none of the changed bits are the same in both i and i-1, so none of them is a one in both. The other ones in i, above the lowest one bit, are the same in both i and i-1, so they remain ones in i & i-1. The result of i & i-1 is 1100 0000.

1100 0000 is 1100 1000 with the lowest set bit turned off.

Then the % 3 is selecting which pole in Towers of Hanoi to use as the source. This is discussed in this question.

Similarly i | i-1 turns on all the low zeros in i, all the zeros up to the lowest one bit. Then (i | i-1) + 1 adds one to that. The result is the same as adding one to the lowest one bit in i. That is, the result is i + x, where x is the lowest bit set in i. Using our example value:

i is 1100 1000 and i-1 is 1100 0111.

i | i-1 is 1100 1111.

(i | i-1) + 1 is 1101 0000, which equals 1100 1000 + 0000 1000.

And again, the % 3 selects a pole.

Title: Using Bitwise Operators in C


问:
An Efficient way to Calculate loss function batchwise?
I am using autoencoders to do anomaly detection. So, I have finished training my model and now I want to calculate the reconstruction loss for each entry in the dataset. so that I can assign anomalies to data points with high reconstruction loss.

This is my current code to calculate the reconstruction loss
But this is really slow. By my estimation, it should take 5 hours to go through the dataset whereas training one epoch occurs in approx 55 mins.
 I feel that converting to tensor operation is bottlenecking the code, but I can't find a better way to do it.

I've tried changing the batch sizes but it does not make much of a difference. I have to use the convert to tensor part because K.eval is throwing an error if I do it normally.

python

```<code> for i in range(0, encoded_dataset.shape[0], batch_size):
    y_true = tf.convert_to_tensor(encoded_dataset[i:i+batch_size].values,
 np.float32)
     y_pred= tf.convert_to_tensor(ae1.predict(encoded_dataset[i:i+batch_size].values),
 np.float32)
    # Append the batch losses (numpy array) to the list
    reconstruction_loss_transaction.append(K.eval(loss_function( y_true, y_pred)))
</code>```

I was able to train in 55 mins per epoch. So I feel prediction should not take 5 hours per epoch. encoded_dataset is a variable that has the entire dataset in main memory as a data frame.
I am using Azure VM instance.
K.eval(loss_function(y_true,y_pred) is to find the loss for each row of the batch
So y_true will be of size (batch_size,2000) and so will y_pred
K.eval(loss_function(y_true,y_pred) will give me an output of

(batch_size,1) evaluating binary cross entropy on each row of y
  _true and y_pred

答:
Moved from comments:

My suspicion is that ae1.predict and K.eval(loss_function) are behaving in unexpected ways. ae1.predict should normally be used to output the loss function value as well as y_pred. When you create the model, specify that the loss value is another output (you can have a list of multiple outputs), then just call predict here once to get both y_pred the loss value in one call.

But I want the loss for each row . Won't the loss returned by the predict method be the mean loss for the entire batch?

The answer depends on how the loss function is implemented. Both ways produce perfectly valid and identical results in TF under the hood. You could average the loss over the batch before taking the gradient w.r.t. the loss, or take the gradient w.r.t. a vector of losses. The gradient operation in TF will perform the averaging of the losses for you if you use the latter approach (see SO articles on taking the per-sample gradient, it's actually hard to do).

If Keras implements the loss with reduce_mean built into the loss, you could just define your own loss. If you're using square loss, replacing 'mean_squared_error' with lambda y_true, y_pred: tf.square(y_pred - y_true). That would produce square error instead of MSE (no difference to the gradient), but look here for the variant including the mean.

In any case this produces a per sample loss so long as you don't use tf.reduce_mean, which is purely optional in the loss. Another option is to simply compute the loss separately from what you optimize for and make that an output of the model, also perfectly valid.

Body:
I am using autoencoders to do anomaly detection. So, I have finished training my model and now I want to calculate the reconstruction loss for each entry in the dataset. so that I can assign anomalies to data points with high reconstruction loss.

This is my current code to calculate the reconstruction loss
But this is really slow. By my estimation, it should take 5 hours to go through the dataset whereas training one epoch occurs in approx 55 mins.
 I feel that converting to tensor operation is bottlenecking the code, but I can't find a better way to do it.

I've tried changing the batch sizes but it does not make much of a difference. I have to use the convert to tensor part because K.eval is throwing an error if I do it normally.

python

 for i in range(0, encoded_dataset.shape[0], batch_size):
    y_true = tf.convert_to_tensor(encoded_dataset[i:i+batch_size].values,
 np.float32)
     y_pred= tf.convert_to_tensor(ae1.predict(encoded_dataset[i:i+batch_size].values),
 np.float32)
    # Append the batch losses (numpy array) to the list
    reconstruction_loss_transaction.append(K.eval(loss_function( y_true, y_pred)))

I was able to train in 55 mins per epoch. So I feel prediction should not take 5 hours per epoch. encoded_dataset is a variable that has the entire dataset in main memory as a data frame.
I am using Azure VM instance.
K.eval(loss_function(y_true,y_pred) is to find the loss for each row of the batch
So y_true will be of size (batch_size,2000) and so will y_pred
K.eval(loss_function(y_true,y_pred) will give me an output of

(batch_size,1) evaluating binary cross entropy on each row of y
  _true and y_pred


问:
How to push object into an object array in Angular 6?
I have an empty object array like this groupList:any = {} and now I want to push an object into it. I am trying to name and description as an object.

答:
app.component.ts

```<code>declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    groupList:any = [];
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

 getPrev(){

     this.array.forEach((item, index) => {

  this.groupList.push(item.id);

});
console.log(this.groupList);
 }

}
</code>```

app.component.html

```<code><button (click) ="getVal()">Previous Value</button>
</code>```

Body:
app.component.ts

declare var require: any;
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
    groupList:any = [];
    arrayVal:any;
    currentVal : any;
  title = 'projectchart';
  public array = [{"id":1},{"id":3},{"id":5}];

 getPrev(){

     this.array.forEach((item, index) => {

  this.groupList.push(item.id);

});
console.log(this.groupList);
 }

}

app.component.html

<button (click) ="getVal()">Previous Value</button>


问:
How to add half link in href?
I want to create half-links in href means, for example, suppose I want to create code to check Alexa ranking so when user come on my website they enter their website URL to check rank so in this https://www.alexa.com/siteinfo/ will come automatically and the URL that enters by the user will add after this link.</p>

答:
You can keep the result from the user in variable and concatenate URL like this:

```<code> https://www.alexa.com/siteinfo/ + userUrl
</code>```

when the userUrl can be - userUrl = 'walla.com' for example

Title: How to add half link in href?

Body:
You can keep the result from the user in variable and concatenate URL like this:

 https://www.alexa.com/siteinfo/ + userUrl

when the userUrl can be - userUrl = 'walla.com' for example


问:
Request for suggestion to develop GWT based Web 2.0 application
I did Web 2.0 applications with Flex. This time, I wish to learn and develop with GWT.

Inspired by JBPM console application, I'm thinking about using gwt-mosiac for user interface(better suggestions are most welcome and I'm thankful).

For example, one of the stacks in Flex is [Flex+Parlsey] - [BlazeDS-Spring/JPA] - MySql. With GWT ?

Kindly suggest the stack or system architecture based on your experience to develop Web 2.0 application with GWT.

答:
I use EJB+JPA on the server side and GWT + Ext GWT (aka GXT) for the UI. It has some downsides (as almost everything), but is well polished, and has a great selection of ready to use components.

Of course it all depends of what are you trying to achieve. If it's supposed to be a "normal" web page, consider jquery or plain GWT. If it's supposed to be RIA (lots of forms, complex interface, etc.) - an additional ui library might be useful. In my opinion: the more code is on the client side, the more you need GWT ;)


问:
Restrict checkout shipping state in Woocommerce
On shipping to the US I am trying to restrict the shipping address to one state (Kentucky), the code below works on WooCommerce 3.5.8, but as soon as update WooCommerce it stops working. I have tried the different increments (3.6.0 beta, rc1, etc) and everything after 3.5.8 causes it to stop working (it is showing all of the states instead of just Kentucky).

I have tried searching to see if that option has changed or been deprecated but I wasn't able to find it or another way of doing it. I have tried some other code  I found here too but that didn't work either.

```<code> add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields )
{
    $fields['shipping']['shipping_state']['options'] = array('KY' => 'Kentucky' );

    return $fields;
}
</code>```

Is there an issue with the above or some change I need to make?

答:
The following will set a default pre-defined shipping country and state, displaying the shipping state select field as disabled (read only) with "Kentucky" selected value:

```<code>add_filter( 'woocommerce_shipping_fields' , 'custom_shipping_state_fields', 100, 1 );
function custom_shipping_state_fields( $fields ) {
    WC()->customer->set_shipping_country('US'); // Set shipping country
    WC()->customer->set_shipping_state('KY'); // Set shipping state

    $fields['shipping_state']['type'] = 'select';
    $fields['shipping_state']['options'] = ['KY' => __('Kentucky', 'WooCommerce')];
    $fields['shipping_state']['default'] = 'KY';
    $fields['shipping_state']['input_class'] = [];
    $fields['shipping_state']['custom_attributes'] = ['disabled' => 'disabled'];

    return $fields;
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Body:
On shipping to the US I am trying to restrict the shipping address to one state (Kentucky), the code below works on WooCommerce 3.5.8, but as soon as update WooCommerce it stops working. I have tried the different increments (3.6.0 beta, rc1, etc) and everything after 3.5.8 causes it to stop working (it is showing all of the states instead of just Kentucky).

I have tried searching to see if that option has changed or been deprecated but I wasn't able to find it or another way of doing it. I have tried some other code  I found here too but that didn't work either.

 add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields )
{
    $fields['shipping']['shipping_state']['options'] = array('KY' => 'Kentucky' );

    return $fields;
}

Is there an issue with the above or some change I need to make?

Body:
The following will set a default pre-defined shipping country and state, displaying the shipping state select field as disabled (read only) with "Kentucky" selected value:

add_filter( 'woocommerce_shipping_fields' , 'custom_shipping_state_fields', 100, 1 );
function custom_shipping_state_fields( $fields ) {
    WC()->customer->set_shipping_country('US'); // Set shipping country
    WC()->customer->set_shipping_state('KY'); // Set shipping state

    $fields['shipping_state']['type'] = 'select';
    $fields['shipping_state']['options'] = ['KY' => __('Kentucky', 'WooCommerce')];
    $fields['shipping_state']['default'] = 'KY';
    $fields['shipping_state']['input_class'] = [];
    $fields['shipping_state']['custom_attributes'] = ['disabled' => 'disabled'];

    return $fields;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.


问:
Read a fixed amount of characters using fgets in C
I'm trying to use the function fgets() in C to read 8 characters, and has to be 8 characters from stdin.

So far, I've got this

```<code>    char HEX[9];
    while (fgets(HEX, 8, stdin) != NULL)
    {
      if (HEX[8] == '\0')
      {
        printf("GOOD\n");
        break;
      }
      else
      {
        printf("Not 8 characters");
      }
    }
</code>```

But it's not working. Any ideas? Also tried using if (strlen(HEX) > 8) but neither.

Thanks in advance.

答:
fgets() store a \n on the 8th position in your case.

So , You have two options,

Check for \0 at 9th position.

Replace \n on the 8th position with \0 then check for \0 on the 8th position.

Body:
I'm trying to use the function fgets() in C to read 8 characters, and has to be 8 characters from stdin.

So far, I've got this

    char HEX[9];
    while (fgets(HEX, 8, stdin) != NULL)
    {
      if (HEX[8] == '\0')
      {
        printf("GOOD\n");
        break;
      }
      else
      {
        printf("Not 8 characters");
      }
    }

But it's not working. Any ideas? Also tried using if (strlen(HEX) > 8) but neither.

Thanks in advance.


问:
After choosing K-components in PCA how do we find out which components(names of the columns) have algorithm selected?
I am new to Data Science and I need some help to understand PCA.I know that each of columns constitute one axis,but when PCA is done and components are reduced to some k value,How to know which all columns got selected?</p>

答:
You have to look at Eigenvectors of the PCA. Each Eigenvalues are the "force" of each "new axis" and the eigenvector provide the linear combination of your original features.

With scikit-learn, you should look at the attribute components_

```<code>import numpy as np
from sklearn.decomposition import PCA
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=2)
pca.fit(X)
print(pca.components_) # << eigenvector matrix
</code>```

Body:
You have to look at Eigenvectors of the PCA. Each Eigenvalues are the "force" of each "new axis" and the eigenvector provide the linear combination of your original features.

With scikit-learn, you should look at the attribute components_

import numpy as np
from sklearn.decomposition import PCA
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=2)
pca.fit(X)
print(pca.components_) # << eigenvector matrix


问:
Function not doing anything after clicking on button (aspx page)
I have problem with buttons, I typed alert("") to be sure if it enters to function or not,I discovered that it enters into function after I click on button and the alert works fine but, anything else inside function does not work neither ajax nor any simple jquery code. I will add the code to be more clarified.

for example these buttons below

```<code><button type="button" id="submitX" class="btn btn-primary">Submit</button>
<button type="submit" id="cancelX" class="btn btn-default">Cancel</button>
</code>```

This javascript code

```<code>    $(document).ready(function () {
    $(document).on("click", "#cancelX", function (event) {
          alert('cancel function');
            window.location.href = "www.test.com";
         });
    $(document).on("click", "#submitX", function (event) {
           alert('submit function');

var Details  = $('#Detail').summernote('code');
var params = [];
params.push({ name: "CreatedBy", value: $('#Email').val() });
params.push({ name: "Detail", value: Details});
var apiURL = "<%= ResolveUrl("~/api/Submit/") %>";
$.ajax({
url: apiURL,
data: params,
type: "POST",
success: function (data, textStatus, jqXHR) {
window.location.href = "www.test.com";
},
error: function (err) {
swal({
text: "An error occured.",
icon: "error"
});
}
})

  });
    });
</code>```

why are both buttons or functions not working properly ? did I do anything wrong here ?

答:
try changing your 'button' tag to 'input' tag as you are using the type attribute.

Hope it works.

Body:
I have problem with buttons, I typed alert("") to be sure if it enters to function or not,I discovered that it enters into function after I click on button and the alert works fine but, anything else inside function does not work neither ajax nor any simple jquery code. I will add the code to be more clarified.

for example these buttons below

<button type="button" id="submitX" class="btn btn-primary">Submit</button>
<button type="submit" id="cancelX" class="btn btn-default">Cancel</button>

This javascript code

    $(document).ready(function () {
    $(document).on("click", "#cancelX", function (event) {
          alert('cancel function');
            window.location.href = "www.test.com";
         });
    $(document).on("click", "#submitX", function (event) {
           alert('submit function');

var Details  = $('#Detail').summernote('code');
var params = [];
params.push({ name: "CreatedBy", value: $('#Email').val() });
params.push({ name: "Detail", value: Details});
var apiURL = "<%= ResolveUrl("~/api/Submit/") %>";
$.ajax({
url: apiURL,
data: params,
type: "POST",
success: function (data, textStatus, jqXHR) {
window.location.href = "www.test.com";
},
error: function (err) {
swal({
text: "An error occured.",
icon: "error"
});
}
})

  });
    });

why are both buttons or functions not working properly ? did I do anything wrong here ?


问:
UIView Expand to Content inside
I have a function that returns a UIView. I want to dynamically change the size of my UIView(fullView) based on how much text is shown in the UITextView (thirdTextView). I currently have my height set at 200. How can I achieve a 'dynamic height'?

EDIT: Updated code so far. Is only working when a subView is added to the View. I don't want this...

```<code>func returnView(text1: String, text2: String) -> UIView {

    let fullView = UIView()

    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)
    fullView.translatesAutoresizingMaskIntoConstraints = false
    let firstButton = UIButton()
    firstButton.translatesAutoresizingMaskIntoConstraints = false
    let secondButton = UIButton()
    secondButton.translatesAutoresizingMaskIntoConstraints = false
    let thirdTextView = UITextView()
    thirdTextView.translatesAutoresizingMaskIntoConstraints = false
    thirdTextView.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
    thirdTextView.backgroundColor = .clear
    thirdTextView.isScrollEnabled = false

    firstButton.setTitle("Button1", for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    let descriptionBarStackView =  UIStackView(arrangedSubviews: [firstButton, UIView() ,secondButton])
    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill

    let viewWithStackViews = UIStackView(arrangedSubviews: [descriptionBarStackView, thirdTextView])
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.axis = .vertical
    viewWithStackViews.layoutMargins = UIEdgeInsets(top: 15, left: 10, bottom: 10, right:10)
    viewWithStackViews.isLayoutMarginsRelativeArrangement = true
    fullView.addSubview(viewWithStackViews)

//        view.addSubview(fullView)

    fullView.leadingAnchor.constraint(equalTo: viewWithStackViews.leadingAnchor).isActive = true
    fullView.trailingAnchor.constraint(equalTo: viewWithStackViews.trailingAnchor).isActive = true
    fullView.topAnchor.constraint(equalTo: viewWithStackViews.topAnchor).isActive = true
    fullView.bottomAnchor.constraint(equalTo: viewWithStackViews.bottomAnchor).isActive = true

    fullView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -10).isActive = true
    fullView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    fullView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

    fullView.layer.cornerRadius = 5

    return fullView
}
</code>```

答:
Just set the width anchor, and it will dynamically expand to content size for height.</p>

```<code>thirdTextView.widthAnchor.constraint(equalToConstant: 128.0).isActive = true
</code>```

Title: UIView Expand to Content inside

Body:
I have a function that returns a UIView. I want to dynamically change the size of my UIView(fullView) based on how much text is shown in the UITextView (thirdTextView). I currently have my height set at 200. How can I achieve a 'dynamic height'?

EDIT: Updated code so far. Is only working when a subView is added to the View. I don't want this...

func returnView(text1: String, text2: String) -> UIView {

    let fullView = UIView()

    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)
    fullView.translatesAutoresizingMaskIntoConstraints = false
    let firstButton = UIButton()
    firstButton.translatesAutoresizingMaskIntoConstraints = false
    let secondButton = UIButton()
    secondButton.translatesAutoresizingMaskIntoConstraints = false
    let thirdTextView = UITextView()
    thirdTextView.translatesAutoresizingMaskIntoConstraints = false
    thirdTextView.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
    thirdTextView.backgroundColor = .clear
    thirdTextView.isScrollEnabled = false

    firstButton.setTitle("Button1", for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    let descriptionBarStackView =  UIStackView(arrangedSubviews: [firstButton, UIView() ,secondButton])
    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill

    let viewWithStackViews = UIStackView(arrangedSubviews: [descriptionBarStackView, thirdTextView])
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.axis = .vertical
    viewWithStackViews.layoutMargins = UIEdgeInsets(top: 15, left: 10, bottom: 10, right:10)
    viewWithStackViews.isLayoutMarginsRelativeArrangement = true
    fullView.addSubview(viewWithStackViews)

//        view.addSubview(fullView)

    fullView.leadingAnchor.constraint(equalTo: viewWithStackViews.leadingAnchor).isActive = true
    fullView.trailingAnchor.constraint(equalTo: viewWithStackViews.trailingAnchor).isActive = true
    fullView.topAnchor.constraint(equalTo: viewWithStackViews.topAnchor).isActive = true
    fullView.bottomAnchor.constraint(equalTo: viewWithStackViews.bottomAnchor).isActive = true

    fullView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -10).isActive = true
    fullView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    fullView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

    fullView.layer.cornerRadius = 5

    return fullView
}

Body:
Just set the width anchor, and it will dynamically expand to content size for height.

thirdTextView.widthAnchor.constraint(equalToConstant: 128.0).isActive = true


问:
Click on item Hide Icon dont refresh screen
In Web/List Module when clicking for example on Hide content Element the icon is changing from "actions-edit-hide" to "spinner-circle-dark", but not into "actions-edit-unhide". When Refreshing the page manually the right icon is shown. It seems that the AJAX Call doesn't refresh the list. This happens also by other actions, for example when deleting some Records.

We are Running TYPO3 8.7 LTS with MySQL 5.7.26 und PHP 7.2.17-0ubuntu0.18.04.1

When looking in my Browsers Network Analyse, i see the following call:
https://2019.mbaec.de/typo3/index.php?ajaxID=%2Fajax%2Frecord%2Fprocess&ajaxToken=976157b65a4042508b6b375cf09a50ea17110b90&data[pages][376][hidden]=0

Header:
Host: 2019.mbaec.de
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0
Accept: application/json, text/javascript, /; q=0.01
Accept-Language: fr,de;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate, br
Referer: https://2019.mbaec.de/typo3/index.php?M=web_list&moduleToken=73ba2ec59dbfe41e0d9e1b38af45dfdebd5b2b89&id=211&
X-Requested-With: XMLHttpRequest
Connection: keep-alive
Cookie: be_lastLoginProvider=1433416747; be_typo_user=5d6f974af357ad400e1380459174c539; Typo3InstallTool=vgehc4q4fs06ph6jn0f7pmg4rd

Result Header:
HTTP/1.1 200 OK
Date: Mon, 27 May 2019 13:48:15 GMT
Server: Apache/2.4.29 (Ubuntu)
Expires: 0
Cache-Control: no-cache, must-revalidate
Pragma: no-cache
X-Frame-Options: SAMEORIGIN
X-JSON: true
Last-Modified: Mon, 27 May 2019 13:48:15 GMT
Vary: Accept-Encoding
Content-Encoding: gzip
Access-Control-Expose-Headers: Content-Length, X-JSON
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Accept, Contet-Type, X-Forwarded-For, X-Prototype-Version, X-Requested-With
Access-Control-Allow-Methods: GET, OPTIONS, PUT, POST
X-UA-Compatible: IE=edge
X-Content-Type-Options: nosniff
Content-Length: 64
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8

Result:
{"redirect":"","messages":[],"hasErrors":true}

答: This issue was fixed with 8.7.26 (2019-05-09 82429eb0b0 [BUGFIX] Set hasErrors depending on existing errors). Are you sure all your opcode cache  was emptied and that you're really on 8.7.26? 8.7.25 introduced that error as a regression. See https://forge.typo3.org/issues/87971</p>


问:
iPhone : How to check whether a substring exists in a string?
I have some string name and I want to compare whether that string contains substring like "_thumb.png". </p>

答:
You can try this:

```<code>NSString *originalString;
NSString *compareString;
</code>```

Let your string be stored in originalString and the substring that you want to compare is stored in compareString.

```<code>if ([originalString rangeOfString:compareString].location==NSNotFound)
{
    NSLog(@"Substring Not Found");
}
else
{
    NSLog(@"Substring Found Successfully");
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can try this:

NSString *originalString;
NSString *compareString;

Let your string be stored in originalString and the substring that you want to compare is stored in compareString.

if ([originalString rangeOfString:compareString].location==NSNotFound)
{
    NSLog(@"Substring Not Found");
}
else
{
    NSLog(@"Substring Found Successfully");
}


问:
Xcode/iOS xctest - Build input file cannot be found
I created the first unit test target in our iOS application by simply clicking through the plus icon inside the test tab on the left navigator.
(The target to be tested is set to the main application)

The unit test target created itself successfully but when I try to run the pre-generated tests, it outputs an error message. The error message displays that the build input file cannot be found. More specifically, the file /Plugins/XXXTests.xctest/XXXTests cannot be found. I double checked and in fact that file is not in that directory.

While I could not find anything similar to this problem, I tried everything that was close to it but nothing seemed to fix problem.

Any help would be greatly appreciated!

答:
Do you have it set properly in schemes?

Go to Product -> Scheme -> Edit Scheme -> Test and check, if your test target is properly added to the correct scheme. It should look something like this:


问:
Why is my Laravel Memcache taking too long to retrieve data?
I am making an simple larvel application to show memcached use. The Os i am using is ubuntu. The records in the database are 50k.

I successfully installed memcache and saved data in it but the problem is that when i am retrieving data from memcache its taking too long same as a retrival from database would. Kindly let me know what is the issue. I have installed memcache on windows as well but the issue is same on windows as well.

```<code>/**
 * Created by PhpStorm.
 * User: Delll
 * Date: 14-Sep-18
 * Time: 2:44 AM
 */

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class User_controller extends Controller{

    public function index(){
        $memcache = 'Using memcache';

        $users = Cache::remember("key",6999,function(){
            return DB::table('users')->get();
        });
//        Cache::pull('key');

        $val= Cache::has('key');
        if($val !=null){
            echo "Found ".$val;
        }else{
            echo "Not Found ".$val;
        }

        return view('pages.home',compact('users','memcache'));
    }

    public function remove(){
        $value = Cache::pull('key');
        return $value;
    }

}
</code>```

The result from memcache should be retrieved faster than database.

答:
Performance issues with memcached are tough to debug (at least for me). I would suggest using the user space strace tool to get some insight into what exactly is causing the delay (read? write? something else?)

here is an example of getting some info:

```<code> strace -p {php_process_id} -k -r -t -i -T -q  -v -y -yy -C -d -o strace_output.log
</code>```

instead of php process id put there the root php-fpm process id and see what you get.

Body:
I am making an simple larvel application to show memcached use. The Os i am using is ubuntu. The records in the database are 50k.

I successfully installed memcache and saved data in it but the problem is that when i am retrieving data from memcache its taking too long same as a retrival from database would. Kindly let me know what is the issue. I have installed memcache on windows as well but the issue is same on windows as well.

/**
 * Created by PhpStorm.
 * User: Delll
 * Date: 14-Sep-18
 * Time: 2:44 AM
 */

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class User_controller extends Controller{

    public function index(){
        $memcache = 'Using memcache';

        $users = Cache::remember("key",6999,function(){
            return DB::table('users')->get();
        });
//        Cache::pull('key');

        $val= Cache::has('key');
        if($val !=null){
            echo "Found ".$val;
        }else{
            echo "Not Found ".$val;
        }

        return view('pages.home',compact('users','memcache'));
    }

    public function remove(){
        $value = Cache::pull('key');
        return $value;
    }

}

The result from memcache should be retrieved faster than database.

Body:
Performance issues with memcached are tough to debug (at least for me). I would suggest using the user space strace tool to get some insight into what exactly is causing the delay (read? write? something else?)

here is an example of getting some info:

 strace -p {php_process_id} -k -r -t -i -T -q  -v -y -yy -C -d -o strace_output.log

instead of php process id put there the root php-fpm process id and see what you get.


问:
RegEx for matching special patterns
I'm trying to match a String like this:62.00|LQ+2*2,FP,MD*3 "Description"
Where the decimal value is 2 digits optional, each user is characterized by two Chars and it can be followed by

(\+[\d]+)? or (\*[\d]+)? or none, or both, or both in different order

like:

LQ*2+4 | LQ+4*2 | LQ*2 | LQ+8 | LQ

Description is also optional

What i have tried is this:

```<code>Pattern.compile("^(?<number>[\\d]+(\\.[\\d]{2})?)\\|(?<users>([A-Z]{2}){1}(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?))((,[A-Z]{2})(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?)))*)(\\s\\\"(?<message>.+)\\\")?$");
</code>```

I need to get all the users so i can split them by ',' and then further regex my way into it.But i cannot grab anything out of it.The desired output from

62.00|LQ+2*2,FP,MD*3 "Description"

Should be:

62.00

LQ+2*2,FP,MD*3

Description

Accepted inputs should be of these kind:

62.00|LQ+2*2,FP,MD*3

30|LQ "Burgers"

35.15|LQ*2,FP+2*4,MD*3+4 "Potatoes"

35.15|LQ,FP,MD

答:
I'm guessing that we have several optional groups here, that might not be a problem. The problem I'm having is that I'm not quite sure what would be the range of our inputs and what might be desired outputs.

RegEx 1

If we are just matching everything, that I'm guessing, we might like to start with something similar to:

```<code>[0-9]+(\.[0-9]{2})?\|[A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,[A-Z]{2},[A-Z]{2}[+*]?([0-9]+)?(\s+"Description")?
</code>```

Here, we simply add a ? after every sub-expression that we wish to have it optional, then we use char lists and quantifiers, and start swiping everything from left to right, to cover all inputs.

If we like to capture, then we simply wrap any part that we want captured with a capturing group ().

Demo

Test

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "[0-9]+(\\.[0-9]{2})?\\|[A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,[A-Z]{2},[A-Z]{2}[+*]?([0-9]+)?(\\s+\"Description\")?";
final String string = "62.00|LQ+2*2,FP,MD*3 \"Description\"\n"
     + "62|LQ+2*2,FP,MD*3 \"Description\"\n"
     + "62|LQ+2*2,FP,MD*3\n"
     + "62|LQ*2,FP,MD*3\n"
     + "62|LQ+8,FP,MD*3\n"
     + "62|LQ,FP,MD";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}
</code>```

RegEx 2

If we wish to output three groups that is listed:

```<code>([0-9]+(\.[0-9]{2})?)\|([A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,[A-Z]{2},[A-Z]{2}[+*]?([0-9]+)?)(\s+"Description")?
</code>```

Demo 2

Test

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "([0-9]+(\\.[0-9]{2})?)\\|([A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,[A-Z]{2},[A-Z]{2}[+*]?([0-9]+)?)(\\s+\"Description\")?";
final String string = "62.00|LQ+2*2,FP,MD*3 \"Description\"\n"
     + "62|LQ+2*2,FP,MD*3 \"Description\"\n"
     + "62|LQ+2*2,FP,MD*3\n"
     + "62|LQ*2,FP,MD*3\n"
     + "62|LQ+8,FP,MD*3\n"
     + "62|LQ,FP,MD";
final String subst = "\\1\\n\\3\\n\\7";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);
</code>```

RegEx 3

Based on updated desired output, this might work:

```<code>([0-9]+(\.[0-9]{2})?)\|((?:[A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,?)(?:[A-Z]{2}[+*]?([0-9]+)?[*+]?([0-9]+)?,?[A-Z]{2}?[*+]?([0-9]+)?[+*]?([0-9]+)?)?)(\s+"(.+?)")?
</code>```

DEMO

Title: RegEx for matching special patterns

Body:
I'm trying to match a String like this:62.00|LQ+2*2,FP,MD*3 "Description"
Where the decimal value is 2 digits optional, each user is characterized by two Chars and it can be followed by

(\+[\d]+)? or (\*[\d]+)? or none, or both, or both in different order

like:

LQ*2+4 | LQ+4*2 | LQ*2 | LQ+8 | LQ

Description is also optional

What i have tried is this:

Pattern.compile("^(?<number>[\\d]+(\\.[\\d]{2})?)\\|(?<users>([A-Z]{2}){1}(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?))((,[A-Z]{2})(((\\+[\\d]+)?(\\*[\\d]+)?)|((\\+[\\d]+)?(\\*[\\d]+)?)))*)(\\s\\\"(?<message>.+)\\\")?$");

I need to get all the users so i can split them by ',' and then further regex my way into it.But i cannot grab anything out of it.The desired output from

62.00|LQ+2*2,FP,MD*3 "Description"

Should be:

62.00

LQ+2*2,FP,MD*3

Description

Accepted inputs should be of these kind:

62.00|LQ+2*2,FP,MD*3

30|LQ "Burgers"

35.15|LQ*2,FP+2*4,MD*3+4 "Potatoes"

35.15|LQ,FP,MD

Body:
I'm guessing that we have several optional groups here, that might not be a problem. The problem I'm having is that I'm not quite sure what would be the range of our inputs and what might be desired outputs.

RegEx 1

If we are just matching everything, that I'm guessing, we might like to start with something similar to:

[0-9]+(\.[0-9]{2})?\|[A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,[A-Z]{2},[A-Z]{2}[+*]?([0-9]+)?(\s+"Description")?

Here, we simply add a ? after every sub-expression that we wish to have it optional, then we use char lists and quantifiers, and start swiping everything from left to right, to cover all inputs.

If we like to capture, then we simply wrap any part that we want captured with a capturing group ().

Demo

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "[0-9]+(\\.[0-9]{2})?\\|[A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,[A-Z]{2},[A-Z]{2}[+*]?([0-9]+)?(\\s+\"Description\")?";
final String string = "62.00|LQ+2*2,FP,MD*3 \"Description\"\n"
     + "62|LQ+2*2,FP,MD*3 \"Description\"\n"
     + "62|LQ+2*2,FP,MD*3\n"
     + "62|LQ*2,FP,MD*3\n"
     + "62|LQ+8,FP,MD*3\n"
     + "62|LQ,FP,MD";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

RegEx 2

If we wish to output three groups that is listed:

([0-9]+(\.[0-9]{2})?)\|([A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,[A-Z]{2},[A-Z]{2}[+*]?([0-9]+)?)(\s+"Description")?

Demo 2

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "([0-9]+(\\.[0-9]{2})?)\\|([A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,[A-Z]{2},[A-Z]{2}[+*]?([0-9]+)?)(\\s+\"Description\")?";
final String string = "62.00|LQ+2*2,FP,MD*3 \"Description\"\n"
     + "62|LQ+2*2,FP,MD*3 \"Description\"\n"
     + "62|LQ+2*2,FP,MD*3\n"
     + "62|LQ*2,FP,MD*3\n"
     + "62|LQ+8,FP,MD*3\n"
     + "62|LQ,FP,MD";
final String subst = "\\1\\n\\3\\n\\7";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);

RegEx 3

Based on updated desired output, this might work:

([0-9]+(\.[0-9]{2})?)\|((?:[A-Z]{2}[+*]?([0-9]+)?[+*]?([0-9]+)?,?)(?:[A-Z]{2}[+*]?([0-9]+)?[*+]?([0-9]+)?,?[A-Z]{2}?[*+]?([0-9]+)?[+*]?([0-9]+)?)?)(\s+"(.+?)")?

DEMO


问:
what is the procedure in SQL server to not execute anything(T SQL commands) but outputs the commands it would execute
what is the procedure in SQL server to not execute anything(T SQL commands) but outputs the commands it would execute</p>

答:
There isn't one unless you are using dynamic SQL where you'd use PRINT

You can see a stored proc definition but this won't show you any actual parameter values etc


问:
EditText with bottom border only
I am trying to make a custom edit text that has only a bottom border. I have tried this code and set it as background:

```<code><item android:gravity="bottom">
        <shape android:shape="line">
            <stroke android:width="1dp" android:color="@color/lightGray"/>
            <padding android:left="12dp" android:right="12dp" android:top="12dp" android:bottom="12dp" />
        </shape>
    </item>
</code>```

and the border is exactly how I want it but it is placed in the middle of the edit text and not at the bottom. How can I solve this?

答:
Try this.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-10dp" android:left="-2dp" android:right="-2dp">
        <shape>
            <solid android:color="@android:color/transparent"/>
            <stroke android:color="@color/lightGray" android:width="1dp"/>
        </shape>
    </item>
</layer-list>
</code>```

Title: EditText with bottom border only

Body:
I am trying to make a custom edit text that has only a bottom border. I have tried this code and set it as background:

<item android:gravity="bottom">
        <shape android:shape="line">
            <stroke android:width="1dp" android:color="@color/lightGray"/>
            <padding android:left="12dp" android:right="12dp" android:top="12dp" android:bottom="12dp" />
        </shape>
    </item>

and the border is exactly how I want it but it is placed in the middle of the edit text and not at the bottom. How can I solve this?

Body:
Try this.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-10dp" android:left="-2dp" android:right="-2dp">
        <shape>
            <solid android:color="@android:color/transparent"/>
            <stroke android:color="@color/lightGray" android:width="1dp"/>
        </shape>
    </item>
</layer-list>


问:
Vue router hooks in NUXT middleware
I am trying to close down the sidebar when my user changes route

```<code>export default function({ store }) {
    store.commit("TOGGLE_SIDEBAR");
}
</code>```

The issue is this calls it as soon as the site loads

I try this

```<code>export default function({ app, store }) {
  app.router.beforeEach((to, next) => {
    store.commit("TOGGLE_SIDEBAR");
    next();
  });
}

</code>```

I get next is not a function.

How do I get this working?

答:
As stated in the documentation router.beforeEach(...) expects a function with 3 arguments : to, from and next.

As you've passed only two arguments, the next argument you are trying to call is in fact the from Route.

Add a third parameter like below :

```<code>export default function({ app, store }) {
  app.router.beforeEach((to, from, next) => {
    store.commit("TOGGLE_SIDEBAR");
    next();
  });
}
</code>```

Title: Vue router hooks in NUXT middleware

Body:
I am trying to close down the sidebar when my user changes route

export default function({ store }) {
    store.commit("TOGGLE_SIDEBAR");
}

The issue is this calls it as soon as the site loads

I try this

export default function({ app, store }) {
  app.router.beforeEach((to, next) => {
    store.commit("TOGGLE_SIDEBAR");
    next();
  });
}

I get next is not a function.

How do I get this working?

Body:
As stated in the documentation router.beforeEach(...) expects a function with 3 arguments : to, from and next.

As you've passed only two arguments, the next argument you are trying to call is in fact the from Route.

Add a third parameter like below :

export default function({ app, store }) {
  app.router.beforeEach((to, from, next) => {
    store.commit("TOGGLE_SIDEBAR");
    next();
  });
}


问:
How to find similarity between two list of strings using doc2vec?
I have a list of strings like below. I would like to see similarity between list1 and list2 using Doc2Vec.</p>

```<code>list1 = [['i','love','machine','learning','its','awesome'],['i', 'love', 'coding', 'in', 'python'],['i', 'love', 'building', 'chatbots']]
list2 = ['i', 'love', 'chatbots']
</code>```

答:
If you're using the Doc2Vec implementation in the gensim library, there are intro notebooks that cover this. See for example the file doc2vec-lee.ipynb, which is inside the gensim docs/notebooks directory (where you can and sould run it locally), or viewable online at:

https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/doc2vec-lee.ipynb

Note that:

you'll need a model trained on far more data - ideally tens-of-thousands or more texts, each text being at least a sentence

if the two texts you want to compare were part of your training set, you can retrieve the learned doc-vectors from the model

if the two texts you want to compare are not part of the training set, you can infer doc-vectors for them, using the model, as is shown in that notebook

Body:
I have a list of strings like below. I would like to see similarity between list1 and list2 using Doc2Vec.

list1 = [['i','love','machine','learning','its','awesome'],['i', 'love', 'coding', 'in', 'python'],['i', 'love', 'building', 'chatbots']]
list2 = ['i', 'love', 'chatbots']


问:
ASP.net Core WebAPI Routing order parameter condition
I've got have the following controller:

```<code>[Route("xapi/statements")] << -- NOTICE THE ROUTE
[Produces("application/json")]
public class StatementsController : ApiControllerBase
</code>```

With he following actions

```<code>/// <summary>
/// Stores a single Statement with the given id.
/// </summary>
/// <param name="statementId"></param>
/// <param name="statement"></param>
/// <returns></returns>
[AcceptVerbs("PUT", "POST", Order = 1)]
public async Task<IActionResult> PutStatement([FromQuery]Guid statementId, [ModelBinder(typeof(StatementPutModelBinder))]Statement statement)
{

    await _mediator.Send(PutStatementCommand.Create(statementId, statement));

    return NoContent();
}

/// <summary>
/// Create statement(s) with attachment(s)
/// </summary>
/// <param name="model"></param>
/// <returns>Array of Statement id(s) (UUID) in the same order as the corresponding stored Statements.</returns>
[HttpPost(Order = 2)]
[Produces("application/json")]
public async Task<ActionResult<ICollection<Guid>>> PostStatements(StatementsPostModelBinder model)
{
    ICollection<Guid> guids = await _mediator.Send(CreateStatementsCommand.Create(model.Statements));

    return Ok(guids);
}
</code>```

The actions are executed in the following order:
1. PutStatement
2. PostStatements

But PutStatement should only be triggered if the statementId parameter is provided. This is not the case.

I'm using 2 model binders to parse the content of the streams as either application/json or multipart/form-data if the statements have any attachments.
1. StatementPutModelBinder
2. StatementsPostModelBinder

How do i prevent the action from being excuted if the statementId parameter is not provided?
Eg. /xapi/statements/ => Hits PutStatement

答: I did not find a answer for my own question, but i made a mistake and was under the impression that the xAPI statements resource should allow statementId as a parameter for POST requests. Therefore i do not have the issue any more, which started my question.</p>

Body:
I've got have the following controller:

[Route("xapi/statements")] << -- NOTICE THE ROUTE
[Produces("application/json")]
public class StatementsController : ApiControllerBase

With he following actions

///
/// Stores a single Statement with the given id.
///
/// <param name="statementId"></param>
/// <param name="statement"></param>
/// <returns></returns>
[AcceptVerbs("PUT", "POST", Order = 1)]
public async Task<IActionResult> PutStatement([FromQuery]Guid statementId, [ModelBinder(typeof(StatementPutModelBinder))]Statement statement)
{

    await _mediator.Send(PutStatementCommand.Create(statementId, statement));

    return NoContent();
}

///
/// Create statement(s) with attachment(s)
///
/// <param name="model"></param>
/// <returns>Array of Statement id(s) (UUID) in the same order as the corresponding stored Statements.</returns>
[HttpPost(Order = 2)]
[Produces("application/json")]
public async Task<ActionResult<ICollection<Guid>>> PostStatements(StatementsPostModelBinder model)
{
    ICollection<Guid> guids = await _mediator.Send(CreateStatementsCommand.Create(model.Statements));

    return Ok(guids);
}

The actions are executed in the following order:
1. PutStatement
2. PostStatements

But PutStatement should only be triggered if the statementId parameter is provided. This is not the case.

I'm using 2 model binders to parse the content of the streams as either application/json or multipart/form-data if the statements have any attachments.
1. StatementPutModelBinder
2. StatementsPostModelBinder

How do i prevent the action from being excuted if the statementId parameter is not provided?
Eg. /xapi/statements/ => Hits PutStatement


问:
Make container go slightly above the footer
I have a container with mainly all the content of the page with a fixed width (so not 100%) and I have a footer at the bottom that is width:100%.

I want to make that part of the container go above the footer, and that's what I came with:

https://jsfiddle.net/84weu9nz/

Doing that, as you can notice, footer content is no longer clickable or selectable, due to z-index. I could set the container to have a relative position, like  https://jsfiddle.net/rLmuq2of/, but the problem of that solution is that I can't make the whole content of the page inside a position:relative element, some popups or some functionality inside that element may have unexpected behaviours, so I don't think it is a good practice.

Any solution? Thanks.

答:
I managed to do this using power of flex but I am not sure if it is really a nicer solution.

I reversed order of columns/elements using css flex-direction: column-reverse, then put main div using order to first position again order: 1 (default order is 0).

.app {
  display: flex;
  flex-direction: column-reverse;
}

main {
  background-color: red;
  width: 400px;
  margin: 0 auto;
  order: 1;
}

footer {
  background-color: green;
  padding-top: 20px;
  margin-top: -20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="app">
  <main>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
  </main>
  <footer>
    <li>#1</li>
    <li>#2</li>
    <li>#3</li>
  </footer>
</div></code>```

Body:
I managed to do this using power of flex but I am not sure if it is really a nicer solution.

I reversed order of columns/elements using css flex-direction: column-reverse, then put main div using order to first position again order: 1 (default order is 0).

.app {
  display: flex;
  flex-direction: column-reverse;
}

main {
  background-color: red;
  width: 400px;
  margin: 0 auto;
  order: 1;
}

footer {
  background-color: green;
  padding-top: 20px;
  margin-top: -20px;
}

<div class="app">
  <main>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
  </main>
  <footer>
    <li><a href="#">#1</a></li>
    <li><a href="#">#2</a></li>
    <li><a href="#">#3</a></li>
  </footer>
</div>


问:
php echo returns fail to jQuery
Below is jQuery code to pass form data to a php file.  I'm using a very simple file just to test this.  The jQuery code returns success and failure messages, but the failure message is the one that fires.  It looks like the problem is in the php file, or in the data encoding.

This is the php file echo_test.php:

```<code><?php
  $str = "Hello world!";
  echo $str;
?>
</code>```

This is the jQuery code that sends html form data to the php file:

```<code><form>
  <!-- form fields omitted for brevity -->
  <div class="btn_div">
    <button href="google.com" class="btn_joinnow" id="btn_submit"   style="color:rgb(255,255,255)">Click to submit data</button>
  </div>
</form>
</code>```

$("#btn_submit").on("click", function(event) {
  event.preventDefault();
  var datastring = JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  });
  console.log("Okay, I'm starting");

  return $.ajax({
    type: "POST",
    url: "echo_test.php",
    data: { post: datastring },
    success: function (response) {
      console.log(response);
    },
    error: function (error) {
      console.log("Okay, I failed" + error);
    }
  });
});
```

(The data [ title: 'foo', body: 'bar', userId: 1 ] are just placeholders.)

The dev console reports:  Okay, I failed[object Object] so it didn't work.

The dev console also says:

XML Parsing Error: no root element found Location: (file location) Line Number 4, Column 1:

Is the problem with jQuery or PHP?

Thanks for any ideas.

答: The error means that expected response was XML but most likely it was empty. Try changing the "URL" for example to <code>"/echo_test.php"</code> and try opening this url via browser to see what's the content </p>

Title: php echo returns fail to jQuery

Body:
Below is jQuery code to pass form data to a php file.  I'm using a very simple file just to test this.  The jQuery code returns success and failure messages, but the failure message is the one that fires.  It looks like the problem is in the php file, or in the data encoding.

This is the php file echo_test.php:

<?php
  $str = "Hello world!";
  echo $str;
?>

This is the jQuery code that sends html form data to the php file:

<form>

    <button href="google.com" class="btn_joinnow" id="btn_submit"   style="color:rgb(255,255,255)">Click to submit data</button>

</form>

$("#btn_submit").on("click", function(event) {
  event.preventDefault();
  var datastring = JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  });
  console.log("Okay, I'm starting");

  return $.ajax({
    type: "POST",
    url: "echo_test.php",
    data: { post: datastring },
    success: function (response) {
      console.log(response);
    },
    error: function (error) {
      console.log("Okay, I failed" + error);
    }
  });
});

(The data [ title: 'foo', body: 'bar', userId: 1 ] are just placeholders.)

The dev console reports:  Okay, I failed[object Object] so it didn't work.

The dev console also says:

XML Parsing Error: no root element found Location: (file location) Line Number 4, Column 1:

Is the problem with jQuery or PHP?

Thanks for any ideas.

Body: The error means that expected response was XML but most likely it was empty. Try changing the "URL" for example to "/echo_test.php" and try opening this url via browser to see what's the content


问:
Failure to transfer dependency, was cached in the local repository
I am working on maven 2 project on eclipse, and I have the m2e plugin, and I am getting the following error in Eclipse:

```<code>Failure to transfer com.thoughtworks.xstream:xstream:pom:1.3.1 from http://repo1.maven.org/maven2 was cached in the
 local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced.
 Original error: Could not transfer artifact com.thoughtworks.xstream:xstream:pom:1.3.1 from/to central (http://
 repo1.maven.org/maven2): Failed to create a selector. to http://repo1.maven.org/maven2/com/thoughtworks/xstream/
 xstream/1.3.1/xstream-1.3.1.pom
</code>```

please advise how to fix it.

答:
Error occured because of old cache of Maven tool is present in your directory.
So you must delete it.
Go to C\User\"your user name"\m2 then delete it.

Body:
I am working on maven 2 project on eclipse, and I have the m2e plugin, and I am getting the following error in Eclipse:

Failure to transfer com.thoughtworks.xstream:xstream:pom:1.3.1 from http://repo1.maven.org/maven2 was cached in the
 local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced.
 Original error: Could not transfer artifact com.thoughtworks.xstream:xstream:pom:1.3.1 from/to central (http://
 repo1.maven.org/maven2): Failed to create a selector. to http://repo1.maven.org/maven2/com/thoughtworks/xstream/
 xstream/1.3.1/xstream-1.3.1.pom

please advise how to fix it.


问:
Pass stack install `--flag` to stack run?
How do I pass a flag to stack run like I'd do with stack install --flag asd:qwe?

答:
I couldn't find a way to do this, so here is my suggested workaround:

Instead of using stack run ..., build your application using stack build and run the program directly.

So, instead of using

```<code># The Problem: This doesn't work because run doesn't recognize --flag

> stack run --flag asd:qwe
</code>```

use the following two-step approach:

stack build --flag asd:qwe

./path/to/your/executable/<your executable>

If you're using stack install instead of stack build, stack puts the compiled binary in the local-bin directory.¹ The documentation suggests that you add this directory to your $PATH variable, which means you can just call <your-executable>.

The rest of this response assumes that you are using stack build.

On my system (Arch linux, May '19, stack 1.9.3.1), stack puts the compiled binary in the bin-folder inside the local-install-root. (Show it using stack path --local-install-root.)

The complete path to the executable should be <local-install-root>/bin/<executable-name>

¹ According to The User guide there is regular confusion about the meaning of stack install. It's an alias to stack build --copy-bins, which just copies the binary to local-bin-path after building, which makes it generally available if your $PATH includes local-bin-path

Body:
I couldn't find a way to do this, so here is my suggested workaround:

Instead of using stack run ..., build your application using stack build and run the program directly.

So, instead of using

# The Problem: This doesn't work because run doesn't recognize --flag

> stack run --flag asd:qwe

use the following two-step approach:

stack build --flag asd:qwe

./path/to/your/executable/<your executable>

If you're using stack install instead of stack build, stack puts the compiled binary in the local-bin directory.¹ The documentation suggests that you add this directory to your $PATH variable, which means you can just call <your-executable>.

The rest of this response assumes that you are using stack build.

On my system (Arch linux, May '19, stack 1.9.3.1), stack puts the compiled binary in the bin-folder inside the local-install-root. (Show it using stack path --local-install-root.)

The complete path to the executable should be <local-install-root>/bin/<executable-name>

¹ According to The User guide there is regular confusion about the meaning of stack install. It's an alias to stack build --copy-bins, which just copies the binary to local-bin-path after building, which makes it generally available if your $PATH includes local-bin-path


问:
Check if user is already logged in and skip if it is true
I am creating web scraping code to login to website and input some data. There is login form before getting to the actual page. My code works there is login first. However website does not ask to login in if you have already logged in. Is there any way to check if login is needed or not?

Here is my code:

```<code>Sub ChechAutomate()
    Dim ie As New InternetExplorer, url As String, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com/"

    With ie
        .Visible = True
        .Navigate2 url

        While .Busy Or .ReadyState < 4: DoEvents: Wend

        With .Document
            .querySelector("[name=userName]").Value = "username"
            .querySelector("[name=password]").Value = "password123"
            .querySelector("[type=submit]").Click

            'While .Busy Or .ReadyState < 4: DoEvents: Wend

            .querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
            .querySelector("[type=submit]").Click
        End With

    End With

End Sub
</code>```

答:
Easiest check is to use querySelectorAll to return a nodeList and check its length IMO. Inside the With .document ...

```<code>If .querySelectorAll("#login-bis-id-btn").length > 0 Then
    'present ....do login page stuff
Else
    'do other stuff
End If
</code>```

Body:
I am creating web scraping code to login to website and input some data. There is login form before getting to the actual page. My code works there is login first. However website does not ask to login in if you have already logged in. Is there any way to check if login is needed or not?

Here is my code:

Sub ChechAutomate()
    Dim ie As New InternetExplorer, url As String, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Other Data")

    url = "https://infra.com/"

    With ie
        .Visible = True
        .Navigate2 url

        While .Busy Or .ReadyState < 4: DoEvents: Wend

        With .Document
            .querySelector("[name=userName]").Value = "username"
            .querySelector("[name=password]").Value = "password123"
            .querySelector("[type=submit]").Click

            'While .Busy Or .ReadyState < 4: DoEvents: Wend

            .querySelector("[id=companySearchKeyData]").Value = ws.Range("T24").Value
            .querySelector("[type=submit]").Click
        End With

    End With

End Sub

Body:
Easiest check is to use querySelectorAll to return a nodeList and check its length IMO. Inside the With .document ...

If .querySelectorAll("#login-bis-id-btn").length > 0 Then
    'present ....do login page stuff
Else
    'do other stuff
End If


问:
How do I undo the command $ eval "$(docker-machine env blog)"
I think that command redirected $ docker commands to the docker machine.  Now all my docker commands are giving me an error FATA[0000] Couldn't read ca cert... follwed by the path to the docker-machine I created.  How can I fix my shell?

答: You could also restart your shell. This will drop the variables that minkube docker-env exports.


问:
ValueError: could not convert string to float - python
I'm new in ML. I created a dataset with some images for digits recognition. I would like to train my model but I have an error when fitting.

I've tried to encode urls numpy array but it doesn't work:

```<code>le = preprocessing.LabelEncoder()
urls = le.fit_transform(urls)
</code>```

```<code>import json
import json_lines
import numpy as np
from sklearn.model_selection import train_test_split
import tensorflow as tf
from sklearn import preprocessing
import sklearn

urls=[]
labels =[]

with open('Digits_file.json') as file1:
    lis = []
    for i in json_lines.reader(file1):
        lis.append(i)

for i in lis:
    urls.append(i['content'])
    labels.append([i['annotation']['labels'][0]])

urls = np.array(urls)
labels = np.array(labels)

x_train, x_test, y_train, y_test = train_test_split(urls, labels, test_size=0.2)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=[98,98]))
model.add(tf.keras.layers.Dense(128, activation="relu"))
model.add(tf.keras.layers.Dense(10, activation="softmax"))

model.compile(
    loss="sparse_categorical_crossentropy",
    optimizer="adam",
    metrics=["accuracy"]
)

model.fit(x_train, y_train, epochs=5)
</code>```

I got the error:

ValueError                                Traceback (most recent call last)
   in
  ----> 1 model.fit(x_train, y_train, epochs=1)
  ValueError: could not convert string to float: 'http://com.dataturks.a96-i23.open.s3.amazonaws.com/2c9fafb06abf8f13016aea188d5c036c/c0e1ad90-fec9-4609-b6d8-65b7efb5263c___0001_CH4M_0_number-25.png'

Thank you for the help.

答:
First of all, String data can be the x_train data.

You should an identification of data for learning.

From Your code, It seems that you want to learn annotation or label by contents.

I think contents would be natural language.

For the basic NLP (Natural language processing), We should do identification process.
I got some good answer from other answer. Please refer it.
https://datascience.stackexchange.com/questions/12695/machine-learning-identification-and-classification-based-on-string-contents-ge

And, You need other preprocessing if training data are images. I got some good answer from other answer. https://datascience.stackexchange.com/questions/5224/how-to-prepare-augment-images-for-neural-network

Body:
I'm new in ML. I created a dataset with some images for digits recognition. I would like to train my model but I have an error when fitting.

I've tried to encode urls numpy array but it doesn't work:

le = preprocessing.LabelEncoder()
urls = le.fit_transform(urls)

import json
import json_lines
import numpy as np
from sklearn.model_selection import train_test_split
import tensorflow as tf
from sklearn import preprocessing
import sklearn

urls=[]
labels =[]

with open('Digits_file.json') as file1:
    lis = []
    for i in json_lines.reader(file1):
        lis.append(i)

for i in lis:
    urls.append(i['content'])
    labels.append([i['annotation']['labels'][0]])

urls = np.array(urls)
labels = np.array(labels)

x_train, x_test, y_train, y_test = train_test_split(urls, labels, test_size=0.2)

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=[98,98]))
model.add(tf.keras.layers.Dense(128, activation="relu"))
model.add(tf.keras.layers.Dense(10, activation="softmax"))

model.compile(
    loss="sparse_categorical_crossentropy",
    optimizer="adam",
    metrics=["accuracy"]
)

model.fit(x_train, y_train, epochs=5)

I got the error:

ValueError                                Traceback (most recent call last)
   in
  ----> 1 model.fit(x_train, y_train, epochs=1)
  ValueError: could not convert string to float: 'http://com.dataturks.a96-i23.open.s3.amazonaws.com/2c9fafb06abf8f13016aea188d5c036c/c0e1ad90-fec9-4609-b6d8-65b7efb5263c___0001_CH4M_0_number-25.png'

Thank you for the help.