问:
Columns don't act responsive even though @media is set?
I've created these to text boxes and want to add responsiveness to them, however, adding the @media doesn't work for some reason. I want the the right box move under the left box when the screen size is under x pixels.

/* CSS Document */

* {
  box-sizing: border-box;
}

#fullbodybg {
  margin-top: 20%;
}

/* Create two unequal columns that floats next to each other */

.column {
  float: left;
  padding: 10px;
  height: auto;
  /* Should be removed. Only for demonstration */
}

@media screen and (max-width: 1000px) {
  .column {
    width: 100%;
  }
}

.left {
  margin-left: 10%;
  width: 25%;
}

.right {
  margin-right: 10%;
  width: 55%;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

.row {
  font-family: lato;
  font-style: normal;
  font-weight: 100;
  font-size: 15px;
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="column left">
    <h2>Angaben gemäß § 5 TMG</h2>
    <p>Max Muster<br>Musterweg<br>12345 Musterstadt<br><br>Vertreten durch:<br>Max Muster<br><br>Kontakt:<br>Telefon: 01234-789456<br>Fax: 1234-56789<br>E-Mail: max@muster.de<br><br>Umsatzsteuer-ID:<br>Umsatzsteuer-Identifikationsnummer gemäß
      §27a Umsatzsteuergesetz: Musterustid.<br><br>Wirtschafts-ID:<br>Musterwirtschaftsid<br><br>Aufsichtsbehörde:<br>Musteraufsicht Musterstadt</p>
  </div>
  <div class="column right">
    <h2>Haftungsausschluss:</h2>
    <p>Zweck einverstanden.</p>
  </div>
</div></code>```

答:
It is about how css prioritizes, you can google and read it. there are some
rules.

In your case, you can either put the @media query below your left and right CSS (media at the bottom is best). Or add important to the CSS in the media query (which not a good practice but will do the job).

Solution 1.

* {
            box-sizing: border-box;
        }

        #fullbodybg {
            margin-top: 20%;
        }

        /* Create two unequal columns that floats next to each other */
        .left {
            margin-left: 10%;
            width: 25%;
        }

        .right {
            margin-right: 10%;
            width: 55%;
        }

        /* Clear floats after the columns */
        .row:after {
            content: "";
            display: table;
            clear: both;
        }

        .row {
            font-family: lato;
            font-style: normal;
            font-weight: 100;
            font-size: 15px;
            text-align: left;
        }
        .column {
            float: left;
            padding: 10px;
            height: auto;
            /* Should be removed. Only for demonstration */
        }

        @media screen and (max-width: 1000px) {
            .column {
                width: 100%;
            }
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
        <div class="column left">
            <h2>Angaben gemäß § 5 TMG</h2>
            <p>Max Muster<br>Musterweg<br>12345 Musterstadt<br><br>Vertreten durch:<br>Max
                Muster<br><br>Kontakt:<br>Telefon: 01234-789456<br>Fax: 1234-56789<br>E-Mail:
                max@muster.de<br><br>Umsatzsteuer-ID:<br>Umsatzsteuer-Identifikationsnummer gemäß §27a
                Umsatzsteuergesetz:
                Musterustid.<br><br>Wirtschafts-ID:<br>Musterwirtschaftsid<br><br>Aufsichtsbehörde:<br>Musteraufsicht
                Musterstadt</p>
        </div>
        <div class="column right">
            <h2>Haftungsausschluss:</h2>
            <p>Zweck einverstanden.</p>
        </div>
    </div></code>```

Solution 2.

/* CSS Document */

* {
  box-sizing: border-box;
}
#fullbodybg {
 margin-top: 20%;
}

/* Create two unequal columns that floats next to each other */
.column {
  float: left;
  padding: 10px;
  height: auto; /* Should be removed. Only for demonstration */
}
@media screen and (max-width: 1000px) {
  .column {
    width: 100% !important;
  }
}

.left {
margin-left: 10%;
  width: 25%;
}

.right {
 margin-right: 10%;
  width: 55%;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

.row {
    font-family: lato;
    font-style: normal;
    font-weight: 100;
    font-size: 15px;
    text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
        <div class="column left">
            <h2>Angaben gemäß § 5 TMG</h2>
            <p>Max Muster<br>Musterweg<br>12345 Musterstadt<br><br>Vertreten durch:<br>Max
                Muster<br><br>Kontakt:<br>Telefon: 01234-789456<br>Fax: 1234-56789<br>E-Mail:
                max@muster.de<br><br>Umsatzsteuer-ID:<br>Umsatzsteuer-Identifikationsnummer gemäß §27a
                Umsatzsteuergesetz:
                Musterustid.<br><br>Wirtschafts-ID:<br>Musterwirtschaftsid<br><br>Aufsichtsbehörde:<br>Musteraufsicht
                Musterstadt</p>
        </div>
        <div class="column right">
            <h2>Haftungsausschluss:</h2>
            <p>Zweck einverstanden.</p>
        </div>
    </div></code>```

Body:
I've created these to text boxes and want to add responsiveness to them, however, adding the @media doesn't work for some reason. I want the the right box move under the left box when the screen size is under x pixels.

/* CSS Document */

* {
  box-sizing: border-box;
}

#fullbodybg {
  margin-top: 20%;
}

/* Create two unequal columns that floats next to each other */

.column {
  float: left;
  padding: 10px;
  height: auto;
  /* Should be removed. Only for demonstration */
}

@media screen and (max-width: 1000px) {
  .column {
    width: 100%;
  }
}

.left {
  margin-left: 10%;
  width: 25%;
}

.right {
  margin-right: 10%;
  width: 55%;
}

/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}

.row {
  font-family: lato;
  font-style: normal;
  font-weight: 100;
  font-size: 15px;
  text-align: left;
}

Angaben gemäß § 5 TMG

Max Muster
Musterweg
12345 Musterstadt

Vertreten durch:
Max Muster

Kontakt:
Telefon: 01234-789456
Fax: 1234-56789
E-Mail: max@muster.de

Umsatzsteuer-ID:
Umsatzsteuer-Identifikationsnummer gemäß
      §27a Umsatzsteuergesetz: Musterustid.

Wirtschafts-ID:
Musterwirtschaftsid

Aufsichtsbehörde:
Musteraufsicht Musterstadt

Haftungsausschluss:

Zweck einverstanden.

Body:
It is about how css prioritizes, you can google and read it. there are some
rules.

In your case, you can either put the @media query below your left and right CSS (media at the bottom is best). Or add important to the CSS in the media query (which not a good practice but will do the job).

Solution 1.

* {
            box-sizing: border-box;
        }

        #fullbodybg {
            margin-top: 20%;
        }

        /* Create two unequal columns that floats next to each other */
        .left {
            margin-left: 10%;
            width: 25%;
        }

        .right {
            margin-right: 10%;
            width: 55%;
        }

        /* Clear floats after the columns */
        .row:after {
            content: "";
            display: table;
            clear: both;
        }

        .row {
            font-family: lato;
            font-style: normal;
            font-weight: 100;
            font-size: 15px;
            text-align: left;
        }
        .column {
            float: left;
            padding: 10px;
            height: auto;
            /* Should be removed. Only for demonstration */
        }

        @media screen and (max-width: 1000px) {
            .column {
                width: 100%;
            }
        }

<div class="row">
        <div class="column left">
            <h2>Angaben gem&auml;&szlig; &sect; 5 TMG</h2>
            <p>Max Muster<br>Musterweg<br>12345 Musterstadt<br><br>Vertreten durch:<br>Max
                Muster<br><br>Kontakt:<br>Telefon: 01234-789456<br>Fax: 1234-56789<br>E-Mail:
                max@muster.de<br><br>Umsatzsteuer-ID:<br>Umsatzsteuer-Identifikationsnummer gem&auml;&szlig; &sect;27a
                Umsatzsteuergesetz:
                Musterustid.<br><br>Wirtschafts-ID:<br>Musterwirtschaftsid<br><br>Aufsichtsbeh&ouml;rde:<br>Musteraufsicht
                Musterstadt</p>
        </div>
        <div class="column right">
            <h2>Haftungsausschluss:</h2>
            <p>Zweck einverstanden.</p>
        </div>
    </div>

Solution 2.

/* CSS Document */

* {
  box-sizing: border-box;
}
#fullbodybg {
 margin-top: 20%;
}

/* Create two unequal columns that floats next to each other */
.column {
  float: left;
  padding: 10px;
  height: auto; /* Should be removed. Only for demonstration */
}
@media screen and (max-width: 1000px) {
  .column {
    width: 100% !important;
  }
}

.left {
margin-left: 10%;
  width: 25%;
}

.right {
 margin-right: 10%;
  width: 55%;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

.row {
    font-family: lato;
    font-style: normal;
    font-weight: 100;
    font-size: 15px;
    text-align: left;
}

<div class="row">
        <div class="column left">
            <h2>Angaben gem&auml;&szlig; &sect; 5 TMG</h2>
            <p>Max Muster<br>Musterweg<br>12345 Musterstadt<br><br>Vertreten durch:<br>Max
                Muster<br><br>Kontakt:<br>Telefon: 01234-789456<br>Fax: 1234-56789<br>E-Mail:
                max@muster.de<br><br>Umsatzsteuer-ID:<br>Umsatzsteuer-Identifikationsnummer gem&auml;&szlig; &sect;27a
                Umsatzsteuergesetz:
                Musterustid.<br><br>Wirtschafts-ID:<br>Musterwirtschaftsid<br><br>Aufsichtsbeh&ouml;rde:<br>Musteraufsicht
                Musterstadt</p>
        </div>
        <div class="column right">
            <h2>Haftungsausschluss:</h2>
            <p>Zweck einverstanden.</p>
        </div>
    </div>


来源: stackexchange

问:
CLion, SDL2, CMake: No available video device
I am trying to start using SDL2 (with CLion as my IDE), but I'm running into errors. I'm on Pop!_OS 19.10 (based on ubuntu)

Here are the relevant project files:

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.13)
project(sdlpractice)

set(CMAKE_CXX_STANDARD 20)

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})

add_executable(sdlpractice main.cpp)
target_link_libraries(sdlpractice ${SDL2_LIBRARIES})
</code>```

Main.cpp

```<code>#include "SDL2/SDL.h"
#include "stdio.h"

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

int main(int argc, char* args[]) {
    // The window we will be rendering to
    SDL_Window * ptrWindow = NULL;
    // The surface contained by the window
    SDL_Surface * ptrScreenSurface = NULL;
    // Initialize SDL
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
    } else {
        // Create window
        ptrWindow = SDL_CreateWindow("SDL Practice",
                SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if (ptrWindow == nullptr) {
            printf("Window creation failed: %s\n", SDL_GetError());
        }
        // Get window surface
        ptrScreenSurface = SDL_GetWindowSurface(ptrWindow);
        // Fill the surface white
        SDL_FillRect(ptrScreenSurface, NULL, SDL_MapRGB(ptrScreenSurface->format, 0xFF, 0xFF, 0xFF));
        // Update the surface
        SDL_UpdateWindowSurface(ptrWindow);
        // Wait 2 seconds
        SDL_Delay(2000);
        // Destroy window, quit SDL subsystems
        SDL_DestroyWindow(ptrWindow);
        SDL_Quit();
        return 0;
    }
}
</code>```

I get the following error:

```<code>SDL could not initialize! SDL_Error: No available video device
</code>```

I have tried setting DISPLAY=:0.0 in CLion's run configurations. Same error results. Futhermore, I ran

```<code>echo $DISPLAY
:1
</code>```

and tried using :1 as well, same error persists.

答: Removing /usr/local/bin/sdl2-config,/usr/local/include/SDL2 and /usr/local/lib/libSDL2* (as suggested by Botje) solved the problem due to the self-built version of SDL2 missing the required video headers.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to start using SDL2 (with CLion as my IDE), but I'm running into errors. I'm on Pop!_OS 19.10 (based on ubuntu)

Here are the relevant project files:

CMakeLists.txt

cmake_minimum_required(VERSION 3.13)
project(sdlpractice)

set(CMAKE_CXX_STANDARD 20)

find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})

add_executable(sdlpractice main.cpp)
target_link_libraries(sdlpractice ${SDL2_LIBRARIES})

Main.cpp

#include "SDL2/SDL.h"
#include "stdio.h"

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

int main(int argc, char* args[]) {
    // The window we will be rendering to
    SDL_Window * ptrWindow = NULL;
    // The surface contained by the window
    SDL_Surface * ptrScreenSurface = NULL;
    // Initialize SDL
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
    } else {
        // Create window
        ptrWindow = SDL_CreateWindow("SDL Practice",
                SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if (ptrWindow == nullptr) {
            printf("Window creation failed: %s\n", SDL_GetError());
        }
        // Get window surface
        ptrScreenSurface = SDL_GetWindowSurface(ptrWindow);
        // Fill the surface white
        SDL_FillRect(ptrScreenSurface, NULL, SDL_MapRGB(ptrScreenSurface->format, 0xFF, 0xFF, 0xFF));
        // Update the surface
        SDL_UpdateWindowSurface(ptrWindow);
        // Wait 2 seconds
        SDL_Delay(2000);
        // Destroy window, quit SDL subsystems
        SDL_DestroyWindow(ptrWindow);
        SDL_Quit();
        return 0;
    }
}

I get the following error:

SDL could not initialize! SDL_Error: No available video device

I have tried setting DISPLAY=:0.0 in CLion's run configurations. Same error results. Futhermore, I ran

echo $DISPLAY
:1

and tried using :1 as well, same error persists.


问:
How to find all jobs which are using particular repository url in jenkins using groovy and disable them
Want to develop some groovy script to find all jobs which are using some particular repository url( xxxx.com) and disable them. I am able to do this by below script which is not working for jobs which are under folders and subfolders.</p>

```<code>Jenkins.instance.getAllItems(hudson.model.AbstractProject.class).each {it ->
  scm = it.getScm()
  if(scm instanceof hudson.plugins.git.GitSCM)
  {
     if(scm.getUserRemoteConfigs()[0].getUrl().contains('XXXXXXXX'))
     {
        println scm.getUserRemoteConfigs()[0].getUrl()
        println it.name
        it.makeDisabled(true)
      }
  }
}
println "Done"
</code>```

答:
```<code>import org.jvnet.hudson.plugins.shelveproject.ShelveProjectTask
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
Jenkins.instance.allItems(org.jenkinsci.plugins.workflow.job.WorkflowJob.class).each {it ->
scm = it.getSCMs()
for ( sc in scm ){

if ( sc instanceof hudson.plugins.git.GitSCM){

scurl = sc.getUserRemoteConfigs()[0].getUrl()
if ( scurl.contains('xxxxxxxxx') ){

println scurl
println it.getFullName()
// it.makeDisabled(true)
def spt=  new ShelveProjectTask(it)
Hudson.getInstance().getQueue().schedule(spt , 0 );
}}}
}
return
</code>```

Body:
Want to develop some groovy script to find all jobs which are using some particular repository url( xxxx.com) and disable them. I am able to do this by below script which is not working for jobs which are under folders and subfolders.

Jenkins.instance.getAllItems(hudson.model.AbstractProject.class).each {it ->
  scm = it.getScm()
  if(scm instanceof hudson.plugins.git.GitSCM)
  {
     if(scm.getUserRemoteConfigs()[0].getUrl().contains('XXXXXXXX'))
     {
        println scm.getUserRemoteConfigs()[0].getUrl()
        println it.name
        it.makeDisabled(true)
      }
  }
}
println "Done"


问:
add a link read more to a text recover belong to a given database
I have a code which is used to retrieve data from a database in an html table.

one of the data to recover is a very long text.

like:

I want to add a read more link to improve the display of my table.

答:
i'll give you a fast example how you can do this, imagine the
 is your cell and the
 is your database content.

    AAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

```

You can do this by giving a max-height:100%; and overflow:auto; to your content.

Hope it helps.

Body:
i'll give you a fast example how you can do this, imagine the <div> is your cell and the <p> is your database content.

<div style="height:100px;width:150px;background-color:red;">
  <p style="max-height:100%;max-width:100%;color:white;  overflow:auto">
    AAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  </p>
</div>

You can do this by giving a max-height:100%; and overflow:auto; to your content.

Hope it helps.


问:
finding columns with recurring nan series between first and last real value
I am currently cleaning a rather large file of time series. As you can see in the dataframe below, the majority of columns begin and end with some NaNs.

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({
               'a': [np.NaN, np.NaN, 3, 4, 5, 3, 2, 1, 2, 1, np.NaN, np.NaN],
               'b': [np.NaN, 80, 84, 30, 3, np.NaN, np.NaN, np.NaN, 4, 3, 2, 1],
               'c': [np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, 80, 84, 1, 2, 3, 4 , 5],
               'd': [np.NaN, 40, 8, 2, 3, 4, 5, 6, 7, 8, 7, np.NaN],
               'e': [np.NaN, 1, 2, 3, np.NaN, np.NaN, 6, 7, 8, 9, 1 ,2]})
</code>```

This isn't a problem for me, but: If there is a series of 2 following NaN's  INSIDE the first real value and the last value of a column, I need to detect them. So what I want to do is very similiar to the idea / thinking behind the interpolation method:

```<code>df = df.interpolate(method = 'linear', limit_area='inside', limit = 2)
</code>```

But instead I would like to get the columns in which there are these recurring NaN series. So looking at the example dataframe above, I would like column "b" and "e" as the output, because those are the only columns who have more than two recurring NaNs INBETWEEN the first and last real, non-NaN value. So I am not looking for a interpolation method, but a method for detecting these columns

Does anyone have a recommendation how this could be done? Thanks in advance

答:
This can be solved using a method derived from the consecutive count problem

Here I would define a function to count the maximum numbers of consecutive NaN inside a Series:

```<code>def seqnan(x):
    y = x[~x.isna()]
    y = x[y.index[0]:y.index[-1]]      # limit from first non NaN value to last one
    # the magic formula (see ref. post for details)
    t = y[y.isna()].groupby((y.isna()&(~y.shift().isna())).cumsum()).cumcount().max()
    return 0 if np.isnan(t) else t+1
</code>```

Now we have:

```<code>>>> df.apply(seqnan)
a    0
b    3
c    0
d    0
e    2
dtype: int64
</code>```

So to get the columns names having at least 2 consecutive NaN values inside the first non NaN to last non NaN, you can do

```<code>tmp = df.apply(seqnan)
cols = tmp[tmp >= 2].index.tolist()
</code>```

to get as expected

```<code>['b', 'e']
</code>```

Body:
I am currently cleaning a rather large file of time series. As you can see in the dataframe below, the majority of columns begin and end with some NaNs.

import pandas as pd
import numpy as np

df = pd.DataFrame({
               'a': [np.NaN, np.NaN, 3, 4, 5, 3, 2, 1, 2, 1, np.NaN, np.NaN],
               'b': [np.NaN, 80, 84, 30, 3, np.NaN, np.NaN, np.NaN, 4, 3, 2, 1],
               'c': [np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, 80, 84, 1, 2, 3, 4 , 5],
               'd': [np.NaN, 40, 8, 2, 3, 4, 5, 6, 7, 8, 7, np.NaN],
               'e': [np.NaN, 1, 2, 3, np.NaN, np.NaN, 6, 7, 8, 9, 1 ,2]})

This isn't a problem for me, but: If there is a series of 2 following NaN's  INSIDE the first real value and the last value of a column, I need to detect them. So what I want to do is very similiar to the idea / thinking behind the interpolation method:

df = df.interpolate(method = 'linear', limit_area='inside', limit = 2)

But instead I would like to get the columns in which there are these recurring NaN series. So looking at the example dataframe above, I would like column "b" and "e" as the output, because those are the only columns who have more than two recurring NaNs INBETWEEN the first and last real, non-NaN value. So I am not looking for a interpolation method, but a method for detecting these columns

Does anyone have a recommendation how this could be done? Thanks in advance

Body:
This can be solved using a method derived from the consecutive count problem

Here I would define a function to count the maximum numbers of consecutive NaN inside a Series:

def seqnan(x):
    y = x[~x.isna()]
    y = x[y.index[0]:y.index[-1]]      # limit from first non NaN value to last one
    # the magic formula (see ref. post for details)
    t = y[y.isna()].groupby((y.isna()&(~y.shift().isna())).cumsum()).cumcount().max()
    return 0 if np.isnan(t) else t+1

Now we have:

>>> df.apply(seqnan)
a    0
b    3
c    0
d    0
e    2
dtype: int64

So to get the columns names having at least 2 consecutive NaN values inside the first non NaN to last non NaN, you can do

tmp = df.apply(seqnan)
cols = tmp[tmp >= 2].index.tolist()

to get as expected

['b', 'e']


问:
How to wait for a AdMob Rewarded Video to Load properly
I am trying to use the AdMob Rewarded Ad in my Android application.
In order to include it in the refered app, I need to wait for the rewarded video to load after the user click the buttom.
I am trying it throughout the code bellow, but I get the error:

java.lang.IllegalStateException: showAd must be called on the main UI
  thread.

When the buttom is clicked:

```<code>b_r_ans.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if(isSomBotaoLigado() && loaded[0])
            soundPool.play(soundID, MyApplication.getVolumeBotao(), MyApplication.getVolumeBotao(), 1, 0, 1f);

        Toast.makeText(MyApplication.getAppContext(),carregando_rv, Toast.LENGTH_LONG).show();

        Thread t_rv = new Thread(new Runnable() {
            public void run() {
                while(!rv_loaded){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        t_rv.start();

        try {
            t_rv.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        mRewardedVideoAd.show();

    }
});
</code>```

Overrided the listener:

```<code>@Override
    public void onRewardedVideoAdLoaded() {
        Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
        rv_loaded = true;
    }
</code>```

Using the mRewardedVideoAd.isLoaded() function triggers the same issue.

How can I wait for the video to load properly?

答:
You can also disable the button until the ad is loaded, then in the onRewardedVideoAdLoaded function enable the button:

```<code>override fun onRewardedVideoAdLoaded() {
        ad_btn.isEnabled = true
    }
</code>```

Hope it helps. This is the implementation that I am using.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use the AdMob Rewarded Ad in my Android application.
In order to include it in the refered app, I need to wait for the rewarded video to load after the user click the buttom.
I am trying it throughout the code bellow, but I get the error:

java.lang.IllegalStateException: showAd must be called on the main UI
  thread.

When the buttom is clicked:

b_r_ans.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if(isSomBotaoLigado() && loaded[0])
            soundPool.play(soundID, MyApplication.getVolumeBotao(), MyApplication.getVolumeBotao(), 1, 0, 1f);

        Toast.makeText(MyApplication.getAppContext(),carregando_rv, Toast.LENGTH_LONG).show();

        Thread t_rv = new Thread(new Runnable() {
            public void run() {
                while(!rv_loaded){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        t_rv.start();

        try {
            t_rv.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        mRewardedVideoAd.show();

    }
});

Overrided the listener:

@Override
    public void onRewardedVideoAdLoaded() {
        Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
        rv_loaded = true;
    }

Using the mRewardedVideoAd.isLoaded() function triggers the same issue.

How can I wait for the video to load properly?

Body:
You can also disable the button until the ad is loaded, then in the onRewardedVideoAdLoaded function enable the button:

override fun onRewardedVideoAdLoaded() {
        ad_btn.isEnabled = true
    }

Hope it helps. This is the implementation that I am using.


问:
Moving dataframes between notebooks
I'm trying to move two dataframes from notebook1 to notebook2

I've tried using nbimporter:

```<code>import nbimporter
import notebook1 as nb1
nb1.df()
</code>```

Which returns:

AttributeError: module 'notebook1' has no attribute 'df' (it does)

I also tried using ipynb but that didn't work either

I would just write it to a excel file and read it but the index gets messed up when reading it in the other notebook.

答:
You could use a magic (literally what it's called, not me being cute lol) command called store. It works like this:

In notebook A:

```<code>df = pd.DataFrame(...)
%store df # Store the variable df in the IPython database
</code>```

Then in another notebook B:

```<code>%store -r # This will load variables from the IPython database
df
</code>```

An advantage of this approach is that you won't run into problems with datatypes changing or indexes getting messed up. This will work with variable types other than pandas dataframes too.

The official documentation displays some more features here

Title: Moving dataframes between notebooks

Body:
I'm trying to move two dataframes from notebook1 to notebook2

I've tried using nbimporter:

import nbimporter
import notebook1 as nb1
nb1.df()

Which returns:

AttributeError: module 'notebook1' has no attribute 'df' (it does)

I also tried using ipynb but that didn't work either

I would just write it to a excel file and read it but the index gets messed up when reading it in the other notebook.

Body:
You could use a magic (literally what it's called, not me being cute lol) command called store. It works like this:

In notebook A:

df = pd.DataFrame(...)
%store df # Store the variable df in the IPython database

Then in another notebook B:

%store -r # This will load variables from the IPython database
df

An advantage of this approach is that you won't run into problems with datatypes changing or indexes getting messed up. This will work with variable types other than pandas dataframes too.

The official documentation displays some more features here


问:
How to determine that UIViewController was started for the first time?
I have a ViewControllers hierarchy, with UINavigationViewController as the root.

How can I find out whether some ViewController was started for the first time or it was started as a result of unwinding of the navigation stack?

答:
On Objective-C it looks like:</p>

```<code>-(void) viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    if ([self isBeingPresented] || [self isMovingToParentViewController]) {
        // This is the first time
    } else {
        // This is the NOT first time
    }
}
</code>```

Body:
On Objective-C it looks like:

-(void) viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    if ([self isBeingPresented] || [self isMovingToParentViewController]) {
        // This is the first time
    } else {
        // This is the NOT first time
    }
}


问:
How to convert string to floating point number inside a Perl hash?
My motive is to convert the string number into floating point number while creating a hash.

I have placed my entire code and error below. Please help me to solve this issue.

Sample code

```<code>use strict;
use warnings;

use Data::Dumper;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

print Dumper($g);
</code>```

Current output

```<code>$VAR1 = {
          'get' => '8.50'
        };
</code>```

Expected output

```<code>$VAR1 = {
          'get' => 8.50
        };
</code>```

答:
Despite the single quotes around 8.50 in the Dumper output, Perl will still treat it as a numeric value when you go to use it:

```<code>use strict;
use warnings;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

my $x = 5;
printf "%.02f\n", $x + $g->{get};
</code>```

Outputs:

```<code>13.50
</code>```

Body:
My motive is to convert the string number into floating point number while creating a hash.

I have placed my entire code and error below. Please help me to solve this issue.

Sample code

use strict;
use warnings;

use Data::Dumper;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

print Dumper($g);

Current output

$VAR1 = {
          'get' => '8.50'
        };

Expected output

$VAR1 = {
          'get' => 8.50
        };

Body:
Despite the single quotes around 8.50 in the Dumper output, Perl will still treat it as a numeric value when you go to use it:

use strict;
use warnings;

my $price = 8.5;

my $g={};
$g->{'get'}=sprintf('%.02f',$price);

my $x = 5;
printf "%.02f\n", $x + $g->{get};

Outputs:

13.50


问:
Running very lightweight tasks periodically with kubernetes
Consider a requirement where we need to run very simple and lightweight tasks , say running curl command every 10 minutes.

If this was to run in a kubernetes cluster , is it efficient to create a container every 10 minutes ? Just to execute a task that may take a few seconds or even millisecond ? Is it an overkill from time and cost angle ?

Please note unfortunately lambda functions or cloud functions is not an option.

答:
You can use a CronJob to run Jobs on a time-based schedule. These automated jobs run like Cron tasks on a Linux or UNIX system. Cron jobs are useful for creating periodic and recurring tasks.

https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/


问:
Akka HTTP Error Response entity was not subscribed after 1 second
I am using Akka HTTP cachedHostConnectionPoolHttps pool to send requests as part of Akka Streams Flow:

```<code>  private val requestFlow: Flow[(HttpRequest, HelperClass), Either[Error, String], _] =
Http().cachedHostConnectionPoolHttps(BaseUrl).mapAsync(1) {
  case (Success(HttpResponse(_, _, entity, _)), _) =>
    Unmarshal(entity).to[String].map(response => {
      Right(response)
    })
  case (Failure(ex), _) =>
    Future(Left(Error(ex)))
}
</code>```

For some reason not all request responses are being processed. Some results in error:

```<code>a.h.i.e.c.PoolGateway - [0 (WaitingForResponseEntitySubscription)] Response entity was not subscribed after 1 second. Make sure to read the response entity body or call `discardBytes()` on it.
</code>```

How to subscribe to my response while maintaining the flow above?

答:
As suggested in docs, implementing entity handling the following way solves the issue:</p>

```<code>          private val requestFlow: Flow[(HttpRequest, HelperClass), Either[Error, String], _] =
Http().cachedHostConnectionPoolHttps(BaseUrl).mapAsync(1) {
  case (Success(HttpResponse(_, _, entity, _)),    _) =>
      entity.dataBytes
        .runReduce(_ ++ _)
        .map(r => Right(r.toString))
  case (Failure(ex), _) =>
    Future(Left(Error(ex)))
}
</code>```

Body:
I am using Akka HTTP cachedHostConnectionPoolHttps pool to send requests as part of Akka Streams Flow:

  private val requestFlow: Flow[(HttpRequest, HelperClass), Either[Error, String], _] =
Http().cachedHostConnectionPoolHttps(BaseUrl).mapAsync(1) {
  case (Success(HttpResponse(_, _, entity, _)), _) =>
    Unmarshal(entity).to[String].map(response => {
      Right(response)
    })
  case (Failure(ex), _) =>
    Future(Left(Error(ex)))
}

For some reason not all request responses are being processed. Some results in error:

a.h.i.e.c.PoolGateway - [0 (WaitingForResponseEntitySubscription)] Response entity was not subscribed after 1 second. Make sure to read the response entity body or call `discardBytes()` on it.

How to subscribe to my response while maintaining the flow above?

Body:
As suggested in docs, implementing entity handling the following way solves the issue:

          private val requestFlow: Flow[(HttpRequest, HelperClass), Either[Error, String], _] =
Http().cachedHostConnectionPoolHttps(BaseUrl).mapAsync(1) {
  case (Success(HttpResponse(_, _, entity, _)),    _) =>
      entity.dataBytes
        .runReduce(_ ++ _)
        .map(r => Right(r.toString))
  case (Failure(ex), _) =>
    Future(Left(Error(ex)))
}


问:
How to combine two composed applicative functors?
I have two composed applicative functors Maybe [Integer] and want to combine them with <$>/<*> but I am stuck with applying the applicative operation. The following does not typecheck:

```<code>(<*>) (<*>) ((<$>) ((+) <$>) $ Just [1,2,3]) $ Just [4,5,6]
</code>```

Expected result:

```<code>Just [5,6,7,6,7,8,7,8,9]
</code>```

The functor part works, i.e. the intermediate value passed to <*> as the first argument is Just [Integer -> Integer]. I am used to S-expressions so I have a hard time with the Haskell syntax. I know of Compose but I am interested in the mere composition wihtout abstraction.

答:
As Li-yao Xia said, using liftA2 makes it a lot less confusing.

But if you still what to see what it becomes in terms of the underlaying operations, we can expand the definition of liftA2:

liftA2 :: (a -> b -> c) -> f a -> f b -> f c
liftA2 f x y = f <$> x <*> y
```

<p>so the solution becomes</p>

```(liftA2 . liftA2) (+) (Just [1,2,3]) (Just [4,5,6])
= liftA2 (liftA2 (+)) (Just [1,2,3]) (Just [4,5,6])
= (\f x y -> f <$> x <*> y) ((\f x y -> f <$> x <*> y) (+)) (Just [1,2,3]) (Just [4,5,6])
= ((\f x y -> f <$> x <*> y) (+)) <$> Just [1,2,3] <*> Just [4,5,6]
= (\x y ->  (+) <$> x <*> y) <$> Just [1,2,3] <*> Just [4,5,6]
```

<p>Now, this is not in point free style like your example above, and I really don't think it's helpful to convert it into point free, but here's the output from http://pointfree.io:</p>

```((<*>) . ((+) <$>)) <$> Just [1, 2, 3] <*> Just [4, 5, 6]
```

<p>we can see that this is the same by eta-expanding:</p>

```(<*>) . ((+) <$>)
= \x y -> ((<*>) . ((+) <$>)) x y
= \x y -> ((<*>) $ ((+) <$>) x) y
= \x y -> ((<*>) ((+) <$> x)) y
= \x y -> (<*>) ((+) <$> x) y
= \x y -> ((+) <$> x) <*> y
= \x y -> (+) <$> x <*> y
```

Body:
I have two composed applicative functors Maybe [Integer] and want to combine them with <$>/<*> but I am stuck with applying the applicative operation. The following does not typecheck:

(<*>) (<*>) ((<$>) ((+) <$>) $ Just [1,2,3]) $ Just [4,5,6]

Expected result:

Just [5,6,7,6,7,8,7,8,9]

The functor part works, i.e. the intermediate value passed to <*> as the first argument is Just [Integer -> Integer]. I am used to S-expressions so I have a hard time with the Haskell syntax. I know of Compose but I am interested in the mere composition wihtout abstraction.

Body:
As Li-yao Xia said, using liftA2 makes it a lot less confusing.

But if you still what to see what it becomes in terms of the underlaying operations, we can expand the definition of liftA2:

liftA2 :: (a -> b -> c) -> f a -> f b -> f c
liftA2 f x y = f <$> x <*> y

so the solution becomes

(liftA2 . liftA2) (+) (Just [1,2,3]) (Just [4,5,6])
= liftA2 (liftA2 (+)) (Just [1,2,3]) (Just [4,5,6])
= (\f x y -> f <$> x <*> y) ((\f x y -> f <$> x <*> y) (+)) (Just [1,2,3]) (Just [4,5,6])
= ((\f x y -> f <$> x <*> y) (+)) <$> Just [1,2,3] <*> Just [4,5,6]
= (\x y ->  (+) <$> x <*> y) <$> Just [1,2,3] <*> Just [4,5,6]

Now, this is not in point free style like your example above, and I really don't think it's helpful to convert it into point free, but here's the output from http://pointfree.io:

((<*>) . ((+) <$>)) <$> Just [1, 2, 3] <*> Just [4, 5, 6]

we can see that this is the same by eta-expanding:

(<*>) . ((+) <$>)
= \x y -> ((<*>) . ((+) <$>)) x y
= \x y -> ((<*>) $ ((+) <$>) x) y
= \x y -> ((<*>) ((+) <$> x)) y
= \x y -> (<*>) ((+) <$> x) y
= \x y -> ((+) <$> x) <*> y
= \x y -> (+) <$> x <*> y


问:
SVN Error - 501 Not Implemented Commit Failed
I have a folder in a repository that cannot commit and even parent folders cannot commit. This happened several weeks ago, then worked, then on the blink again. I have cleared my authentication cache and no help. I can still work with other trunks but not this one and the error message does not help me where to go. I have done Clean Up. I have created a new directory from VisualSVN from the repository and same problem. Would you have any suggestions? Can I nuke the .svn folder and help? I don't want to start with a new repo because we have TeamCity integrated and watching. Help and thanks in advance!
Doug

**Error: Commit failed (details follow):

Error: Server sent unexpected return value (501 Not Implemented) in response to

Error: PROPFIND request for '/svn/MAHCP/trunk/src/RssaSolution/Mahcp.Rssa'**

I posted to SVNForum as well but has anyone else had this crazy situation!

答: The answer was that the svn server URL had been changed previously and then when trying to check it back in it would error.  The trick then was to nuke the .svn folders, pull down fresh and then copy over with my new changes.  I wish the error message had been better.</p>

ContentLicense: CC BY-SA 2.5


问:
Oracle SQL - How to merge multiple columns into new one
I need to merge multiple columns (there are quite a lot of columns and rows) into new one column.

Eg. shortened test_table

```<code>Col1    Col2    Col3    Col4    Col5    Col6
942 72987   14759   441277503   73553030    null
943 72987   14759   441278315   73553166    null
944 72987   14759   441362593   73570082    null
945 72987   14759   441380217   73572619    null
946 72987   14759   441394189   73574533    null
947 72987   14759   441394189   73574533    null
</code>```

and I'd like to merge Col1-Col5 with comma separator (",") and put created String into Col6

So in Col6 I'd like to have eg:
942,72987,14759,441277503,73553030

Is there any solution how can I do it in SQL / PL/SQL?
As I said there are a lot of column so I'd like to avoid to add them manually by using Col1 || Col2 || Col3 || Col4 || Col5

Thanks in advance,
Michał

答:
I'd follow @APC's route and use a query of USER_TAB_COLUMNS to generate the necessary SQL:

```<code>CREATE TABLE t (col1 VARCHAR2(5), col2 NUMBER, col3 VARCHAR2(30),
                col4 VARCHAR2(7), col5 DATE,   col6 VARCHAR2(200));
SELECT column_name
  FROM user_tab_columns
 WHERE table_name = 'T'
   AND column_name <> 'COL6';

COL1
COL2
COL3
COL4
COL5
</code>```

You can now concatenate them with LISTAGG:

```<code>SELECT LISTAGG(column_name, '||'',''||')
       WITHIN GROUP (ORDER BY column_id) AS sql
  FROM user_tab_columns
 WHERE table_name = 'T'
   AND column_name <> 'COL6';

COL1||','||COL2||','||COL3||','||COL4||','||COL5
</code>```

Now I'd copy and paste this to the appropriate query, f.i.

```<code>UPDATE t
   SET col6 = COL1||','||COL2||','||COL3||','||COL4||','||COL5;
</code>```

To concatenate the columns, they need to be converted to VARCHAR2. Oracle tries an automatic datatype conversion. You have to check if this works and is good enough for you. Numbers may have leading spaces, a comma or decimal point, dates may need a format string etc.

You could think of doing it along those lines:

```<code>SELECT column_name,
       CASE WHEN data_type IN ('NUMBER','FLOAT')
              THEN 'TO_CHAR('||column_name||')'
            WHEN data_type IN ('DATE')
              THEN 'TO_CHAR('||column_name||',''YYYY-MM-DD'')'
            ELSE column_name
        END AS cstr
  FROM user_tab_columns
 WHERE table_name = 'T'
   AND column_name <> 'COL6';

COL1   COL1
COL2   TO_CHAR(COL2)
COL3   COL3
COL4   COL4
COL5   TO_CHAR(COL5,'YYYY-MM-DD')
</code>```

Depending on your circumstances, you may be able to use a virtual column instead of copying the real data:

```<code>ALTER TABLE t DROP COLUMN col6;
ALTER TABLE t ADD (col6 NUMBER GENERATED ALWAYS
               AS (COL1||','||COL2||','||COL3||','||COL4||','||COL5));
</code>```

Body:
I need to merge multiple columns (there are quite a lot of columns and rows) into new one column.

Eg. shortened test_table

Col1    Col2    Col3    Col4    Col5    Col6
942 72987   14759   441277503   73553030    null
943 72987   14759   441278315   73553166    null
944 72987   14759   441362593   73570082    null
945 72987   14759   441380217   73572619    null
946 72987   14759   441394189   73574533    null
947 72987   14759   441394189   73574533    null

and I'd like to merge Col1-Col5 with comma separator (",") and put created String into Col6

So in Col6 I'd like to have eg:
942,72987,14759,441277503,73553030

Is there any solution how can I do it in SQL / PL/SQL?
As I said there are a lot of column so I'd like to avoid to add them manually by using Col1 || Col2 || Col3 || Col4 || Col5

Thanks in advance,
Michał

Body:
I'd follow @APC's route and use a query of USER_TAB_COLUMNS to generate the necessary SQL:

CREATE TABLE t (col1 VARCHAR2(5), col2 NUMBER, col3 VARCHAR2(30),
                col4 VARCHAR2(7), col5 DATE,   col6 VARCHAR2(200));
SELECT column_name
  FROM user_tab_columns
 WHERE table_name = 'T'
   AND column_name <> 'COL6';

COL1
COL2
COL3
COL4
COL5

You can now concatenate them with LISTAGG:

SELECT LISTAGG(column_name, '||'',''||')
       WITHIN GROUP (ORDER BY column_id) AS sql
  FROM user_tab_columns
 WHERE table_name = 'T'
   AND column_name <> 'COL6';

COL1||','||COL2||','||COL3||','||COL4||','||COL5

Now I'd copy and paste this to the appropriate query, f.i.

UPDATE t
   SET col6 = COL1||','||COL2||','||COL3||','||COL4||','||COL5;

To concatenate the columns, they need to be converted to VARCHAR2. Oracle tries an automatic datatype conversion. You have to check if this works and is good enough for you. Numbers may have leading spaces, a comma or decimal point, dates may need a format string etc.

You could think of doing it along those lines:

SELECT column_name,
       CASE WHEN data_type IN ('NUMBER','FLOAT')
              THEN 'TO_CHAR('||column_name||')'
            WHEN data_type IN ('DATE')
              THEN 'TO_CHAR('||column_name||',''YYYY-MM-DD'')'
            ELSE column_name
        END AS cstr
  FROM user_tab_columns
 WHERE table_name = 'T'
   AND column_name <> 'COL6';

COL1   COL1
COL2   TO_CHAR(COL2)
COL3   COL3
COL4   COL4
COL5   TO_CHAR(COL5,'YYYY-MM-DD')

Depending on your circumstances, you may be able to use a virtual column instead of copying the real data:

ALTER TABLE t DROP COLUMN col6;
ALTER TABLE t ADD (col6 NUMBER GENERATED ALWAYS
               AS (COL1||','||COL2||','||COL3||','||COL4||','||COL5));


问:
Why does my code not realize that game = false?
I have a while loop that says:

```<code>game = True
while game == True:
    shop = False
    while shop == False:
        choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
        if choice == "E" or choice == "e":
           game = False
</code>```

And yet it keeps on repeating and I cant cant figure out why (I'm also new to coding so there could be an obvious answer)
Link to code here: https://repl.it/@WeirdDragon/ore-digging-sim#main.py

答:
You need to understand how while loops work, take this for example:

```<code>a = 5
while a == 5:
    a = 6
    print('done')
</code>```

Output:

```<code> done
</code>```

The condition we gave the while loop tells it when to stop looping, but python must first reach the condition again in order to compare, meaning as long as there is no break statement, python will first finish the current loop. But in your code, because of the other while loop in that while loop never ends, we never gave python a chace to compare that game condition.

```<code>game = True
while game == True:
    shop = False
    while shop == False:
        choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
        if choice == "E" or choice == "e":
           game = False
</code>```

To fix that, simply add a break statement after the game = False:

```<code>        if choice == "E" or choice == "e":
           game = False
           break
</code>```

Body:
I have a while loop that says:

game = True
while game == True:
    shop = False
    while shop == False:
        choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
        if choice == "E" or choice == "e":
           game = False

And yet it keeps on repeating and I cant cant figure out why (I'm also new to coding so there could be an obvious answer)
Link to code here: https://repl.it/@WeirdDragon/ore-digging-sim#main.py

Body:
You need to understand how while loops work, take this for example:

a = 5
while a == 5:
    a = 6
    print('done')

Output:

 done

The condition we gave the while loop tells it when to stop looping, but python must first reach the condition again in order to compare, meaning as long as there is no break statement, python will first finish the current loop. But in your code, because of the other while loop in that while loop never ends, we never gave python a chace to compare that game condition.

game = True
while game == True:
    shop = False
    while shop == False:
        choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
        if choice == "E" or choice == "e":
           game = False

To fix that, simply add a break statement after the game = False:

        if choice == "E" or choice == "e":
           game = False
           break


问:
How to explicitly resize frames in tkinter?
so i'm currently working on a piece of code that'll be integrating into something else later to act as a settings configurator. For the time being, i want to have a window that is laid out like you see below:

where each coloured box is a frame. This window is not resizable and will always be 480x720 pixels. As such, i want the 3 frames im using, sideBar(yellow), container (blue) and static(red) to always remain the same size and fill the window as pictured above with roughly the same ratios (doesn't need to be exact).

The code for this window is below

```<code>        self.window = tk.Tk()

        self.windowHeight = 480
        self.windowLength = 720
        self.windowDimensions = str(self.windowLength)+"x"+str(self.windowHeight) #make diemnsions string; dimensions are set as a single string
        self.window.geometry(self.windowDimensions)
        self.window.resizable(width=False, height=False)

        self.container = tk.Frame(self.window, relief="sunken", borderwidth=2) #instantiate new window
        self.sideBar = tk.Frame(self.window,  relief="sunken", borderwidth=2)
        self.static = tk.Frame(self.window, relief="sunken", borderwidth=2)

        self.sideBar.grid_propagate(False)
        self.sideBar.grid(row=0, column=0)
        self.container.grid(row=0,column=1)
        self.static.grid(row=5, column=1)

        self.configuratorObject = configuratorObject

        audioButton = tk.Button(self.sideBar, text="Audio Page", command=lambda: self.raisePage("audioPage"))
        colourButton = tk.Button(self.sideBar, text="Colours", command=lambda: self.raisePage("coloursPage"))
        saveButton = tk.Button(self.static, text = "Save", state="disabled")
        applyButton = tk.Button(self.static, text = "Apply", state="disabled")
        audioButton.pack()
        colourButton.pack()
        saveButton.pack()
        applyButton.pack()
</code>```

I've attempted to change the height and width parameters of the grids, but they really don't seem to be doing anything. So how could i go about explicitly defining the layout and sizes of the frames?

Any help is appreciated

答:
In the comments you wrote

If theres a way of getting tkinter to do it then that'd be great

That is definitely the preferred way, over forcing widgets to be a particular size.

We'll start by using pack instead of grid for the three frames. For such a basic layout it requires fewer lines of code than grid.

```<code>self.sideBar.pack(side="left", fill="y")
self.static.pack(side="bottom", fill="x")
self.container.pack(side="top", fill="both", expand=True)
</code>```

Next, add the buttons on the left. This will cause the left frame to shrink in width to fit the buttons. Because we used fill="y", the height will be forced to remain the full height of the window.

```<code>audioButton.pack(side="top", fill="x")
colourButton.pack(side="top", fill="x")
</code>```

Finally, add the buttons on the bottom. Your original code shows them stacked top-to-bottom but your illustration shows them in a single horizontal row. This example adheres to the illustration.

```<code>applyButton.pack(side="right", padx=10)
saveButton.pack(side="right", padx=10)
</code>```

With that we end up with a window that looks like the following, and the proportions and orientation stays exactly the same when you resize the window:

Note: you can do this with grid too, but it requires a few more lines of code to apply weights to the rows and columns. I personally prefer pack when the layout doesn't naturally fit in a grid since it requires fewer lines of code.

Body:
so i'm currently working on a piece of code that'll be integrating into something else later to act as a settings configurator. For the time being, i want to have a window that is laid out like you see below:

where each coloured box is a frame. This window is not resizable and will always be 480x720 pixels. As such, i want the 3 frames im using, sideBar(yellow), container (blue) and static(red) to always remain the same size and fill the window as pictured above with roughly the same ratios (doesn't need to be exact).

The code for this window is below

        self.window = tk.Tk()

        self.windowHeight = 480
        self.windowLength = 720
        self.windowDimensions = str(self.windowLength)+"x"+str(self.windowHeight) #make diemnsions string; dimensions are set as a single string
        self.window.geometry(self.windowDimensions)
        self.window.resizable(width=False, height=False)

        self.container = tk.Frame(self.window, relief="sunken", borderwidth=2) #instantiate new window
        self.sideBar = tk.Frame(self.window,  relief="sunken", borderwidth=2)
        self.static = tk.Frame(self.window, relief="sunken", borderwidth=2)

        self.sideBar.grid_propagate(False)
        self.sideBar.grid(row=0, column=0)
        self.container.grid(row=0,column=1)
        self.static.grid(row=5, column=1)

        self.configuratorObject = configuratorObject

        audioButton = tk.Button(self.sideBar, text="Audio Page", command=lambda: self.raisePage("audioPage"))
        colourButton = tk.Button(self.sideBar, text="Colours", command=lambda: self.raisePage("coloursPage"))
        saveButton = tk.Button(self.static, text = "Save", state="disabled")
        applyButton = tk.Button(self.static, text = "Apply", state="disabled")
        audioButton.pack()
        colourButton.pack()
        saveButton.pack()
        applyButton.pack()

I've attempted to change the height and width parameters of the grids, but they really don't seem to be doing anything. So how could i go about explicitly defining the layout and sizes of the frames?

Any help is appreciated

Body:
In the comments you wrote

If theres a way of getting tkinter to do it then that'd be great

That is definitely the preferred way, over forcing widgets to be a particular size.

We'll start by using pack instead of grid for the three frames. For such a basic layout it requires fewer lines of code than grid.

self.sideBar.pack(side="left", fill="y")
self.static.pack(side="bottom", fill="x")
self.container.pack(side="top", fill="both", expand=True)

Next, add the buttons on the left. This will cause the left frame to shrink in width to fit the buttons. Because we used fill="y", the height will be forced to remain the full height of the window.

audioButton.pack(side="top", fill="x")
colourButton.pack(side="top", fill="x")

Finally, add the buttons on the bottom. Your original code shows them stacked top-to-bottom but your illustration shows them in a single horizontal row. This example adheres to the illustration.

applyButton.pack(side="right", padx=10)
saveButton.pack(side="right", padx=10)

With that we end up with a window that looks like the following, and the proportions and orientation stays exactly the same when you resize the window:

Note: you can do this with grid too, but it requires a few more lines of code to apply weights to the rows and columns. I personally prefer pack when the layout doesn't naturally fit in a grid since it requires fewer lines of code.


问:
How to find out which element causes a transactional error in Hibernate/Spring Data?
Using Spring 2.2.5 with Spring Data / JPA / Hibernate.

When using the CrudRepository with either CrudRepository#saveAll() or a loop structure with individual CrudRepository#save(), it seems impossible to tell which of the elements violates a constraint.

Assuming this method:

```<code>@Transactional
public void storeAll(Collection<Attribute> attributes) {
    repository.saveAll(attributes);
}
</code>```

The returned DataIntegrityViolationException with a nested hibernate ContraintViolationExceptionis being thrown. There seem to be no references to the entity in said exceptions.

Using a loop doesn't work either:

```<code>@Transactional
    public void storeAll(Collection<Attribute> attributes) {
        for(Attribute attribute : attributes){
            try{
                repository.save(attribute);
            }catch (Exception e){
                ///
            }
        }
    }
</code>```

The exception inside the loop isn't being catched (the save method doesn't seem to throw anything). Instead, it's thrown when returning from the method. Maybe due to optimization of some sort?

答:
If your objects have an identifier (an ID, unique code, etc), you can surround the code with a try/catch block and see which objects are causing the problem:

```<code>private void saveMyObjects (List<MyObject> myObjects) {
  for (MyObject myObject: myObjects) {
    try {
      this.myObjectRepository.save(myObject);
    } catch (Exception e) {
      //To be more specific:
      // } catch (DataIntegrityViolationException e) {
      system.out.println("I have a problem with this object: " + myObject.getMyIdentifier());
    }
  }
}
</code>```

Body:
Using Spring 2.2.5 with Spring Data / JPA / Hibernate.

When using the CrudRepository with either CrudRepository#saveAll() or a loop structure with individual CrudRepository#save(), it seems impossible to tell which of the elements violates a constraint.

Assuming this method:

@Transactional
public void storeAll(Collection<Attribute> attributes) {
    repository.saveAll(attributes);
}

The returned DataIntegrityViolationException with a nested hibernate ContraintViolationExceptionis being thrown. There seem to be no references to the entity in said exceptions.

Using a loop doesn't work either:

@Transactional
    public void storeAll(Collection<Attribute> attributes) {
        for(Attribute attribute : attributes){
            try{
                repository.save(attribute);
            }catch (Exception e){
                ///
            }
        }
    }

The exception inside the loop isn't being catched (the save method doesn't seem to throw anything). Instead, it's thrown when returning from the method. Maybe due to optimization of some sort?

Body:
If your objects have an identifier (an ID, unique code, etc), you can surround the code with a try/catch block and see which objects are causing the problem:

private void saveMyObjects (List<MyObject> myObjects) {
  for (MyObject myObject: myObjects) {
    try {
      this.myObjectRepository.save(myObject);
    } catch (Exception e) {
      //To be more specific:
      // } catch (DataIntegrityViolationException e) {
      system.out.println("I have a problem with this object: " + myObject.getMyIdentifier());
    }
  }
}


问:
Trying to configure prometheus with alert manager but getting error with rules file
In my prometheus.yml,the rules file is called rules.yml and it has this

```<code>---
groups:
  - name: example
    rules:
      - alert: ServiceDown
        expr: up == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: cannot connect to {{ $labels.job }}
</code>```

when i run sudo ./promtool check config rules.yml i get the error

```<code>Checking rules.yml
  FAILED: parsing YAML file rules.yml: yaml: unmarshal errors:
  line 2: field groups not found in type config.plain
</code>```

I am not sure what is wrong as i am following this https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/

Prometheus version is 2.18.1

Hoping for some assistance from someone

Thanks
KK

答:
You are loading the rules.yml using the "rule_file" clause in the Prometheus configuration file, right?

```<code>rule_files:
  - rules.yml
</code>```

I notice that we can't execute the "promtool check config" directly to the rule file but if you execute it to the Prometheus configuration file it'll check the rule file correctly:

```<code>$ promtool check config prometheus.yaml

Checking prometheus.yaml
  SUCCESS: 1 rule files found

Checking rules.yaml
  SUCCESS: 18 rules found
</code>```

Body:
In my prometheus.yml,the rules file is called rules.yml and it has this

---
groups:
  - name: example
    rules:
      - alert: ServiceDown
        expr: up == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: cannot connect to {{ $labels.job }}

when i run sudo ./promtool check config rules.yml i get the error

Checking rules.yml
  FAILED: parsing YAML file rules.yml: yaml: unmarshal errors:
  line 2: field groups not found in type config.plain

I am not sure what is wrong as i am following this https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/

Prometheus version is 2.18.1

Hoping for some assistance from someone

Thanks
KK

Body:
You are loading the rules.yml using the "rule_file" clause in the Prometheus configuration file, right?

rule_files:
  - rules.yml

I notice that we can't execute the "promtool check config" directly to the rule file but if you execute it to the Prometheus configuration file it'll check the rule file correctly:

$ promtool check config prometheus.yaml

Checking prometheus.yaml
  SUCCESS: 1 rule files found

Checking rules.yaml
  SUCCESS: 18 rules found


问:
Error: Action has more than one parameter bound from request body
I wrote a new method into my Controller of my ASP.Net MVC project and getting error below. I think InvalidOperationException coming from with Swagger. I marked it as "ignored Api" hoping it will skip the method but error still there:

```<code>[ApiExplorerSettings(IgnoreApi = true)]
public decimal CalculatePriceWithCampaign(
       BeverageCapacityCampaign campaign,
       BeverageCapacity capacity,
       int count = 1)
{
    switch (campaign.DiscountType)
    {
        case DiscountType.Fixed:
            return (capacity.CapacityPrice - campaign.DiscountValue) * count;
        case DiscountType.Percentage:
            return (capacity.CapacityPrice * count) * campaign.DiscountValue;
        default:
            return capacity.CapacityPrice;
    }
}
</code>```

But when running I am getting this error:

An unhandled exception occurred while processing the request.

InvalidOperationException: Action 'Gorilla.WebApi.Source.Controller.Campaigns.BeverageCapacityCampaignController.CalculatePriceWithCampaign (Gorilla.WebApi)' has more than one parameter that was specified or inferred as bound from request body. Only one parameter per action may be bound from body. Inspect the following parameters, and use 'FromQueryAttribute' to specify bound from query, 'FromRouteAttribute' to specify bound from route, and 'FromBodyAttribute' for parameters to be bound from body:

    BeverageCapacityCampaign campaign

    BeverageCapacity capacity

Information I could find suggested to check nugets, but all my Nugets are up-to-date.

答: I got this error by inheriting from BaseController instead of ControllerBase. It was a class from another library that is completely unrelated and I misremembered the name. The exception was a red herring for me.</p>

Body:
I wrote a new method into my Controller of my ASP.Net MVC project and getting error below. I think InvalidOperationException coming from with Swagger. I marked it as "ignored Api" hoping it will skip the method but error still there:

[ApiExplorerSettings(IgnoreApi = true)]
public decimal CalculatePriceWithCampaign(
       BeverageCapacityCampaign campaign,
       BeverageCapacity capacity,
       int count = 1)
{
    switch (campaign.DiscountType)
    {
        case DiscountType.Fixed:
            return (capacity.CapacityPrice - campaign.DiscountValue) * count;
        case DiscountType.Percentage:
            return (capacity.CapacityPrice * count) * campaign.DiscountValue;
        default:
            return capacity.CapacityPrice;
    }
}

But when running I am getting this error:

An unhandled exception occurred while processing the request.

InvalidOperationException: Action 'Gorilla.WebApi.Source.Controller.Campaigns.BeverageCapacityCampaignController.CalculatePriceWithCampaign (Gorilla.WebApi)' has more than one parameter that was specified or inferred as bound from request body. Only one parameter per action may be bound from body. Inspect the following parameters, and use 'FromQueryAttribute' to specify bound from query, 'FromRouteAttribute' to specify bound from route, and 'FromBodyAttribute' for parameters to be bound from body:

    BeverageCapacityCampaign campaign

    BeverageCapacity capacity

Information I could find suggested to check nugets, but all my Nugets are up-to-date.


问:
Django dynamic form with text and **images** through AJAX
I'm trying to create a website for creating articles, and by an article, I mean legit article with arbitrary number of text fields and images. (No just a plain single models.TextField stuff... which is mostly taught to get started with django).

I have some priorities for key features to work for as well.

User can add as many text field, and image field as possible.

As soon as user uploads the image, it gets showed up as a preview.

Now recently I learned AJAX, so I've done 90% of the work already, by putting the dynamic content into a JSON format, containing full info about the article as {"title": "...", "heading": "...", "text": "...", "heading": "...", "text": "..."}, and I'm storing that as the article content by using the request.GET in the view, and later I'd loop through that to display all the sub contents of the article in that same order.
So here I'm AJAX -

const ArticleContent = JSON.stringify(ArticleObject);

jQuery.ajax({
    url: "{% url 'upload-article' %}",
    data: {
    title: ArticleTitle,
    description: ArticleDescription,
    content: ArticleContent
    }
})
```

<p>And then by using that to create and save the new article</p>

<pre class="lang-py prettyprint-override"><code>title = request.GET.get('title', None)
description = request.GET.get('description', None)
content = request.GET.get('content', None)

article = Article.objects.create(
    title = title,
    description = description,
    content = content,
    author = request.user
)
</code>```

The problem is sending the images, I just couldn't get that part.
How can I send the list (array) of all the images I've upload in the article template through ajax to the django so that I can do something like...

title = request.GET.get('title', None)
description = request.GET.get('description', None)
content = request.GET.get('content', None)
images = request.GET.get('images', None)
...
...
for image in images:
    Image.objects.create(image = image, article = article)
```

I've also discovered django formsets, which allows to have arbitrary number of forms (in my case an image form), but the problem with this approach is - it is against the usage of AJAX, and it make the page refreshes anytime a new image is uploaded...

So now I'm basically a lot confused like what's the best approach to doing something like this.
All suggestions are appreciated. And I'm also open to whole new approach as well (like using php etc...)

答:
Maybe you need to create Image model which has a post id field as a foreign key.

```<code>def get_image_filename(instance, filename):
    id = instance.article.id
    return "article_images/%s" % (id)

class Images(models.Model):
    article = models.ForeignKey(Article, default=None)
    image = models.ImageField(upload_to=get_image_filename,
                              verbose_name='Image')
</code>```

And in forms.py, you can create Article Forma and ImageForm class for uploading images for the article.

```<code>class ArticleForm(forms.ModelForm):
    title = forms.CharField(max_length=128)
    content = forms.CharField(max_length=245, label="Item Description.")

    class Meta:
        model = Post
        fields = ('title', 'body', )

class ImageForm(forms.ModelForm):
    image = forms.ImageField(label='Image')
    class Meta:
        model = Images
        fields = ('image', )
</code>```

Finally in views.py, you can create post function that deals with post request for images data.(this is just an example)

```<code>def post(request):
    ImageFormSet = modelformset_factory(Images,
                                        form=ImageForm, extra=3)
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        formset = ImageFormSet(request.POST, request.FILES,
                               queryset=Images.objects.none())
        if form.is_valid() and formset.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            for form in formset.cleaned_data:
                image = form['image']
                photo = Images(post=post, image=image)
                photo.save()
            messages.success(request,
                             "Posted!")
            return HttpResponseRedirect("/")
        else:
            print form.errors, formset.errors
    else:
        form = ArticleForm()
        formset = ImageFormSet(queryset=Images.objects.none())
    return render(request, 'index.html',
                  {'articleForm': form, 'formset': formset},
                  context_instance=RequestContext(request))
</code>```

Body:
I'm trying to create a website for creating articles, and by an article, I mean legit article with arbitrary number of text fields and images. (No just a plain single models.TextField stuff... which is mostly taught to get started with django).

I have some priorities for key features to work for as well.

User can add as many text field, and image field as possible.

As soon as user uploads the image, it gets showed up as a preview.

Now recently I learned AJAX, so I've done 90% of the work already, by putting the dynamic content into a JSON format, containing full info about the article as {"title": "...", "heading": "...", "text": "...", "heading": "...", "text": "..."}, and I'm storing that as the article content by using the request.GET in the view, and later I'd loop through that to display all the sub contents of the article in that same order.
So here I'm AJAX -

const ArticleContent = JSON.stringify(ArticleObject);

jQuery.ajax({
    url: "{% url 'upload-article' %}",
    data: {
    title: ArticleTitle,
    description: ArticleDescription,
    content: ArticleContent
    }
})

And then by using that to create and save the new article

title = request.GET.get('title', None)
description = request.GET.get('description', None)
content = request.GET.get('content', None)

article = Article.objects.create(
    title = title,
    description = description,
    content = content,
    author = request.user
)

The problem is sending the images, I just couldn't get that part.
How can I send the list (array) of all the images I've upload in the article template through ajax to the django so that I can do something like...

title = request.GET.get('title', None)
description = request.GET.get('description', None)
content = request.GET.get('content', None)
images = request.GET.get('images', None)
...
...
for image in images:
    Image.objects.create(image = image, article = article)

I've also discovered django formsets, which allows to have arbitrary number of forms (in my case an image form), but the problem with this approach is - it is against the usage of AJAX, and it make the page refreshes anytime a new image is uploaded...

So now I'm basically a lot confused like what's the best approach to doing something like this.
All suggestions are appreciated. And I'm also open to whole new approach as well (like using php etc...)

Body:
Maybe you need to create Image model which has a post id field as a foreign key.

def get_image_filename(instance, filename):
    id = instance.article.id
    return "article_images/%s" % (id)

class Images(models.Model):
    article = models.ForeignKey(Article, default=None)
    image = models.ImageField(upload_to=get_image_filename,
                              verbose_name='Image')

And in forms.py, you can create Article Forma and ImageForm class for uploading images for the article.

class ArticleForm(forms.ModelForm):
    title = forms.CharField(max_length=128)
    content = forms.CharField(max_length=245, label="Item Description.")

    class Meta:
        model = Post
        fields = ('title', 'body', )

class ImageForm(forms.ModelForm):
    image = forms.ImageField(label='Image')
    class Meta:
        model = Images
        fields = ('image', )

Finally in views.py, you can create post function that deals with post request for images data.(this is just an example)

def post(request):
    ImageFormSet = modelformset_factory(Images,
                                        form=ImageForm, extra=3)
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        formset = ImageFormSet(request.POST, request.FILES,
                               queryset=Images.objects.none())
        if form.is_valid() and formset.is_valid():
            post = form.save(commit=False)
            post.user = request.user
            post.save()
            for form in formset.cleaned_data:
                image = form['image']
                photo = Images(post=post, image=image)
                photo.save()
            messages.success(request,
                             "Posted!")
            return HttpResponseRedirect("/")
        else:
            print form.errors, formset.errors
    else:
        form = ArticleForm()
        formset = ImageFormSet(queryset=Images.objects.none())
    return render(request, 'index.html',
                  {'articleForm': form, 'formset': formset},
                  context_instance=RequestContext(request))


问:
Tomcat / handling connections when use NIO mode
I have a web socket server which is runnnig on Tomcat.

Tomcat works in NIO – non-blocking I/O (many more connections than threads) mode.

maxConnections = 1000
  maxThreads = 200

Assuming 300 connections for example , all 300 users can be serve simultaneously by Tomcat ??

I mean, one thred from pool can switch between 2 ore more connections because of 300 > 200 ?

答:
While Tomcat can manage more connections than requests currently in-flight (meaning, work is actively being done on those requests), the in-flight requests are limited by the number of request-processing threads.

So if you have 200 threads, you can only work on 200 requests at a time. The other 300 requests will sit in a queue until a request-processing thread is available.

This The above situation is the case for "normal" requests using standard HTTP request-response.

If you switch into asynchronous mode, things change. If you upgrade the connection to Websocket, things also change. But those are completely different I/O and dispatch models where the term "request" sort of loses its original meaning.

I believe that Tomcat allocates a single thread per connection for an upgraded Websocket connection, and that thread will handle the connection and no others. So when upgrading to Websocket, you are turning Tomcat's request-dispatch model from one thread-per-request into one thread-per-connection.


问:
What does &H57 represent and how can I translate it for C#?
I'm trying to convert old VB.NET code into C# and I'm not sure about the current line and what it means really.

VB.NET:

```<code>Const REQUEST_EFI As Byte = &H57
</code>```

What would this be in c#?  I tried:

```<code>const byte request_efi = &H57;
</code>```

But it says

"H57 is not part of the current
  context".

First of all, how is &H57 a byte?  Second, it seems that the & operator has a different representation in this context aside from concatenation.  Third obviously being, how the heck do I re-write this for C#? lol.  Thanks!

答:
It is hexadecimal representation of the 87.
Use const byte request_efi = 0x57; or const byte request_efi = 87;

Body:
I'm trying to convert old VB.NET code into C# and I'm not sure about the current line and what it means really.

VB.NET:

Const REQUEST_EFI As Byte = &H57

What would this be in c#?  I tried:

const byte request_efi = &H57;

But it says

"H57 is not part of the current
  context".

First of all, how is &H57 a byte?  Second, it seems that the & operator has a different representation in this context aside from concatenation.  Third obviously being, how the heck do I re-write this for C#? lol.  Thanks!


问:
django how to include javascript in template
I'm working on a project and following the documentation. I didn't succeed to include javascript.

Here is my settings:

```<code>STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

STATIC_ROOT = '/static/'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)
</code>```

So, I have created a static folder with a javascipt file in my project.

myproject/static/app.js

my urls.py:

```<code>urlpatterns = [
    url(r'^$', 'app.views.home'),
    url(r'^admin/', include(admin.site.urls)),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

and in my template:
myproject/templates/base.html:

```<code><!DOCTYPE html>
<head>
  {% load static %}
  <script src="{% static 'app.js' %}"></script>
  <title>Site</title>
</head>
<body>
<img src="{% static 'img.png' %}" alt="Mon image" />
  {% block content %}{% endblock %}
</body>
</html>
</code>```

My other template:

```<code>{% block content %}
    hello world
{% endblock %}
</code>```

I have the "hello world" on

http://127.0.0.1:8000/

but i do not have my image or script.

I tried so many different things but I never succeed

答:
From my understanding, the STATICFILES_DIRS should be in the settings.py and defined like this:

```<code>STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
</code>```

Please check the documentation.

Body:
I'm working on a project and following the documentation. I didn't succeed to include javascript.

Here is my settings:

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

STATIC_ROOT = '/static/'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

So, I have created a static folder with a javascipt file in my project.

myproject/static/app.js

my urls.py:

urlpatterns = [
    url(r'^$', 'app.views.home'),
    url(r'^admin/', include(admin.site.urls)),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

and in my template:
myproject/templates/base.html:

<!DOCTYPE html>

  {% load static %}

  <title>Site</title>

  {% block content %}{% endblock %}

My other template:

{% block content %}
    hello world
{% endblock %}

I have the "hello world" on

http://127.0.0.1:8000/

but i do not have my image or script.

I tried so many different things but I never succeed

Body:
From my understanding, the STATICFILES_DIRS should be in the settings.py and defined like this:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

Please check the documentation.


问:
is there a way to accept all image mime types in node
i would like to accept only images to be stored however i have to specify every image extension,
is there a single line code like in other languages like java and PHP where i use image/*

here is the code requiring me to put every file extension in node

const fileFilter = (req, file, cb) => {
    if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/png'){
        //store image
    }
};```

答:
```<code>if (file.mimetype.match(/^image/))
</code>```

or

```<code>if (file.mimetype.indexOf('image/') > -1)
</code>```

or

```<code>if (file.mimetype.substr(0,6) == 'image/')
</code>```

Body:
if (file.mimetype.match(/^image/))

or

if (file.mimetype.indexOf('image/') > -1)

or

if (file.mimetype.substr(0,6) == 'image/')


问:
what is the query equivalence in postgresql
what is the equivalence query on postgresql?

Build database and tables

```<code>CREATE DATABASE IF NOT EXISTS lemonade;

use lemonade;

CREATE TABLE users (
    id int PRIMARY KEY NOT NULL auto_increment,
    name varchar(50) NOT NULL,
    email varchar(50) NOT NULL
);

CREATE TABLE memories (
    id int PRIMARY KEY NOT NULL auto_increment,
    content varchar(50) NOT NULL,
    userID int,
    FOREIGN KEY (userID) REFERENCES users(id)
);

INSERT INTO users (name, email) VALUES ("Ruan", "ruan@gmail.com");
INSERT INTO users (name, email) VALUES ("Pereira", "pereira@gmail.com");

INSERT INTO memories (content, userID) VALUES ("memoria 1", 1);
INSERT INTO memories (content, userID) VALUES ("memoria 2", 1);
INSERT INTO memories (content, userID) VALUES ("memoria 3", 2);
INSERT INTO memories (content, userID) VALUES ("memoria 4", 2);
</code>```

query on mysql:

```<code>select ANY_VALUE(m.id), ANY_VALUE(m.content), m.userID, ANY_VALUE(u.id), ANY_VALUE(u.name), ANY_VALUE(u.email) from memories m inner join users u on m.userID = u.id group by userID;
</code>```

result:
image with result of my query

query on postgresql:

?

result: expect result equal of up image

答:
I think you need DISTINCT ON ( expression ...) clause.

New code is

```<code>select distinct on(u.id)
m.id, m.content, m.userID, u.id, u.name, u.email
from memories m
inner join users u on m.userID = u.id;
</code>```

Note: DISTINCT ON is  Non-Standard SQL Clause.

Form more information see

Body:
what is the equivalence query on postgresql?

Build database and tables

CREATE DATABASE IF NOT EXISTS lemonade;

use lemonade;

CREATE TABLE users (
    id int PRIMARY KEY NOT NULL auto_increment,
    name varchar(50) NOT NULL,
    email varchar(50) NOT NULL
);

CREATE TABLE memories (
    id int PRIMARY KEY NOT NULL auto_increment,
    content varchar(50) NOT NULL,
    userID int,
    FOREIGN KEY (userID) REFERENCES users(id)
);

INSERT INTO users (name, email) VALUES ("Ruan", "ruan@gmail.com");
INSERT INTO users (name, email) VALUES ("Pereira", "pereira@gmail.com");

INSERT INTO memories (content, userID) VALUES ("memoria 1", 1);
INSERT INTO memories (content, userID) VALUES ("memoria 2", 1);
INSERT INTO memories (content, userID) VALUES ("memoria 3", 2);
INSERT INTO memories (content, userID) VALUES ("memoria 4", 2);

query on mysql:

select ANY_VALUE(m.id), ANY_VALUE(m.content), m.userID, ANY_VALUE(u.id), ANY_VALUE(u.name), ANY_VALUE(u.email) from memories m inner join users u on m.userID = u.id group by userID;

result:
image with result of my query

query on postgresql:

?

result: expect result equal of up image

Body:
I think you need DISTINCT ON ( expression ...) clause.

New code is

select distinct on(u.id)
m.id, m.content, m.userID, u.id, u.name, u.email
from memories m
inner join users u on m.userID = u.id;

Note: DISTINCT ON is  Non-Standard SQL Clause.

Form more information see


问:
Dynamic element reference in angular template driven forms
I am trying to generate form dynamically . I am trying to set element reference to ngModel dynamically but it is not working .

```<code> #{{item.name}}="ngModel"
</code>```

.Here is the code

```<code>  <input type={{item.type}} class={{item.className}} placeholder="{{item.placeholder}}"
  [(ngModel)]="item.value" name='{{item.name}}' #{{item.name}}="ngModel"
  [ngClass]="{ 'is-invalid': f.submitted && item.value==''}" [required]="item.required">
</code>```

Json

```<code>{
className: "form-control"
icon: "fa-font"
label: "TextBox"
layout: "row"
layoutList: (2) [{…}, {…}]
name: "textq6es58"
placeholder: "Enter your name"
required: true
toggle: true
type: "text"
}
</code>```

Is there any way to set Dynamic element reference in angular template driven forms?

答:
You can provide it as

```<code>[id]='variableName'
</code>```

so that the variableName will be the element reference ID.

Body:
I am trying to generate form dynamically . I am trying to set element reference to ngModel dynamically but it is not working .

 #{{item.name}}="ngModel"

.Here is the code

  <input type={{item.type}} class={{item.className}} placeholder="{{item.placeholder}}"
  [(ngModel)]="item.value" name='{{item.name}}' #{{item.name}}="ngModel"
  [ngClass]="{ 'is-invalid': f.submitted && item.value==''}" [required]="item.required">

Json

{
className: "form-control"
icon: "fa-font"
label: "TextBox"
layout: "row"
layoutList: (2) [{…}, {…}]
name: "textq6es58"
placeholder: "Enter your name"
required: true
toggle: true
type: "text"
}

Is there any way to set Dynamic element reference in angular template driven forms?

Body:
You can provide it as

[id]='variableName'

so that the variableName will be the element reference ID.


问:
How to extract an array from a List of anonymous objects
Could anyone please help with the following:

If I have a list declared as follows:

```<code>List<(uint u, string s)> list1 = new List<(uint u, string s)>();
</code>```

Is there a succinct LINQ statement that could extract a list of the uints in my list?

For example, if my list was initialised as:

```<code>list1.Add((1,"One"));
list1.Add((2,"Two"));
list1.Add((3,"Three"));
</code>```

How could I crate a List containing the numbers {1,2,3}

At the moment I create an array of uints an loop through the array, but how could this be done using LINQ?

Thanks for any help,
Mitch.

答:
Use a Select for projection and ToList to accumulate to a list.

```<code>var result = list1.Select(x => x.u).ToList();
</code>```

Body:
Could anyone please help with the following:

If I have a list declared as follows:

List<(uint u, string s)> list1 = new List<(uint u, string s)>();

Is there a succinct LINQ statement that could extract a list of the uints in my list?

For example, if my list was initialised as:

list1.Add((1,"One"));
list1.Add((2,"Two"));
list1.Add((3,"Three"));

How could I crate a List containing the numbers {1,2,3}

At the moment I create an array of uints an loop through the array, but how could this be done using LINQ?

Thanks for any help,
Mitch.

Body:
Use a Select for projection and ToList to accumulate to a list.

var result = list1.Select(x => x.u).ToList();


问:
gmaps4rails add image to infowindow
I have enjoyed using you gmaps_4_rails gem and am impressed with the ease of configuring it. The only problem that I have had and I have spent a great deal of time trying to get it working is how to add an image to an infowindow. I cant get the example:

```<code>def gmaps4rails_infowindow
  "<img src=\"#{self.picture}\"> #{self.name}"
end
</code>```

to work. I want to be able to do something like this in the infowindow     /public/images/#{name}.jpg width= 25 height = 32.

I eventually want to store the images on amazon s3 but have been working on my local macbook  to get the process working.

Any assistance would be greatly appreciated

答:
Simply do this:

```<code>def gmaps4rails_infowindow
  "<img src='/images/#{name}.jpg' width='25' height='32'> #{name}"
end
</code>```

Have a look here to be sure of what you do:
https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Security-Warning

Title: gmaps4rails add image to infowindow

Body:
I have enjoyed using you gmaps_4_rails gem and am impressed with the ease of configuring it. The only problem that I have had and I have spent a great deal of time trying to get it working is how to add an image to an infowindow. I cant get the example:

def gmaps4rails_infowindow
  " #{self.name}"
end

to work. I want to be able to do something like this in the infowindow     /public/images/#{name}.jpg width= 25 height = 32.

I eventually want to store the images on amazon s3 but have been working on my local macbook  to get the process working.

Any assistance would be greatly appreciated

Body:
Simply do this:

def gmaps4rails_infowindow
  "<img src='/images/#{name}.jpg' width='25' height='32'> #{name}"
end

Have a look here to be sure of what you do:
https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Security-Warning


问:
containers with ipv6 addresses can't connect to outside in k8s/calico environment
I am trying to test ipv6 connectivity in k8s environment, and installed calico network plugin; the issue is that the container can't ping to the ipv6 gateway or other addresses of the cluster nodes, the version of k8s and calico is v1.18.2  and calico v1.12(also tried v1.13); the configurations  as followings:

centos7, kernel is  4.4(upgraded)

opened ipv6 forwarding

net.ipv6.conf.all.forwarding = 1

net.ipv6.conf.default.forwarding = 1

calico config:

```<code>[root@k8s-master-01 ~]# calicoctl get ipp -owide
NAME                  CIDR            NAT    IPIPMODE   VXLANMODE   DISABLED   SELECTOR
default-ipv4-ippool   10.244.0.0/16   true   Never      Never       false      all()
default-ipv6-ippool   fc00:f00::/24   true   Never      Never       false      all()

within the pod, can see ipv6 address is allocated
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1440
        inet 10.244.36.196  netmask 255.255.255.255  broadcast 0.0.0.0
        inet6 fe80::a8c6:c1ff:fe61:258c  prefixlen 64  scopeid 0x20<link>
        inet6 fc00:fd8:4bce:9a48:4ab7:a333:5ec8:c684  prefixlen 128  scopeid 0x0<global>
        ether aa:c6:c1:61:25:8c  txqueuelen 0  (Ethernet)
        RX packets 23026  bytes 3522721 (3.3 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 24249  bytes 3598501 (3.4 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[root@k8s-worker-01 ~]# ip -6 route show
fc00:fd8:4bce:9a48:4ab7:a333:5ec8:c684 dev eth0 proto kernel metric 256 pref medium
fe80::/64 dev eth0 proto kernel metric 256 pref medium
default via fe80::ecee:eeff:feee:eeee dev eth0 metric 1024 pref medium
</code>```

actually, I captured the messages with tcpdump from the host, and can see some icmp requests came in to the like cali66e9f9aafee interface, but looks no furthur processing, I checked ip6tables and saw that no any packages came into the right CHAIN of masqurade

```<code>[root@k8s-worker-01 ~]# ip6tables -t nat -vnL
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    1    80 cali-PREROUTING  all      *      *       ::/0                 ::/0                 /* cali:6gwbT8clXdHdC1b1 */

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 791 packets, 63280 bytes)
 pkts bytes target     prot opt in     out     source               destination
  796 63680 cali-OUTPUT  all      *      *       ::/0                 ::/0                 /* cali:tVnHkvAo15HuiPy0 */

Chain POSTROUTING (policy ACCEPT 791 packets, 63280 bytes)
 pkts bytes target     prot opt in     out     source               destination
  796 63680 cali-POSTROUTING  all      *      *       ::/0                 ::/0                 /* cali:O3lYWMrLQYEMJtB5 */

Chain cali-OUTPUT (1 references)
 pkts bytes target     prot opt in     out     source               destination
  796 63680 cali-fip-dnat  all      *      *       ::/0                 ::/0                 /* cali:GBTAv2p5CwevEyJm */

Chain cali-POSTROUTING (1 references)
 pkts bytes target     prot opt in     out     source               destination
  796 63680 cali-fip-snat  all      *      *       ::/0                 ::/0                 /* cali:Z-c7XtVd2Bq7s_hA */
  796 63680 cali-nat-outgoing  all      *      *       ::/0                 ::/0                 /* cali:nYKhEzDlr11Jccal */

Chain cali-PREROUTING (1 references)
 pkts bytes target     prot opt in     out     source               destination
    1    80 cali-fip-dnat  all      *      *       ::/0                 ::/0                 /* cali:r6XmIziWUJsdOK6Z */

Chain cali-fip-dnat (2 references)
 pkts bytes target     prot opt in     out     source               destination

Chain cali-fip-snat (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain cali-nat-outgoing (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 MASQUERADE  all      *      *       ::/0                 ::/0                 /* cali:Ir_z2t1P6-CxTDof */ match-set cali60masq-ipam-pools src ! match-set cali60all-ipam-pools dst
</code>```

tried lots of times, but failed, did i missed something?

regards

答:
I had exactily the same issue with a similar CentOS7 setup.

Besides following the instruction on the calico website and securing that all nodes had ipv6 forwarding enabled the solution was setting the environment variable CALICO_IPV6POOL_NAT_OUTGOING to true for the install-cni in the initContainers section and for the calico-node in the containers section.

In my case I also had to set the IP_AUTODETECTION_METHOD to my actual interface with the public v6 IP address.

I also explicitly added --proxy-mode=iptables to the kube-proxy parameters (which I'm not sure if it is default).

I hope this helps.

Body:
I am trying to test ipv6 connectivity in k8s environment, and installed calico network plugin; the issue is that the container can't ping to the ipv6 gateway or other addresses of the cluster nodes, the version of k8s and calico is v1.18.2  and calico v1.12(also tried v1.13); the configurations  as followings:

centos7, kernel is  4.4(upgraded)

opened ipv6 forwarding

net.ipv6.conf.all.forwarding = 1

net.ipv6.conf.default.forwarding = 1

calico config:

[root@k8s-master-01 ~]# calicoctl get ipp -owide
NAME                  CIDR            NAT    IPIPMODE   VXLANMODE   DISABLED   SELECTOR
default-ipv4-ippool   10.244.0.0/16   true   Never      Never       false      all()
default-ipv6-ippool   fc00:f00::/24   true   Never      Never       false      all()

within the pod, can see ipv6 address is allocated
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1440
        inet 10.244.36.196  netmask 255.255.255.255  broadcast 0.0.0.0
        inet6 fe80::a8c6:c1ff:fe61:258c  prefixlen 64  scopeid 0x20<link>
        inet6 fc00:fd8:4bce:9a48:4ab7:a333:5ec8:c684  prefixlen 128  scopeid 0x0<global>
        ether aa:c6:c1:61:25:8c  txqueuelen 0  (Ethernet)
        RX packets 23026  bytes 3522721 (3.3 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 24249  bytes 3598501 (3.4 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[root@k8s-worker-01 ~]# ip -6 route show
fc00:fd8:4bce:9a48:4ab7:a333:5ec8:c684 dev eth0 proto kernel metric 256 pref medium
fe80::/64 dev eth0 proto kernel metric 256 pref medium
default via fe80::ecee:eeff:feee:eeee dev eth0 metric 1024 pref medium

actually, I captured the messages with tcpdump from the host, and can see some icmp requests came in to the like cali66e9f9aafee interface, but looks no furthur processing, I checked ip6tables and saw that no any packages came into the right CHAIN of masqurade

[root@k8s-worker-01 ~]# ip6tables -t nat -vnL
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    1    80 cali-PREROUTING  all      *      *       ::/0                 ::/0                 /* cali:6gwbT8clXdHdC1b1 */

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 791 packets, 63280 bytes)
 pkts bytes target     prot opt in     out     source               destination
  796 63680 cali-OUTPUT  all      *      *       ::/0                 ::/0                 /* cali:tVnHkvAo15HuiPy0 */

Chain POSTROUTING (policy ACCEPT 791 packets, 63280 bytes)
 pkts bytes target     prot opt in     out     source               destination
  796 63680 cali-POSTROUTING  all      *      *       ::/0                 ::/0                 /* cali:O3lYWMrLQYEMJtB5 */

Chain cali-OUTPUT (1 references)
 pkts bytes target     prot opt in     out     source               destination
  796 63680 cali-fip-dnat  all      *      *       ::/0                 ::/0                 /* cali:GBTAv2p5CwevEyJm */

Chain cali-POSTROUTING (1 references)
 pkts bytes target     prot opt in     out     source               destination
  796 63680 cali-fip-snat  all      *      *       ::/0                 ::/0                 /* cali:Z-c7XtVd2Bq7s_hA */
  796 63680 cali-nat-outgoing  all      *      *       ::/0                 ::/0                 /* cali:nYKhEzDlr11Jccal */

Chain cali-PREROUTING (1 references)
 pkts bytes target     prot opt in     out     source               destination
    1    80 cali-fip-dnat  all      *      *       ::/0                 ::/0                 /* cali:r6XmIziWUJsdOK6Z */

Chain cali-fip-dnat (2 references)
 pkts bytes target     prot opt in     out     source               destination

Chain cali-fip-snat (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain cali-nat-outgoing (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 MASQUERADE  all      *      *       ::/0                 ::/0                 /* cali:Ir_z2t1P6-CxTDof */ match-set cali60masq-ipam-pools src ! match-set cali60all-ipam-pools dst

tried lots of times, but failed, did i missed something?

regards


问:
What is the correct way to send suggestions to the user with the [Suggestions] response type?
I have tried for what feels like hours to get the Composer to send a suggestion back to the user. I want the suggestion, if clicked, to open another website.

First, I created a template:

```<code># urlCard(title, value)
[CardAction
    Type = openUrl
    Title = ${title}
    Value = ${value}
]
</code>```

This works fine if I use it from a hero card, for example:

```<code>[HeroCard
      title = Click that button
      text = This is a test hero card
      buttons = ${urlCard( 'Google', 'https://google.com/' )}
    ]
</code>```

But I cannot get suggestions to work with [Suggestions:

```<code>[Suggestions
      SuggestionActions = ${urlCard( 'Google', 'https://google.com/' )}
    ]
</code>```

This is what I see in the Bot Framework Emulator:

How can I send suggestions to the user, without being in a hero card?

答:
I have no experience with the Composer but I can tell you how the Python API works and maybe it can help you to figure this out.

In Python (JS is very similar) you would do something like:

```<code>CardAction(title="Yes?", type=ActionTypes.im_back, value='yes')
CardAction(title="No?", type=ActionTypes.im_back, value='no')
</code>```

The suggested actions disappear after the user makes a selection and the bot will receive a message with the action value. I don't think you can embed a URL however, so maybe this is the actual issue you have.

Body:
I have tried for what feels like hours to get the Composer to send a suggestion back to the user. I want the suggestion, if clicked, to open another website.

First, I created a template:

# urlCard(title, value)
[CardAction
    Type = openUrl
    Title = ${title}
    Value = ${value}
]

This works fine if I use it from a hero card, for example:

[HeroCard
      title = Click that button
      text = This is a test hero card
      buttons = ${urlCard( 'Google', 'https://google.com/' )}
    ]

But I cannot get suggestions to work with [Suggestions:

[Suggestions
      SuggestionActions = ${urlCard( 'Google', 'https://google.com/' )}
    ]

This is what I see in the Bot Framework Emulator:

How can I send suggestions to the user, without being in a hero card?

Body:
I have no experience with the Composer but I can tell you how the Python API works and maybe it can help you to figure this out.

In Python (JS is very similar) you would do something like:

CardAction(title="Yes?", type=ActionTypes.im_back, value='yes')
CardAction(title="No?", type=ActionTypes.im_back, value='no')

The suggested actions disappear after the user makes a selection and the bot will receive a message with the action value. I don't think you can embed a URL however, so maybe this is the actual issue you have.