问:
Change actor color after window is rendered
I'm trying to change the color of one of the actors. Seems like the method SetColor(colors.GetColor3d("Silver")) is not working.

I'm also tried with b.GetMapper().ScalarVisibilityOff() but doesn´t work.

```<code>import vtk

colors = vtk.vtkNamedColors()

def crear_superficie(*puntos):

    points = vtk.vtkPoints()
    polygon = vtk.vtkPolygon()
    polygon.GetPointIds().SetNumberOfIds(len(puntos))
    for i, p in enumerate(puntos):
        points.InsertNextPoint(*p)
        polygon.GetPointIds().SetId(i, i)
    polygons = vtk.vtkCellArray()
    polygons.InsertNextCell(polygon)

    # Create a PolyData
    polygonPolyData = vtk.vtkPolyData()
    polygonPolyData.SetPoints(points)
    polygonPolyData.SetPolys(polygons)

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polygonPolyData)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().EdgeVisibilityOn()
    actor.GetProperty().SetLineWidth(2)
    actor.GetProperty().SetColor(colors.GetColor3d("Banana"))

    return actor

def main():

    a = crear_superficie((0, 0, 0), (0, 6, 0), (15, 10, 0), (30, 6, 0), (30, 0, 0))
    b = crear_superficie((0, 6, 0), (15, 10, 0), (15, 10, 60), (0, 6, 60))
   # Add the polygon to a list of polygons

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Polygon")
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(a)
    renderer.AddActor(b)
    renderer.SetBackground(colors.GetColor3d("Silver"))
    renderWindow.Render()
    renderWindowInteractor.Start()
    b.GetProperty().SetColor(colors.GetColor3d("Silver"))

if __name__ == '__main__':
   main()
</code>```

EDIT:

After call Render like Nico suggested I get this Warning:

```<code>2020-06-01 12:45:40.413 (   5.598s) [                ]     vtkOpenGLState.cxx:1380  WARN| Hardware does not support the number of textures defined.2020-06-01 12:45:40.467 (   5.652s) [                ]     vtkOpenGLState.cxx:1380  WARN| Hardware does not support the number of textures defined.2020-06-01 12:45:40.484 (   5.669s) [                ]   vtkShaderProgram.cxx:437    ERR| vtkShaderProgram (000002380CB1D770): 1: #version 150
2: #ifndef GL_ES
3: #define highp
4: #define mediump
5: #define lowp
6: #endif // GL_ES
7: #define attribute in
8: #define varying out
9:
10:
11: /*=========================================================================
12:
13:   Program:   Visualization Toolkit
14:   Module:    vtkPolyDataVS.glsl
15:
16:   Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
17:   All rights reserved.
18:   See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
19:
20:      This software is distributed WITHOUT ANY WARRANTY; without even
21:      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
22:      PURPOSE.  See the above copyright notice for more information.
23:
24: =========================================================================*/
25:
26: in vec4 vertexMC;
27:
28:
29:
30: // frag position in VC
31: out vec4 vertexVCVSOutput;
32:
33: // optional normal declaration
34: //VTK::Normal::Dec
35:
36: // extra lighting parameters
37: //VTK::Light::Dec
38:
39: // Texture coordinates
40: //VTK::TCoord::Dec
41:
42: // material property values
43: //VTK::Color::Dec
44:
45: // clipping plane vars
46: //VTK::Clip::Dec
47:
48: // camera and actor matrix values
49: uniform mat4 MCDCMatrix;
50: uniform mat4 MCVCMatrix;
51:
52: // Apple Bug
53: //VTK::PrimID::Dec
54:
55: // Value raster
56: //VTK::ValuePass::Dec
57:
58: // picking support
59: //VTK::Picking::Dec
60:
61: void main()
62: {
63:   //VTK::Color::Impl
64:
65:   //VTK::Normal::Impl
66:
67:   //VTK::TCoord::Impl
68:
69:   //VTK::Clip::Impl
70:
71:   //VTK::PrimID::Impl
72:
73:   vertexVCVSOutput = MCVCMatrix * vertexMC;
74:   gl_Position = MCDCMatrix * vertexMC;
75:
76:
77:   //VTK::ValuePass::Impl
78:
79:   //VTK::Light::Impl
80:
81:   //VTK::Picking::Impl
82: }

2020-06-01 12:45:41.157 (   6.341s) [                ]   vtkShaderProgram.cxx:438    ERR| vtkShaderProgram (000002380CB1D770): Could not create shader object.
</code>```

答:
VTK works on a lazy evaluation mode to preserve performance. You should manually ask for rendering after modifications if you want to see them.

So add a renderWindow.Render() after the SetColor(colors.GetColor3d("Silver")) line

Body:
I'm trying to change the color of one of the actors. Seems like the method SetColor(colors.GetColor3d("Silver")) is not working.

I'm also tried with b.GetMapper().ScalarVisibilityOff() but doesn´t work.

import vtk

colors = vtk.vtkNamedColors()

def crear_superficie(*puntos):

    points = vtk.vtkPoints()
    polygon = vtk.vtkPolygon()
    polygon.GetPointIds().SetNumberOfIds(len(puntos))
    for i, p in enumerate(puntos):
        points.InsertNextPoint(*p)
        polygon.GetPointIds().SetId(i, i)
    polygons = vtk.vtkCellArray()
    polygons.InsertNextCell(polygon)

    # Create a PolyData
    polygonPolyData = vtk.vtkPolyData()
    polygonPolyData.SetPoints(points)
    polygonPolyData.SetPolys(polygons)

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polygonPolyData)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().EdgeVisibilityOn()
    actor.GetProperty().SetLineWidth(2)
    actor.GetProperty().SetColor(colors.GetColor3d("Banana"))

    return actor

def main():

    a = crear_superficie((0, 0, 0), (0, 6, 0), (15, 10, 0), (30, 6, 0), (30, 0, 0))
    b = crear_superficie((0, 6, 0), (15, 10, 0), (15, 10, 60), (0, 6, 60))
   # Add the polygon to a list of polygons

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetWindowName("Polygon")
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(a)
    renderer.AddActor(b)
    renderer.SetBackground(colors.GetColor3d("Silver"))
    renderWindow.Render()
    renderWindowInteractor.Start()
    b.GetProperty().SetColor(colors.GetColor3d("Silver"))

if __name__ == '__main__':
   main()

EDIT:

After call Render like Nico suggested I get this Warning:

2020-06-01 12:45:40.413 (   5.598s) [                ]     vtkOpenGLState.cxx:1380  WARN| Hardware does not support the number of textures defined.2020-06-01 12:45:40.467 (   5.652s) [                ]     vtkOpenGLState.cxx:1380  WARN| Hardware does not support the number of textures defined.2020-06-01 12:45:40.484 (   5.669s) [                ]   vtkShaderProgram.cxx:437    ERR| vtkShaderProgram (000002380CB1D770): 1: #version 150
2: #ifndef GL_ES
3: #define highp
4: #define mediump
5: #define lowp
6: #endif // GL_ES
7: #define attribute in
8: #define varying out
9:
10:
11: /*=========================================================================
12:
13:   Program:   Visualization Toolkit
14:   Module:    vtkPolyDataVS.glsl
15:
16:   Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
17:   All rights reserved.
18:   See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
19:
20:      This software is distributed WITHOUT ANY WARRANTY; without even
21:      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
22:      PURPOSE.  See the above copyright notice for more information.
23:
24: =========================================================================*/
25:
26: in vec4 vertexMC;
27:
28:
29:
30: // frag position in VC
31: out vec4 vertexVCVSOutput;
32:
33: // optional normal declaration
34: //VTK::Normal::Dec
35:
36: // extra lighting parameters
37: //VTK::Light::Dec
38:
39: // Texture coordinates
40: //VTK::TCoord::Dec
41:
42: // material property values
43: //VTK::Color::Dec
44:
45: // clipping plane vars
46: //VTK::Clip::Dec
47:
48: // camera and actor matrix values
49: uniform mat4 MCDCMatrix;
50: uniform mat4 MCVCMatrix;
51:
52: // Apple Bug
53: //VTK::PrimID::Dec
54:
55: // Value raster
56: //VTK::ValuePass::Dec
57:
58: // picking support
59: //VTK::Picking::Dec
60:
61: void main()
62: {
63:   //VTK::Color::Impl
64:
65:   //VTK::Normal::Impl
66:
67:   //VTK::TCoord::Impl
68:
69:   //VTK::Clip::Impl
70:
71:   //VTK::PrimID::Impl
72:
73:   vertexVCVSOutput = MCVCMatrix * vertexMC;
74:   gl_Position = MCDCMatrix * vertexMC;
75:
76:
77:   //VTK::ValuePass::Impl
78:
79:   //VTK::Light::Impl
80:
81:   //VTK::Picking::Impl
82: }

2020-06-01 12:45:41.157 (   6.341s) [                ]   vtkShaderProgram.cxx:438    ERR| vtkShaderProgram (000002380CB1D770): Could not create shader object.


来源: stackexchange

问:
wtforms validate_on_submit with empty values behaviour
I would like a little bit of help into understanding how the validation function in this case. I have the following code:
1. forms.py - here I define my form

```<code>    from flask_wtf import FlaskForm
    from wtforms import StringField, PasswordField, SubmitField, BooleanField
    import email_validator
    from wtforms.validators import DataRequired, Length, Email, EqualTo

    class RegistrationForm(FlaskForm):
        username = StringField('Username',
                               validators=[DataRequired(),
                                           Length(min=2, max=20)])

        email = StringField('Email',
                            validators=[DataRequired(), Email()])

        password = PasswordField('Password',
                                 validators=[DataRequired()])

        confirm_password = PasswordField('Confirm Password',
                                         validators=[DataRequired(),
                                                     EqualTo('password')])

        submit = SubmitField('Sign Up')
</code>```

app.py - the main app

```<code>    from flask import Flask, render_template, url_for, flash, redirect
    from forms import RegistrationForm, LoginForm

    app = Flask(__name__)

    app.config['SECRET_KEY'] = 'giberish'

    @app.route("/")
    @app.route("/home")
    def home():
        return render_template("home.html", title="Home", posts=posts)

    @app.route('/register', methods=['GET', 'POST'])
    def register():
        form = RegistrationForm()
        if form.validate_on_submit():
            flash(f'Account created for {form.username.data}!', 'success')
            return redirect(url_for('home'))
        return render_template('register.html', title='register', form=form)

    if __name__ == '__main__':
        app.run(debug=True)
</code>```

register.html - the template

```<code>{% extends "layout.html" %}
{% block content %}
  <div class="content-section">
    <form method="POST" action="">
      {{ form.hidden_tag() }}
      <fieldset class="form-group">
        <legend class="border-bottom mb-4">Join Today</legend>
        <div class="form-group">
          {{ form.username.label(class="form-control-label") }}
          {% if form.username.errors %}
            {{ form.username(class="form-control form-control-lg is-invalid") }}
            <div class="invalid-feedback">
              {% for error in form.username.errors %}
                <span>{{ error }}</span>
              {% endfor %}
            </div>
            {% else %}
            {{ form.username(class="form-control form-control-lg") }}
          {% endif %}
        </div>
        <div class="form-group">
          {{ form.email.label(class="form-control-label") }}
          {% if form.email.errors %}
            {{ form.email(class="form-control form-control-lg is-invalid") }}
            <div class="invalid-feedback">
              {% for error in form.email.errors %}
                <span>{{ error }}</span>
              {% endfor %}
            </div>
          {% else %}
            {{ form.email(class="form-control form-control-lg") }}
          {% endif %}
        </div>
        <div class="form-group">
          {{ form.password.label(class="form-control-label") }}
          {% if form.password.errors %}
            {{ form.password(class="form-control form-control-lg is-invalid") }}
            <div class="invalid-feedback">
              {% for error in form.password.errors %}
                <span>{{ error }}</span>
              {% endfor %}
            </div>
          {% else %}
            {{ form.password(class="form-control form-control-lg") }}
          {% endif %}
        </div>
        <div class="form-group">
          {{ form.confirm_password.label(class="form-control-label") }}
          {% if form.confirm_password.errors %}
            {{ form.confirm_password(class="form-control form-control-lg is-invalid") }}
            <div class="invalid-feedback">
              {% for error in form.confirm_password.errors %}
                <span>{{ error }}</span>
              {% endfor %}
            </div>
          {% else %}
            {{ form.confirm_password(class="form-control form-control-lg") }}
          {% endif %}
        </div>
      </fieldset>
      <div class="form-group">
        {{ form.submit(class="btn btn-outline-info") }}
      </div>
  </div>
  <div class="border-top pt-3">
    <small class="text-muted">
      Already Have An Account? <a href="{{url_for('login')}}" class="ml-2">Sign In</a>.
    </small>
  </div>
  {% if form.errors %}
      {{ form.errors }}
  {% endif %}
{% endblock content %}
</code>```

As some could see this is from the videos of Corey Schafer and the code functions, but not exactly as expected at least in the case when I submit an empty form.

In the video from Corey when he submits an empty form than the form.field.errors gets populated and the errors are displayed below each field.

In my case I only get the fields with a red outline and a pop up with please fill in this field.
I would like to know if either I am doing something wrong or this is eventually a new behavior in form validation.

I spend several hours trying to understand and I have not managed. In the case when I fill in one character than the form.field.errors gets populated and the error messages are displayed.
My bed is on the fact that the DataRequired() validator is somehow short-circuiting the validation, but I am not 100% sure as I am a beginner in this.

I would appreciate also eventually a way of approaching this type of errors and where to look for such small details (into documentation or (my) code).

Thanks!

答:
I believe the reason for the above mentioned behaviour is due to this line from the docs :

class wtforms.validators.DataRequired(message=None) source

If the data is empty, also removes prior errors (such as processing errors) from the field.

So, to achieve what you want replace replace these :

```<code>username = StringField('Username', validators=[DataRequired(),Length(min=2, max=20)])
</code>```

with these :

```<code>username = StringField('Username', validators=[InputRequired(),Length(min=2, max=20)])
</code>```

Because according to the above linked documentation page:

Unless a very specific reason exists, we recommend using the InputRequired instead.

Let me know if that answers your question and resolves your issue :D

ContentLicense: CC BY-SA 4.0

Body:
I would like a little bit of help into understanding how the validation function in this case. I have the following code:
1. forms.py - here I define my form

    from flask_wtf import FlaskForm
    from wtforms import StringField, PasswordField, SubmitField, BooleanField
    import email_validator
    from wtforms.validators import DataRequired, Length, Email, EqualTo

    class RegistrationForm(FlaskForm):
        username = StringField('Username',
                               validators=[DataRequired(),
                                           Length(min=2, max=20)])

        email = StringField('Email',
                            validators=[DataRequired(), Email()])

        password = PasswordField('Password',
                                 validators=[DataRequired()])

        confirm_password = PasswordField('Confirm Password',
                                         validators=[DataRequired(),
                                                     EqualTo('password')])

        submit = SubmitField('Sign Up')

app.py - the main app

    from flask import Flask, render_template, url_for, flash, redirect
    from forms import RegistrationForm, LoginForm

    app = Flask(__name__)

    app.config['SECRET_KEY'] = 'giberish'

    @app.route("/")
    @app.route("/home")
    def home():
        return render_template("home.html", title="Home", posts=posts)

    @app.route('/register', methods=['GET', 'POST'])
    def register():
        form = RegistrationForm()
        if form.validate_on_submit():
            flash(f'Account created for {form.username.data}!', 'success')
            return redirect(url_for('home'))
        return render_template('register.html', title='register', form=form)

    if __name__ == '__main__':
        app.run(debug=True)

register.html - the template

{% extends "layout.html" %}
{% block content %}

    <form method="POST" action="">
      {{ form.hidden_tag() }}
      <fieldset class="form-group">
        <legend class="border-bottom mb-4">Join Today</legend>

          {{ form.username.label(class="form-control-label") }}
          {% if form.username.errors %}
            {{ form.username(class="form-control form-control-lg is-invalid") }}

              {% for error in form.username.errors %}
                {{ error }}
              {% endfor %}

            {% else %}
            {{ form.username(class="form-control form-control-lg") }}
          {% endif %}

          {{ form.email.label(class="form-control-label") }}
          {% if form.email.errors %}
            {{ form.email(class="form-control form-control-lg is-invalid") }}

              {% for error in form.email.errors %}
                {{ error }}
              {% endfor %}

          {% else %}
            {{ form.email(class="form-control form-control-lg") }}
          {% endif %}

          {{ form.password.label(class="form-control-label") }}
          {% if form.password.errors %}
            {{ form.password(class="form-control form-control-lg is-invalid") }}

              {% for error in form.password.errors %}
                {{ error }}
              {% endfor %}

          {% else %}
            {{ form.password(class="form-control form-control-lg") }}
          {% endif %}

          {{ form.confirm_password.label(class="form-control-label") }}
          {% if form.confirm_password.errors %}
            {{ form.confirm_password(class="form-control form-control-lg is-invalid") }}

              {% for error in form.confirm_password.errors %}
                {{ error }}
              {% endfor %}

          {% else %}
            {{ form.confirm_password(class="form-control form-control-lg") }}
          {% endif %}

      </fieldset>

        {{ form.submit(class="btn btn-outline-info") }}

      Already Have An Account? Sign In.

  {% if form.errors %}
      {{ form.errors }}
  {% endif %}
{% endblock content %}

As some could see this is from the videos of Corey Schafer and the code functions, but not exactly as expected at least in the case when I submit an empty form.

In the video from Corey when he submits an empty form than the form.field.errors gets populated and the errors are displayed below each field.

In my case I only get the fields with a red outline and a pop up with please fill in this field.
I would like to know if either I am doing something wrong or this is eventually a new behavior in form validation.

I spend several hours trying to understand and I have not managed. In the case when I fill in one character than the form.field.errors gets populated and the error messages are displayed.
My bed is on the fact that the DataRequired() validator is somehow short-circuiting the validation, but I am not 100% sure as I am a beginner in this.

I would appreciate also eventually a way of approaching this type of errors and where to look for such small details (into documentation or (my) code).

Thanks!

Body:
I believe the reason for the above mentioned behaviour is due to this line from the docs :

class wtforms.validators.DataRequired(message=None) source

If the data is empty, also removes prior errors (such as processing errors) from the field.

So, to achieve what you want replace replace these :

username = StringField('Username', validators=[DataRequired(),Length(min=2, max=20)])

with these :

username = StringField('Username', validators=[InputRequired(),Length(min=2, max=20)])

Because according to the above linked documentation page:

Unless a very specific reason exists, we recommend using the InputRequired instead.

Let me know if that answers your question and resolves your issue :D


问:
TabItem icon not showing with Material Components 1.1.0
Just upgraded my application to Material Components 1.1.0 and the icons in my TabLayout no longer display.
I followed the tutorial on the official website of google material.io, the preview in Android Studio is good, but once the application is launched, the icons do not appear.

Here is the XML Code :

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_gravity="bottom"
            style="@style/Widget.MaterialComponents.TabLayout.Colored"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="center">

            <com.google.android.material.tabs.TabItem
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:icon="@drawable/ic_home"/>

            <com.google.android.material.tabs.TabItem
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:icon="@drawable/ic_fav"/>

            <com.google.android.material.tabs.TabItem
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:icon="@drawable/ic_about"/>

        </com.google.android.material.tabs.TabLayout>

    </androidx.viewpager.widget.ViewPager>

</RelativeLayout>
```

<p>In my <strong>styles.xml</strong> file I defined <em>colorPrimary</em> and <em>colorOnPrimary</em> which are used to tint icons and TabLayout background color.</p>

<p>However, even if the preview in Android Studio is good, once the application is launched, the background of my TabLayout is displayed in the right color, but the icons don't show up.</p>

<p><strong>EDIT :</strong></p>

<p>Just use debug mode and icon of tabs are null for each tab item :</p>

<p><img src="https://i.stack.imgur.com/1RtVM.png" alt="enter image description here"></p>

<p><strong>EDIT 2:</strong></p>

<p>I have found the problem but not the solution!
The problem comes from this line :</p>

<pre class="lang-java prettyprint-override"><code>tabLayout.setupWithViewPager(viewPager)
</code>```

After this line is executed, all icons in TabLayout are reset to null.
By disabling this line I have all of my icons.
However, how can i setup a ViewPager with icons on my TabLayout ?
If I set them up manually, I will not have the color inherited from MDC

答:
The method tabLayout.setupWithViewPager() removes all tabs and then adds tabs from the adapted.

To add the icons you can use something like:

```<code>for (int i = 0; i < tabLayout.getTabCount(); i++) {
        tabLayout.getTabAt(i).setIcon(iconResId);
}
</code>```

If I set them up manually, I will not have the color inherited from MDC

The com.google.android.material.tabs.TabLayoutuses by default the Widget.MaterialComponents.TabLayout style. If you want to override the icon tint just use tabIconTint in your layout or custom style:

```<code><com.google.android.material.tabs.TabLayout
  app:tabIconTint="@color/my_selector"
  ...>
</code>```

Body:
Just upgraded my application to Material Components 1.1.0 and the icons in my TabLayout no longer display.
I followed the tutorial on the official website of google material.io, the preview in Android Studio is good, but once the application is launched, the icons do not appear.

Here is the XML Code :

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_gravity="bottom"
            style="@style/Widget.MaterialComponents.TabLayout.Colored"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="center">

            <com.google.android.material.tabs.TabItem
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:icon="@drawable/ic_home"/>

            <com.google.android.material.tabs.TabItem
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:icon="@drawable/ic_fav"/>

            <com.google.android.material.tabs.TabItem
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:icon="@drawable/ic_about"/>

        </com.google.android.material.tabs.TabLayout>

    </androidx.viewpager.widget.ViewPager>

</RelativeLayout>

In my styles.xml file I defined colorPrimary and colorOnPrimary which are used to tint icons and TabLayout background color.

However, even if the preview in Android Studio is good, once the application is launched, the background of my TabLayout is displayed in the right color, but the icons don't show up.

EDIT :

Just use debug mode and icon of tabs are null for each tab item :

EDIT 2:

I have found the problem but not the solution!
The problem comes from this line :

tabLayout.setupWithViewPager(viewPager)

After this line is executed, all icons in TabLayout are reset to null.
By disabling this line I have all of my icons.
However, how can i setup a ViewPager with icons on my TabLayout ?
If I set them up manually, I will not have the color inherited from MDC

Body:
The method tabLayout.setupWithViewPager() removes all tabs and then adds tabs from the adapted.

To add the icons you can use something like:

for (int i = 0; i < tabLayout.getTabCount(); i++) {
        tabLayout.getTabAt(i).setIcon(iconResId);
}

If I set them up manually, I will not have the color inherited from MDC

The com.google.android.material.tabs.TabLayoutuses by default the Widget.MaterialComponents.TabLayout style. If you want to override the icon tint just use tabIconTint in your layout or custom style:

<com.google.android.material.tabs.TabLayout
  app:tabIconTint="@color/my_selector"
  ...>


问:
kubernetes pending pod priority
I have the following pods on my kubernetes (1.18.3) cluster:

```<code>NAME      READY   STATUS    RESTARTS   AGE
pod1      1/1     Running   0          14m
pod2      1/1     Running   0          14m
pod3      0/1     Pending   0          14m
pod4      0/1     Pending   0          14m
</code>```

pod3 and pod4 cannot start because the node has capacity for 2 pods only. When pod1 finishes and quits, then the scheduler picks either pod3 or pod4 and starts it. So far so good.

However, I also have a high priority pod (hpod) that I'd like to start before pod3 or pod4 when either of the running pods finishes and quits.

So I created a priorityclass can be found in the kubernetes docs:

```<code>kind: PriorityClass
metadata:
  name: high-priority-no-preemption
value: 1000000
preemptionPolicy: Never
globalDefault: false
description: "This priority class should be used for XYZ service pods only."
</code>```

I've created the following pod yaml:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: hpod
  labels:
    app: hpod
spec:
  containers:
  - name: hpod
    image: ...
    resources:
      requests:
        cpu: "500m"
        memory: "500Mi"
      limits:
        cpu: "500m"
        memory: "500Mi"
  priorityClassName: high-priority-no-preemption
</code>```

Now the problem is that when I start the high prio pod with kubectl apply -f hpod.yaml, then the scheduler terminates a running pod to allow the high priority pod to start despite I've set 'preemptionPolicy: Never'.

The expected behaviour would be to postpone starting hpod until a currently running pod finishes. And when it does, then let hpod start before pod3 or pod4.

What am I doing wrong?

答:
Prerequisites:

This solution was tested on Kubernetes v1.18.3, docker 19.03 and Ubuntu 18.
Also text editor is required (i.e. sudo apt-get install vim).

In Kubernetes documentation under How to disable preemption you can find Note:

Note: In Kubernetes 1.15 and later, if the feature NonPreemptingPriority is enabled, PriorityClasses have the option to set preemptionPolicy: Never. This will prevent pods of that PriorityClass from preempting other pods.

Also under Non-preempting PriorityClass you have information:

The use of the PreemptionPolicy field requires the NonPreemptingPriority feature gate to be enabled.

Later if you will check thoses Feature Gates info, you will find that NonPreemptingPriority is false, so as default it's disabled.

Output with your current configuration:

```<code>$ kubectl get pods
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal     1/1     Running   0          32s
nginx-normal-2   1/1     Running   0          32s
$ kubectl apply -f prio.yaml
pod/nginx-priority created$ kubectl get pods
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal-2   1/1     Running   0          48s
nginx-priority   1/1     Running   0          8s
</code>```

To enable preemptionPolicy: Never you need to apply --feature-gates=NonPreemptingPriority=true to 3 files:

/etc/kubernetes/manifests/kube-apiserver.yaml

/etc/kubernetes/manifests/kube-controller-manager.yaml

/etc/kubernetes/manifests/kube-scheduler.yaml

To check if this feature-gate is enabled you can check by using commands:

```<code>ps aux | grep apiserver | grep feature-gates
ps aux | grep scheduler | grep feature-gates
ps aux | grep controller-manager | grep feature-gates
</code>```

For quite detailed information, why you have to edit thoses files please check this Github thread.

```<code>$ sudo su
# cd /etc/kubernetes/manifests/
# ls
etcd.yaml  kube-apiserver.yaml  kube-controller-manager.yaml  kube-scheduler.yaml
</code>```

Use your text editor to add feature gate to those files

```<code># vi kube-apiserver.yaml
</code>```

and add - --feature-gates=NonPreemptingPriority=true under spec.containers.command like in example bellow:

```<code>spec:
  containers:
  - command:
    - kube-apiserver
    - --feature-gates=NonPreemptingPriority=true
    - --advertise-address=10.154.0.31
</code>```

And do the same with 2 other files. After that you can check if this flags were applied.

```<code>$ ps aux | grep apiserver | grep feature-gates
root     26713 10.4  5.2 565416 402252 ?       Ssl  14:50   0:17 kube-apiserver --feature-gates=NonPreemptingPriority=true --advertise-address=10.154.0.31
</code>```

Now you have redeploy your PriorityClass.

```<code>$ kubectl get priorityclass
NAME                          VALUE        GLOBAL-DEFAULT   AGE
high-priority-no-preemption   1000000      false            12m
system-cluster-critical       2000000000   false            23m
system-node-critical          2000001000   false            23m
$ kubectl delete priorityclass high-priority-no-preemption
priorityclass.scheduling.k8s.io "high-priority-no-preemption" deleted
$ kubectl apply -f class.yaml
priorityclass.scheduling.k8s.io/high-priority-no-preemption created
</code>```

Last step is to deploy pod with this PriorityClass.

TEST

```<code>$ kubectl get po
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal     1/1     Running   0          4m4s
nginx-normal-2   1/1     Running   0          18m
$ kubectl apply -f prio.yaml
pod/nginx-priority created
$ kubectl get po
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal     1/1     Running   0          5m17s
nginx-normal-2   1/1     Running   0          20m
nginx-priority   0/1     Pending   0          67s
$ kubectl delete po nginx-normal-2
pod "nginx-normal-2" deleted
$ kubectl get po
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal     1/1     Running   0          5m55s
nginx-priority   1/1     Running   0          105s
</code>```

Title: kubernetes pending pod priority

Body:
I have the following pods on my kubernetes (1.18.3) cluster:

NAME      READY   STATUS    RESTARTS   AGE
pod1      1/1     Running   0          14m
pod2      1/1     Running   0          14m
pod3      0/1     Pending   0          14m
pod4      0/1     Pending   0          14m

pod3 and pod4 cannot start because the node has capacity for 2 pods only. When pod1 finishes and quits, then the scheduler picks either pod3 or pod4 and starts it. So far so good.

However, I also have a high priority pod (hpod) that I'd like to start before pod3 or pod4 when either of the running pods finishes and quits.

So I created a priorityclass can be found in the kubernetes docs:

kind: PriorityClass
metadata:
  name: high-priority-no-preemption
value: 1000000
preemptionPolicy: Never
globalDefault: false
description: "This priority class should be used for XYZ service pods only."

I've created the following pod yaml:

apiVersion: v1
kind: Pod
metadata:
  name: hpod
  labels:
    app: hpod
spec:
  containers:
  - name: hpod
    image: ...
    resources:
      requests:
        cpu: "500m"
        memory: "500Mi"
      limits:
        cpu: "500m"
        memory: "500Mi"
  priorityClassName: high-priority-no-preemption

Now the problem is that when I start the high prio pod with kubectl apply -f hpod.yaml, then the scheduler terminates a running pod to allow the high priority pod to start despite I've set 'preemptionPolicy: Never'.

The expected behaviour would be to postpone starting hpod until a currently running pod finishes. And when it does, then let hpod start before pod3 or pod4.

What am I doing wrong?

Body:
Prerequisites:

This solution was tested on Kubernetes v1.18.3, docker 19.03 and Ubuntu 18.
Also text editor is required (i.e. sudo apt-get install vim).

In Kubernetes documentation under How to disable preemption you can find Note:

Note: In Kubernetes 1.15 and later, if the feature NonPreemptingPriority is enabled, PriorityClasses have the option to set preemptionPolicy: Never. This will prevent pods of that PriorityClass from preempting other pods.

Also under Non-preempting PriorityClass you have information:

The use of the PreemptionPolicy field requires the NonPreemptingPriority feature gate to be enabled.

Later if you will check thoses Feature Gates info, you will find that NonPreemptingPriority is false, so as default it's disabled.

Output with your current configuration:

$ kubectl get pods
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal     1/1     Running   0          32s
nginx-normal-2   1/1     Running   0          32s
$ kubectl apply -f prio.yaml
pod/nginx-priority created$ kubectl get pods
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal-2   1/1     Running   0          48s
nginx-priority   1/1     Running   0          8s

To enable preemptionPolicy: Never you need to apply --feature-gates=NonPreemptingPriority=true to 3 files:

/etc/kubernetes/manifests/kube-apiserver.yaml

/etc/kubernetes/manifests/kube-controller-manager.yaml

/etc/kubernetes/manifests/kube-scheduler.yaml

To check if this feature-gate is enabled you can check by using commands:

ps aux | grep apiserver | grep feature-gates
ps aux | grep scheduler | grep feature-gates
ps aux | grep controller-manager | grep feature-gates

For quite detailed information, why you have to edit thoses files please check this Github thread.

$ sudo su
# cd /etc/kubernetes/manifests/
# ls
etcd.yaml  kube-apiserver.yaml  kube-controller-manager.yaml  kube-scheduler.yaml

Use your text editor to add feature gate to those files

# vi kube-apiserver.yaml

and add - --feature-gates=NonPreemptingPriority=true under spec.containers.command like in example bellow:

spec:
  containers:
  - command:
    - kube-apiserver
    - --feature-gates=NonPreemptingPriority=true
    - --advertise-address=10.154.0.31

And do the same with 2 other files. After that you can check if this flags were applied.

$ ps aux | grep apiserver | grep feature-gates
root     26713 10.4  5.2 565416 402252 ?       Ssl  14:50   0:17 kube-apiserver --feature-gates=NonPreemptingPriority=true --advertise-address=10.154.0.31

Now you have redeploy your PriorityClass.

$ kubectl get priorityclass
NAME                          VALUE        GLOBAL-DEFAULT   AGE
high-priority-no-preemption   1000000      false            12m
system-cluster-critical       2000000000   false            23m
system-node-critical          2000001000   false            23m
$ kubectl delete priorityclass high-priority-no-preemption
priorityclass.scheduling.k8s.io "high-priority-no-preemption" deleted
$ kubectl apply -f class.yaml
priorityclass.scheduling.k8s.io/high-priority-no-preemption created

Last step is to deploy pod with this PriorityClass.

TEST

$ kubectl get po
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal     1/1     Running   0          4m4s
nginx-normal-2   1/1     Running   0          18m
$ kubectl apply -f prio.yaml
pod/nginx-priority created
$ kubectl get po
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal     1/1     Running   0          5m17s
nginx-normal-2   1/1     Running   0          20m
nginx-priority   0/1     Pending   0          67s
$ kubectl delete po nginx-normal-2
pod "nginx-normal-2" deleted
$ kubectl get po
NAME             READY   STATUS    RESTARTS   AGE
nginx-normal     1/1     Running   0          5m55s
nginx-priority   1/1     Running   0          105s


问:
NodeJS Execute a bash script that prompts for keyboard input
I am trying to execute an external bash script from nodejs.

The script when executed from terminal, prompts for input, such as a password.

When executing from nodejs, i can not get it to pause to read the input.

Can not find any good info online on this.

Is this not possible?

```<code>var shelljs = require( 'shelljs' )

var returns     = shelljs.exec("passwd", {shell: '/bin/bash'}, {stdio:'inherit'});
</code>```

passwd: conversation failure

答:
```<code>  shelljs.exec("exec </dev/tty\n passwd", ... )

  seems to work. found by accident.
</code>```

Not sure if this is the best way though.

Not very solid i think.

Body:
I am trying to execute an external bash script from nodejs.

The script when executed from terminal, prompts for input, such as a password.

When executing from nodejs, i can not get it to pause to read the input.

Can not find any good info online on this.

Is this not possible?

var shelljs = require( 'shelljs' )

var returns     = shelljs.exec("passwd", {shell: '/bin/bash'}, {stdio:'inherit'});

passwd: conversation failure

Body:
  shelljs.exec("exec </dev/tty\n passwd", ... )

  seems to work. found by accident.

Not sure if this is the best way though.

Not very solid i think.


问:
Whats the point of DOCTYPE?
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks </p>

<p>UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01? </p>

答:
Browser Modes

Back in the past, Browsers implemented CSS to their own rules.

Only over the years have Browser now adapted the W3C standards.

To make sure that websites rendered correctly various browsers, web developers had to implement CSS according to the wishes of these browsers. Thus, most websites used CSS in ways that didn’t quite match the specifications.

Therefore, when standards compliancy became important browser vendors faced a tough choice. Moving closer to the W3C specifications was the way to go, but if they’d just change the CSS implementations to match the standards perfectly, many websites would break to a greater or lesser extent. Existing CSS would start to show odd side effects if it were suddenly interpreted in the correct way.

So moving closer to standards compliance would cause problems. On the other hand, not moving closer to standards compliance would perpetuate the general confusion of the Browser Wars Era.

To this end all Browser had to start supporting both modes. Quirks mode for older designs and standard mode for new design.

Paraphrased from here: Quirks mode and strict mode

DocTypes

Choosing which mode to use requires a trigger, and this trigger was found in ’doctype switching’.
  According to the standards, any (X)HTML document should have a doctype which tells the world at large which flavour of (X)HTML the document is using.

Taken from here too: Quirks mode and strict mode

Additonal Resources

Document Type Declaration

Quirks Mode on Wikipedia

Quirks mode and strict mode

Internet Explorer box model bug

The CSS box model

ContentLicense: CC BY-SA 3.0

Title: Whats the point of DOCTYPE?

Body:
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks

UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01?


问:
Python rotating the elements inside subarrays
I am trying to create two subarrays in given order, in this case i have two integers a and b a represents the value of the subarrays range, and b represents how many times it needs to be rotated.

I created the subarrays like this;

```<code>def reorder(a,b):
   return [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]
</code>```

Imagine a is 10 and b is 1 the output is:

```<code>[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
</code>```

But how can i reverse each subarrays b times?

The output that i want;

```<code>[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]
</code>```

答:
You can use a double ended que which has a built in rotate() function,

```<code>from collections import deque

def reorder(a,b):

   my_arr   = [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]
   first_q  = deque(my_arr[0])
   second_q = deque(my_arr[1])

   first_q.rotate(b)
   second_q.rotate(b)

   return [list(first_q), list(second_q)]

print(reorder(10, 1))
</code>```

Body:
I am trying to create two subarrays in given order, in this case i have two integers a and b a represents the value of the subarrays range, and b represents how many times it needs to be rotated.

I created the subarrays like this;

def reorder(a,b):
   return [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]

Imagine a is 10 and b is 1 the output is:

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]

But how can i reverse each subarrays b times?

The output that i want;

[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]

Body:
You can use a double ended que which has a built in rotate() function,

from collections import deque

def reorder(a,b):

   my_arr   = [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]
   first_q  = deque(my_arr[0])
   second_q = deque(my_arr[1])

   first_q.rotate(b)
   second_q.rotate(b)

   return [list(first_q), list(second_q)]

print(reorder(10, 1))


问:
Hover image not centred (CSS + JS)
In the following solution, I can't seem to be able to centre to the screen the image appearing at hover.

How can I solve this? Is this a CSS position issue or can be resolved in JS?

https://jsfiddle.net/Mengolor/2wzv6tr1/1/

```<code>div {
    position: relative;
    border: 1px solid gray;
    border-radius: 6px;
    width: 600px;
    height: auto;
    top: 250px;
    left: 100px;
}

img#image {
    position: absolute;
    display: none;
    z-index: 99;
    max-width: 50vw;
  transform: translate(-50%, -50%);
}

h3 {
  padding: 40px;
}

span:hover img#image {
    display: block;
  pointer-events: none;
}
</code>```

```<code>$(document).mousemove(function(e){
        const { scrollTop, scrollLeft } = document.documentElement;
    $("#image").css({left:e.clientX + scrollLeft, top:e.clientY + scrollTop});
});
</code>```

答:
Instead of making your position attribute relative, try position:center;

div {
 position: center;
 border: 1px solid gray;
 border-radius: 6px;
 width: 600px;
 height: auto;
 top: 250px;
 left: 100px;
}```

I tested this in the JSFiddle console, and it seemed to work.

Title: Hover image not centred (CSS + JS)

Body:
In the following solution, I can't seem to be able to centre to the screen the image appearing at hover.

How can I solve this? Is this a CSS position issue or can be resolved in JS?

https://jsfiddle.net/Mengolor/2wzv6tr1/1/

div {
    position: relative;
    border: 1px solid gray;
    border-radius: 6px;
    width: 600px;
    height: auto;
    top: 250px;
    left: 100px;
}

img#image {
    position: absolute;
    display: none;
    z-index: 99;
    max-width: 50vw;
  transform: translate(-50%, -50%);
}

h3 {
  padding: 40px;
}

span:hover img#image {
    display: block;
  pointer-events: none;
}

$(document).mousemove(function(e){
        const { scrollTop, scrollLeft } = document.documentElement;
    $("#image").css({left:e.clientX + scrollLeft, top:e.clientY + scrollTop});
});

Body:
Instead of making your position attribute relative, try position:center;

div {
 position: center;
 border: 1px solid gray;
 border-radius: 6px;
 width: 600px;
 height: auto;
 top: 250px;
 left: 100px;
}

I tested this in the JSFiddle console, and it seemed to work.


问:
Refactor using loop query
I want to refactor a loop query in rails in the below code:

```<code>users.each do |user|
  books+=(book.where(user_id: user))
end
</code>```

I found that, here I can use group_by or index. But could not understand how to do that?

Can someone please help me out with that.

答:
If I understand correctly, you just want all the books that belong to any of the users in your users array/relation.

Assuming you have a proper belongs_to :user in your Book model, the following query will do what you need. No group_by needed.

```<code>Book.where(user: users)
</code>```

An index in the database will still make it faster and as a rule of thumb all foreign keys should be indexed (exceptions exist of course)

Title: Refactor using loop query

Body:
I want to refactor a loop query in rails in the below code:

users.each do |user|
  books+=(book.where(user_id: user))
end

I found that, here I can use group_by or index. But could not understand how to do that?

Can someone please help me out with that.

Body:
If I understand correctly, you just want all the books that belong to any of the users in your users array/relation.

Assuming you have a proper belongs_to :user in your Book model, the following query will do what you need. No group_by needed.

Book.where(user: users)

An index in the database will still make it faster and as a rule of thumb all foreign keys should be indexed (exceptions exist of course)


问:
Prevent Browser Adding Light-Blue Background to Input Elements on Second Visit
When a form is filled out for a 2nd time and the browser recognises the details it adds a light-blue background to the form input elements on a site I'm building (which currently have the background set as transparent to show the dark blue background of the parent section). Image attached.

Is there a way to prevent this from happening?

It doesn't do it the first time of filling the form in, only if you input the details a second time after submission.

In the attached image I've left the fourth (bottom-right) field blank so you can see how it should look.

Thanks

答:
Why not just override the box-shadow of the input autofill property as shown in this other SO thread like this:

```<code>    input:-webkit-autofill {
        -webkit-box-shadow:0 0 0 50px white inset;
    }

    input:-webkit-autofill:focus {
        -webkit-box-shadow: 0 0 0 50px white inset;
    }
</code>```

I tried it on a dummy html form just now and the above (even without the text-fill-color property defined) seems to work fine in removing the blue background.

Body:
Why not just override the box-shadow of the input autofill property as shown in this other SO thread like this:

    input:-webkit-autofill {
        -webkit-box-shadow:0 0 0 50px white inset;
    }

    input:-webkit-autofill:focus {
        -webkit-box-shadow: 0 0 0 50px white inset;
    }

I tried it on a dummy html form just now and the above (even without the text-fill-color property defined) seems to work fine in removing the blue background.


问:
Python Error - Calculating Feature Geometry
I have a line of code in a GIS script tool that keeps giving me an error of "TypeError: 'tuple' object is not callable". It is to calculate the geometry of line features - the line begin and end point XY coordinates.

I do not know why I keep getting this error. Help is appreciated.

```<code>#Calcluate X & Y Values Of Network Begin/End Points
arcpy.CalculateGeometryAttributes_management(outfc, [["X_BEG", "LINE_START_X", "FEET_US"], ["Y_BEG", "LINE_START_Y", "FEET_US"]])
</code>```

答:
Your length unit "FEET_US" needs to be moved outside of the geometry properties lists and added as a separate input after the geometry properties

```<code>#Calcluate X & Y Values Of Network Begin/End Points
arcpy.CalculateGeometryAttributes_management(outfc, [["X_BEG", "LINE_START_X"], ["Y_BEG", "LINE_START_Y"]], "FEET_US")
</code>```

See: ESRI documentation for Calculate Geometry Attributes Code Sample

Body:
I have a line of code in a GIS script tool that keeps giving me an error of "TypeError: 'tuple' object is not callable". It is to calculate the geometry of line features - the line begin and end point XY coordinates.

I do not know why I keep getting this error. Help is appreciated.

#Calcluate X & Y Values Of Network Begin/End Points
arcpy.CalculateGeometryAttributes_management(outfc, [["X_BEG", "LINE_START_X", "FEET_US"], ["Y_BEG", "LINE_START_Y", "FEET_US"]])

Body:
Your length unit "FEET_US" needs to be moved outside of the geometry properties lists and added as a separate input after the geometry properties

#Calcluate X & Y Values Of Network Begin/End Points
arcpy.CalculateGeometryAttributes_management(outfc, [["X_BEG", "LINE_START_X"], ["Y_BEG", "LINE_START_Y"]], "FEET_US")

See: ESRI documentation for Calculate Geometry Attributes Code Sample


问:
Vuejs : Is there a event emitted when a particular tab gets active ( boostrap-vue )
I want to show and hide a div ( a section in my page ) when a particular b-tab is active and close it when it is not active ( open and close is achieved using 2 methods - forceOpenSettings and forceCloseSettings). Is there an event emitted when a particular tab gets active. So that I could link that to these methods. I could not find any when I checked bootstrap-vue documentation. The closest thing I found was this - https://bootstrap-vue.org/docs/components/tabs#programmatically-activating-and-deactivating-tabs

Tried using the activate and deactivate explained in this section like this, but it's not working

```<code><b-tab title="User Table" @activate="forceOpenSettings" @deactivate="forceCloseSettings"></b-tab>
</code>```

Case when it's working fine

The same thing working fine here. I wanted to open and close the same div but this time based on b-collapse. In the bootstrap-vue docs for b-collapse, I could find @hide and @show event emitters - https://bootstrap-vue.org/docs/components/collapse#comp-ref-b-collapse-events . Tried using that and it works fine. What i want is an event emitter similar to that when the tab is active and not active.

```<code><b-collapse role="tabpanel" @show="forceOpenSettings" @hide="forceCloseSettings"></b-collpase>
</code>```

NB - The section that is shown and hidden is another section in the page, not a child of b-tabs or b-collapse. I just want to open and close that div based on this tab and collapse. Collapse is working fine but the tab is not.

If there are no event emitters maybe I should write a method to achieve this. But it would be great if Vuejs has some event emitters to achieve this.

答:
Try something like this:</p>

```<code><b-tabs @input="onTabChange" ...
...
methods: {
  onTabChange () {
    // tab is changed!
  }
}
</code>```

Body:
I want to show and hide a div ( a section in my page ) when a particular b-tab is active and close it when it is not active ( open and close is achieved using 2 methods - forceOpenSettings and forceCloseSettings). Is there an event emitted when a particular tab gets active. So that I could link that to these methods. I could not find any when I checked bootstrap-vue documentation. The closest thing I found was this - https://bootstrap-vue.org/docs/components/tabs#programmatically-activating-and-deactivating-tabs

Tried using the activate and deactivate explained in this section like this, but it's not working

Case when it's working fine

The same thing working fine here. I wanted to open and close the same div but this time based on b-collapse. In the bootstrap-vue docs for b-collapse, I could find @hide and @show event emitters - https://bootstrap-vue.org/docs/components/collapse#comp-ref-b-collapse-events . Tried using that and it works fine. What i want is an event emitter similar to that when the tab is active and not active.

NB - The section that is shown and hidden is another section in the page, not a child of b-tabs or b-collapse. I just want to open and close that div based on this tab and collapse. Collapse is working fine but the tab is not.

If there are no event emitters maybe I should write a method to achieve this. But it would be great if Vuejs has some event emitters to achieve this.

Body:
Try something like this:

<b-tabs @input="onTabChange" ...
...
methods: {
  onTabChange () {
    // tab is changed!
  }
}


问:
Transfer an id via parameter in an html form
Good morning to you all,

I would like to transfer to my target page an id that I have upstream recovered with GET, in the sending form with a php parameter,

```<code>    <?php $idEleve = $_GET['id']; ?>
    <form method="POST" action="addNotes.php?id=$idEleve">
</code>```

I’m not sure it’s okay, please help me

答:
There are two options.

1) You can transfer it as a GET parameter to the next page in your form action attribute:

<form method="POST" action="addNotes.php?id=" . <?= $idEleve ?>
```

<p>Then receive it the same way:</p>

<pre class="lang-php prettyprint-override"><code>$idEleve = $_GET['id'];
</code>```

2) Use a hidden input field

<input type="hidden" name="id" value="<?= $idEleve ?>">
```

<p>In that case it will be a part of your <code>$_POST</code> array:</p>

<pre class="lang-php prettyprint-override"><code>$_POST['id']
</code>```

Body:
Good morning to you all,

I would like to transfer to my target page an id that I have upstream recovered with GET, in the sending form with a php parameter,

    <?php $idEleve = $_GET['id']; ?>
    <form method="POST" action="addNotes.php?id=$idEleve">

I’m not sure it’s okay, please help me

Body:
There are two options.

1) You can transfer it as a GET parameter to the next page in your form action attribute:

<form method="POST" action="addNotes.php?id=" . <?= $idEleve ?>

Then receive it the same way:

$idEleve = $_GET['id'];

2) Use a hidden input field

<input type="hidden" name="id" value="<?= $idEleve ?>">

In that case it will be a part of your $_POST array:

$_POST['id']


问:
python string split slice and into a list
I have a string for example "streemlocalbbv"

and I have my_function that takes this string and a string that I want to find ("loc") in the original string. And what I want to get returned is this;

```<code>my_function("streemlocalbbv", "loc")

output = ["streem","loc","albbv"]
</code>```

what I did so far is

```<code>def find_split(string,find_word):

    length = len(string)
    find_word_start_index = string.find(find_word)
    find_word_end_index = find_word_start_index + len(find_word)

    string[find_word_start_index:find_word_end_index]

    a = string[0:find_word_start_index]
    b = string[find_word_start_index:find_word_end_index]
    c = string[find_word_end_index:length]

    return [a,b,c]
</code>```

Trying to find the index of the string I am looking for in the original string, and then split the original string. But from here I am not sure how should I do it.

答:
Use the split function:

```<code>def find_split(string,find_word):
    ends = string.split(find_word)
    return [ends[0], find_word, ends[1]]
</code>```

Body:
I have a string for example "streemlocalbbv"

and I have my_function that takes this string and a string that I want to find ("loc") in the original string. And what I want to get returned is this;

my_function("streemlocalbbv", "loc")

output = ["streem","loc","albbv"]

what I did so far is

def find_split(string,find_word):

    length = len(string)
    find_word_start_index = string.find(find_word)
    find_word_end_index = find_word_start_index + len(find_word)

    string[find_word_start_index:find_word_end_index]

    a = string[0:find_word_start_index]
    b = string[find_word_start_index:find_word_end_index]
    c = string[find_word_end_index:length]

    return [a,b,c]

Trying to find the index of the string I am looking for in the original string, and then split the original string. But from here I am not sure how should I do it.

Body:
Use the split function:

def find_split(string,find_word):
    ends = string.split(find_word)
    return [ends[0], find_word, ends[1]]


问:
List of items placed inside a Swing environment
Hello i have a simple program that has a toolbar with furniture jbuttons and a placing area. I am cloning buttons from my toolbar and placing them inside my other panel. It is a room floor sketcher. What im trying to do is have a list of items i have placed so far.

I have a method to add my node to the board:

```<code>  nodes.add(n);

  if(n instanceof OvenNode){
     ovens.add(n);
     System.out.println("added a oven");

     ov++;
     oven = "Oven x";
     map.put("Oven", ov);
     oven += map.get("Oven");
     shoppingList.add(oven);
  }
  else if(n instanceof FridgeNode){
     fridges.add(n);
     System.out.println("added a fridge");
     shoppingList.add("Fridge");
     fr++;
     map.put("Fridge", fr);
  }
</code>```

And what i have tried so far is just creating an arraylist called shoppinglist and everytime i add a OvenNode it also adds a String Oven to the shopping list. There are other furniture peaces that also get added the same way

Then i have a method that turns that list into a string:

```<code>public String ListtoString(List<String> listen){

  String list = "";

  for (int i = 0; i < listen.size();i++) {

     String everything = listen.get(i).toString();

     list += everything  + " " + "\n";

  }

  return list;

}
</code>```

This method together with ..

```<code>public List<String> shoppingList(){
  return shoppingList;
}
</code>```

.. are called in:

```<code>  JMenuItem shoppingList = new JMenuItem("Shopping List");
  shoppingList.addActionListener(new ActionListener(){

     public void actionPerformed(ActionEvent event){
        text = new JTextArea(graph.ListtoString(graph.shoppingList()));
        JOptionPane.showMessageDialog(null,
                          text);

     }

  });
</code>```

And this is where my list is.

But it looks like this:

And I don't want it to be like this, I only want it to change the number and let the text be alone. So if there are 3 ovens and I add another one I should only increment the oven counter so it only has Oven x (the number that is incremented)

Is there something I can do in my ListtoString method like a substring so it cuts out the text part and only leaves the changing integer?

答:
So i worked on it and came up with a solution that might not be the cleanest one but at least it works:

`  public String getmeList(){

```<code>  String ovs = "Ovens x";

  ovs += ov;

  String space = "\n";

  String fri = "Fridges x";

  fri += fr;

  String tot = "\n";

  String tab = "Tables x";

  tab += ta;

  String bedz = "Bed x";

  bedz += be;

  String cotop = "Countertop x";

  cotop += sp;

  String win = "Window x";

  win += wi;

  String war = "Wardrobe x";

  war += wa;
</code>```

tot += ovs += space  += fri += space += tab += space += bedz += space += cotop += space += win += space += war;
      return tot;`

and now it i get this

it also works very well when i remove something, because i only decrement the counter in my remove method.

cheers

Body:
Hello i have a simple program that has a toolbar with furniture jbuttons and a placing area. I am cloning buttons from my toolbar and placing them inside my other panel. It is a room floor sketcher. What im trying to do is have a list of items i have placed so far.

I have a method to add my node to the board:

  nodes.add(n);

  if(n instanceof OvenNode){
     ovens.add(n);
     System.out.println("added a oven");

     ov++;
     oven = "Oven x";
     map.put("Oven", ov);
     oven += map.get("Oven");
     shoppingList.add(oven);
  }
  else if(n instanceof FridgeNode){
     fridges.add(n);
     System.out.println("added a fridge");
     shoppingList.add("Fridge");
     fr++;
     map.put("Fridge", fr);
  }

And what i have tried so far is just creating an arraylist called shoppinglist and everytime i add a OvenNode it also adds a String Oven to the shopping list. There are other furniture peaces that also get added the same way

Then i have a method that turns that list into a string:

public String ListtoString(List<String> listen){

  String list = "";

  for (int i = 0; i < listen.size();i++) {

     String everything = listen.get(i).toString();

     list += everything  + " " + "\n";

  }

  return list;

}

This method together with ..

public List<String> shoppingList(){
  return shoppingList;
}

.. are called in:

  JMenuItem shoppingList = new JMenuItem("Shopping List");
  shoppingList.addActionListener(new ActionListener(){

     public void actionPerformed(ActionEvent event){
        text = new JTextArea(graph.ListtoString(graph.shoppingList()));
        JOptionPane.showMessageDialog(null,
                          text);

     }

  });

And this is where my list is.

But it looks like this:

And I don't want it to be like this, I only want it to change the number and let the text be alone. So if there are 3 ovens and I add another one I should only increment the oven counter so it only has Oven x (the number that is incremented)

Is there something I can do in my ListtoString method like a substring so it cuts out the text part and only leaves the changing integer?

Body:
So i worked on it and came up with a solution that might not be the cleanest one but at least it works:

`  public String getmeList(){

  String ovs = "Ovens x";

  ovs += ov;

  String space = "\n";

  String fri = "Fridges x";

  fri += fr;

  String tot = "\n";

  String tab = "Tables x";

  tab += ta;

  String bedz = "Bed x";

  bedz += be;

  String cotop = "Countertop x";

  cotop += sp;

  String win = "Window x";

  win += wi;

  String war = "Wardrobe x";

  war += wa;

tot += ovs += space  += fri += space += tab += space += bedz += space += cotop += space += win += space += war;
      return tot;`

and now it i get this

it also works very well when i remove something, because i only decrement the counter in my remove method.

cheers


问:
sudo: no tty present and no askpass program specified when trying to run Shell script from JENKINS AWS instance
I am trying to run a basic docker command using shell script from my Jenkins in AWS Ubuntu instance.
When I am trying to run like:
sudo docker build mavendocker:1.0.0 .
I am getting below error:

I tried to change the visudo following:
How to fix 'sudo: no tty present and no askpass program specified' error?
but it screwed my visudo file of AWS Ubuntu instance.

Is there any other way, I can execute my Jenkins job?

答:
Above problem is resolved following:
https://sgoyal.net/2016/11/18/run-a-shell-from-jenkins-using-sudo-ubuntu/</p>


问:
Django error :sdr_media' is not a valid tag library: Template library sdr_media not found . How to remove this error?
My sdr_media.py is in this path .

```<code>geodjango/geographic_admin/templates/templatetags/sdr_media.py
</code>```

My layer_upload.html is in this folder

```<code>   geodjango/geographic_admin/template/maps
</code>```

The code is this

```<code>{% load sdr_media %}
</code>```

But , still the sdr_media tag is  not found . The templatetags folder has init.py for it to work . Is my path wrong ?

Edit

This is the sdr_media.py code

```<code>from django import template
from django.conf import settings

register = template.Library()

@register.tag('sdr_media')
def geonode_media(parser, token):
    try:
        tagname, argument = token.split_contents()
        argument = argument[1:-1] # get rid of quotes
        if not argument in settings.MEDIA_LOCATIONS:
            raise template.TemplateSyntaxError, '%s is not a valid resource name' % argument
        return MediaNode(argument)
    except ValueError:
        raise template.TemplateSyntaxError, '%r requires a single argument' % token.contents.split()[0]

class MediaNode(template.Node):
    def __init__(self, resource):
        self.resource = resource

    def render(self, context):
        return settings.MEDIA_LOCATIONS[self.resource]
</code>```

答:
I'd say: yes

The app should contain a templatetags
  directory, at the same level as
  models.py, views.py, etc. If this
  doesn’t already exist, create it

https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#code-layout

Body:
My sdr_media.py is in this path .

geodjango/geographic_admin/templates/templatetags/sdr_media.py

My layer_upload.html is in this folder

   geodjango/geographic_admin/template/maps

The code is this

{% load sdr_media %}

But , still the sdr_media tag is  not found . The templatetags folder has init.py for it to work . Is my path wrong ?

Edit

This is the sdr_media.py code

from django import template
from django.conf import settings

register = template.Library()

@register.tag('sdr_media')
def geonode_media(parser, token):
    try:
        tagname, argument = token.split_contents()
        argument = argument[1:-1] # get rid of quotes
        if not argument in settings.MEDIA_LOCATIONS:
            raise template.TemplateSyntaxError, '%s is not a valid resource name' % argument
        return MediaNode(argument)
    except ValueError:
        raise template.TemplateSyntaxError, '%r requires a single argument' % token.contents.split()[0]

class MediaNode(template.Node):
    def __init__(self, resource):
        self.resource = resource

    def render(self, context):
        return settings.MEDIA_LOCATIONS[self.resource]


问:
React Material UI passing updated Date through Multi Page App
I have created a multi page form and one of the pages that contains a datetime picker from material ui is not passing the updated date to the confirm page. I have created a sandbox. I have tried many methods including lifting the state, but none of it worked.
https://codesandbox.io/embed/inspiring-glade-74it3?fontsize=14&hidenavigation=1&theme=dark</p>

答: Hi I have updated Code Sandbox Please check it. You had lot of issue. You do destructuring props wrongly and again you put the prefered_date into a values objects. I cannot explain everything here instead, please check this fixing and read some article on react. You will have better understanding. Happy Learning :)


答:
You can use str.partition which does exactly what you want:

```<code>>>> "streemlocalbbv".partition("loc")
('streem', 'loc', 'albbv')
</code>```

Title: python string split slice and into a list

Body:
You can use str.partition which does exactly what you want:

>>> "streemlocalbbv".partition("loc")
('streem', 'loc', 'albbv')


问:
Angular async call inside an observable
I have a function to make expire date control for an Item.
In this function i create an observable that checks if the item is new or not.
If it´s new it works as expected but when a try to get some complementary data to define if its expiring date is when it does not work well.

If the call is made for a single Item it works fine but when i try to fill a table with several item it return undefined.

I think it is a matter of the async call. The subscriber is not waiting for the inner httprequest to finish before making a new call for the next item on the table.

1- Function that meke the call to get the expire date and set the proper status.

```<code> /* ValueGetter para mostrar en la tabla si la droga está vencida o vigente */
      ctlVigencia(params){
        let message: string;
        this.ds.ctlVencimientoDroga(params.data._id, params.data.informacion.fecha.vencimientoCertificado, null)
        .subscribe(res=> {
          console.log(res);

          if(res.fAsignada == null){
            message= 'No deterninado'
          } else {
            let now = moment(new Date());
            if (res.fAsignada > now ) {
              message= 'Vigente'
            } else {
              message= ('Vencida')
            }
          }
        })
        return message
      };
</code>```

2) Function that returns the value of the expiration date.

```<code>  /*Control vencimiento droga */
    ctlVencimientoDroga(idSelected: string, vencimientoCertificado: Date, modeForm?: string){
      let retesteos: Retesteo[];
      const resObs= Observable.create((observer:Observer<{[key: string]: any}>) =>{
        if (modeForm == 'nuevo'){
          observer.next({fAsignada: vencimientoCertificado})
          observer.complete();
        } else{
          this.rs.dataRetesteo.subscribe(res=>{
            retesteos= res;
            if (retesteos && retesteos.length == 0) {
              if(vencimientoCertificado != null) {
                observer.next({fAsignada: vencimientoCertificado});
              } else {
                observer.next(null);
              }
            }
            /* From here and down is where is the problem */
            if (retesteos && retesteos.length > 0){
              let fechaUltimoRetesteoAprobado: Date;
              retesteos.forEach(element => {
                if (element.estado.estado == estadoAprobacion.Aprobado && (fechaUltimoRetesteoAprobado == null || element.fVencimiento > fechaUltimoRetesteoAprobado )){
                  fechaUltimoRetesteoAprobado= element.fVencimiento
                }
              });
              observer.next({fAsignada: fechaUltimoRetesteoAprobado});
            }
            observer.complete();
          });
          this.rs.getById(idSelected);
        }
      })
      return resObs;
  }
}
</code>```

I appreciate your help.

答:
I would rewrite pretty much all of this to make use of operators...

```<code>  ctlVigencia(params){
     // use map operator, return observable
    return this.ds.ctlVencimientoDroga(params.data._id, params.data.informacion.fecha.vencimientoCertificado, null)
    .pipe(map(res=> {
      console.log(res);
      if(res.fAsignada == null){
        return 'No deterninado'
      } else {
        let now = moment(new Date());
        if (res.fAsignada > now ) {
          return 'Vigente'
        } else {
          return 'Vencida'
        }
      }
    }));
  };

ctlVencimientoDroga(idSelected: string, vencimientoCertificado: Date, modeForm?: string){
  let retesteos: Retesteo[];
  if (modeForm == 'nuevo') {
    // return mock observable
    return of({fAsignada: vencimientoCertificado});
  }
  // return this observable and use map operator
  return this.rs.dataRetesteo.pipe(
      map(res=> {
        retesteos = res;
        if (retesteos && retesteos.length == 0) {
          if(vencimientoCertificado != null) {
            return {fAsignada: vencimientoCertificado};
          } else {
            return null;
          }
        } else {
          let fechaUltimoRetesteoAprobado: Date;
          retesteos.forEach(element => {
            if (element.estado.estado == estadoAprobacion.Aprobado && (fechaUltimoRetesteoAprobado == null || element.fVencimiento > fechaUltimoRetesteoAprobado )){
              fechaUltimoRetesteoAprobado = element.fVencimiento
            }
          });
          this.rs.getById(idSelected); // unclear why or when this should happen
          return {fAsignada: fechaUltimoRetesteoAprobado};
        }
      })
  );
}
</code>```

then whoever wants the value from ctlVigencia needs to subscribe to it.

Title: Angular async call inside an observable

Body:
I have a function to make expire date control for an Item.
In this function i create an observable that checks if the item is new or not.
If it´s new it works as expected but when a try to get some complementary data to define if its expiring date is when it does not work well.

If the call is made for a single Item it works fine but when i try to fill a table with several item it return undefined.

I think it is a matter of the async call. The subscriber is not waiting for the inner httprequest to finish before making a new call for the next item on the table.

1- Function that meke the call to get the expire date and set the proper status.

 /* ValueGetter para mostrar en la tabla si la droga está vencida o vigente */
      ctlVigencia(params){
        let message: string;
        this.ds.ctlVencimientoDroga(params.data._id, params.data.informacion.fecha.vencimientoCertificado, null)
        .subscribe(res=> {
          console.log(res);

          if(res.fAsignada == null){
            message= 'No deterninado'
          } else {
            let now = moment(new Date());
            if (res.fAsignada > now ) {
              message= 'Vigente'
            } else {
              message= ('Vencida')
            }
          }
        })
        return message
      };

2) Function that returns the value of the expiration date.

  /*Control vencimiento droga */
    ctlVencimientoDroga(idSelected: string, vencimientoCertificado: Date, modeForm?: string){
      let retesteos: Retesteo[];
      const resObs= Observable.create((observer:Observer<{[key: string]: any}>) =>{
        if (modeForm == 'nuevo'){
          observer.next({fAsignada: vencimientoCertificado})
          observer.complete();
        } else{
          this.rs.dataRetesteo.subscribe(res=>{
            retesteos= res;
            if (retesteos && retesteos.length == 0) {
              if(vencimientoCertificado != null) {
                observer.next({fAsignada: vencimientoCertificado});
              } else {
                observer.next(null);
              }
            }
            /* From here and down is where is the problem */
            if (retesteos && retesteos.length > 0){
              let fechaUltimoRetesteoAprobado: Date;
              retesteos.forEach(element => {
                if (element.estado.estado == estadoAprobacion.Aprobado && (fechaUltimoRetesteoAprobado == null || element.fVencimiento > fechaUltimoRetesteoAprobado )){
                  fechaUltimoRetesteoAprobado= element.fVencimiento
                }
              });
              observer.next({fAsignada: fechaUltimoRetesteoAprobado});
            }
            observer.complete();
          });
          this.rs.getById(idSelected);
        }
      })
      return resObs;
  }
}

I appreciate your help.

Body:
I would rewrite pretty much all of this to make use of operators...

  ctlVigencia(params){
     // use map operator, return observable
    return this.ds.ctlVencimientoDroga(params.data._id, params.data.informacion.fecha.vencimientoCertificado, null)
    .pipe(map(res=> {
      console.log(res);
      if(res.fAsignada == null){
        return 'No deterninado'
      } else {
        let now = moment(new Date());
        if (res.fAsignada > now ) {
          return 'Vigente'
        } else {
          return 'Vencida'
        }
      }
    }));
  };

ctlVencimientoDroga(idSelected: string, vencimientoCertificado: Date, modeForm?: string){
  let retesteos: Retesteo[];
  if (modeForm == 'nuevo') {
    // return mock observable
    return of({fAsignada: vencimientoCertificado});
  }
  // return this observable and use map operator
  return this.rs.dataRetesteo.pipe(
      map(res=> {
        retesteos = res;
        if (retesteos && retesteos.length == 0) {
          if(vencimientoCertificado != null) {
            return {fAsignada: vencimientoCertificado};
          } else {
            return null;
          }
        } else {
          let fechaUltimoRetesteoAprobado: Date;
          retesteos.forEach(element => {
            if (element.estado.estado == estadoAprobacion.Aprobado && (fechaUltimoRetesteoAprobado == null || element.fVencimiento > fechaUltimoRetesteoAprobado )){
              fechaUltimoRetesteoAprobado = element.fVencimiento
            }
          });
          this.rs.getById(idSelected); // unclear why or when this should happen
          return {fAsignada: fechaUltimoRetesteoAprobado};
        }
      })
  );
}

then whoever wants the value from ctlVigencia needs to subscribe to it.


问:
How to apply a custom function to nested dataframes?
I'm trying to apply a custom function to a nested dataframe

I want to apply a machine learning algorithm to predict NA values

After doing a bit of reading online, it seemed that the map function would be the most applicable here

I have a section of code that nests the dataframe and then splits the data into a test (data3) and train (data2) set - with the test dataset containing all the null values for the column to be predicted, and the train containing all the values that are not null to be used to train the ML model

```<code>dmaExtendedDataNA2 <- dmaExtendedDataNA %>%
                  group_by(dma) %>%
                  nest() %>%
                  mutate(data2 = map(data, ~filter(., !(is.na(mean_night_flow)))),
                         data3 = map(data, ~filter(., is.na(mean_night_flow))))
</code>```

Here is the function I intend to use:

```<code>    my_function (test,train) {
             et  <- extraTrees(x = train, y = train[, "mean_night_flow"], na.action = "fuse", ntree = 1000, nodesize = 2, mtry = ncol(train) * 0.9 )
             test1 <- test
             test1[ , "mean_night_flow"] <- 0
             pred  <- predict(et, newdata = test1[, "mean_night_flow"])
             test1[ , "mean_night_flow"] <- pred
             return(test1)
</code>```

I have tried the following code, however it does not work:

```<code>dmaExtendedDataNA2 <- dmaExtendedDataNA %>%
                      group_by(dma) %>%
                      nest() %>%
                      mutate(data2 = map(data, ~filter(., !(is.na(mean_night_flow)))),
                             data3 = map(data, ~filter(., is.na(mean_night_flow))),
                             data4 = map(data3, data2, ~my_function(.x,.y)))
</code>```

It gives the following error:

```<code>Error: Index 1 must have length 1, not 33
</code>```

This is suggests that it expects a column rather than a whole dataframe. How can I get this to work?

Many thanks

答:
Without testing on your data, I think you're using the wrong map function. purrr::map works on one argument (one list, one vector, whatever) and returns a list. You are passing it two values (data3 and data2), so we need to use:

dmaExtendedDataNA2 <- dmaExtendedDataNA %>%
                      group_by(dma) %>%
                      nest() %>%
                      mutate(data2 = map(data, ~filter(., !(is.na(mean_night_flow)))),
                             data3 = map(data, ~filter(., is.na(mean_night_flow))),
                             data4 = map2(data3, data2, ~my_function(.x,.y)))
```

<p>If you find yourself needing more than two, you need <code>pmap</code>. You can use <code>pmap</code> for 1 or 2 arguments, it's effectively the same. The two biggest differences when migrating from <code>map</code> to <code>pmap</code> are:</p>

<ul>
<li><p>your arguments need to be enclosed within a list, so</p>

<pre class="lang-r prettyprint-override"><code>map2(data3, data12, ...)
</code>```

becomes

pmap(list(data3, data12), ...)
```</li>
<li><p>you refer to them with double-dot number position, <code>..1</code>, <code>..2</code>, <code>..3</code>, etc, so</p>

<pre class="lang-r prettyprint-override"><code>~ my_function(.x, .y)
</code>```

becomes

~ my_function(..1, ..2)
```</li>
</ul>

<hr>

<p>An alternative that simplifies your overall flow just a little.</p>

<pre class="lang-r prettyprint-override"><code>my_function (test, train = NULL, fld = "mean_night_flow") {
  if (is.null(train)) {
    train <- test[ !is.na(test[[fld]]),, drop = FALSE ]
    test <- test[ is.na(test[[fld]]),, drop = FALSE ]
  }
  et  <- extraTrees(x = train, y = train[, fld], na.action = "fuse", ntree = 1000, nodesize = 2, mtry = ncol(train) * 0.9 )
  test1 <- test
  test1[ , fld] <- 0
  pred  <- predict(et, newdata = test1[, fld])
  test1[ , fld] <- pred
  return(test1)
}
</code>```

which auto-populates train based on the missingness of your field. (I also parameterized it in case you ever need to train/test on a different field.) This changes your use to

dmaExtendedDataNA2 <- dmaExtendedDataNA %>%
                      group_by(dma) %>%
                      nest() %>%
                      mutate(data4 = map(data, ~ my_function(.x, fld = "mean_night_flow")))
```

<p>(It's important to name <code>fld=</code>, since otherwise it will be confused for <code>train</code>.)</p>

<p>If you're planning on reusing <code>data2</code> and/or <code>data3</code> later in the pipe or analysis, then this step is not necessarily what you need.</p>

<p>Note: I suspect your function in under-tested or incomplete. The fact that you assign all <code>0</code> to your <code>test1[,"mean_night_flow"]</code> and then use those zeroes in your call to <code>predict</code> seems suspect. I might be missing something, but I would expect perhaps</p>

<pre class="lang-r prettyprint-override"><code>  test1 <- test
  pred  <- predict(et, newdata = test1)
  test1[ , fld] <- pred
  return(test1)
</code>```

(though copying to test1 using tibble or data.frame is mostly unnecessary, since it is copied in-place and the original frame is untouched; I would be more cautious if you were using class data.table).

Body:
I'm trying to apply a custom function to a nested dataframe

I want to apply a machine learning algorithm to predict NA values

After doing a bit of reading online, it seemed that the map function would be the most applicable here

I have a section of code that nests the dataframe and then splits the data into a test (data3) and train (data2) set - with the test dataset containing all the null values for the column to be predicted, and the train containing all the values that are not null to be used to train the ML model

dmaExtendedDataNA2 <- dmaExtendedDataNA %>%
                  group_by(dma) %>%
                  nest() %>%
                  mutate(data2 = map(data, ~filter(., !(is.na(mean_night_flow)))),
                         data3 = map(data, ~filter(., is.na(mean_night_flow))))

Here is the function I intend to use:

    my_function (test,train) {
             et  <- extraTrees(x = train, y = train[, "mean_night_flow"], na.action = "fuse", ntree = 1000, nodesize = 2, mtry = ncol(train) * 0.9 )
             test1 <- test
             test1[ , "mean_night_flow"] <- 0
             pred  <- predict(et, newdata = test1[, "mean_night_flow"])
             test1[ , "mean_night_flow"] <- pred
             return(test1)

I have tried the following code, however it does not work:

dmaExtendedDataNA2 <- dmaExtendedDataNA %>%
                      group_by(dma) %>%
                      nest() %>%
                      mutate(data2 = map(data, ~filter(., !(is.na(mean_night_flow)))),
                             data3 = map(data, ~filter(., is.na(mean_night_flow))),
                             data4 = map(data3, data2, ~my_function(.x,.y)))

It gives the following error:

Error: Index 1 must have length 1, not 33

This is suggests that it expects a column rather than a whole dataframe. How can I get this to work?

Many thanks

Body:
Without testing on your data, I think you're using the wrong map function. purrr::map works on one argument (one list, one vector, whatever) and returns a list. You are passing it two values (data3 and data2), so we need to use:

dmaExtendedDataNA2 <- dmaExtendedDataNA %>%
                      group_by(dma) %>%
                      nest() %>%
                      mutate(data2 = map(data, ~filter(., !(is.na(mean_night_flow)))),
                             data3 = map(data, ~filter(., is.na(mean_night_flow))),
                             data4 = map2(data3, data2, ~my_function(.x,.y)))

If you find yourself needing more than two, you need pmap. You can use pmap for 1 or 2 arguments, it's effectively the same. The two biggest differences when migrating from map to pmap are:

your arguments need to be enclosed within a list, so

map2(data3, data12, ...)

becomes

pmap(list(data3, data12), ...)

you refer to them with double-dot number position, ..1, ..2, ..3, etc, so

~ my_function(.x, .y)

becomes

~ my_function(..1, ..2)

An alternative that simplifies your overall flow just a little.

my_function (test, train = NULL, fld = "mean_night_flow") {
  if (is.null(train)) {
    train <- test[ !is.na(test[[fld]]),, drop = FALSE ]
    test <- test[ is.na(test[[fld]]),, drop = FALSE ]
  }
  et  <- extraTrees(x = train, y = train[, fld], na.action = "fuse", ntree = 1000, nodesize = 2, mtry = ncol(train) * 0.9 )
  test1 <- test
  test1[ , fld] <- 0
  pred  <- predict(et, newdata = test1[, fld])
  test1[ , fld] <- pred
  return(test1)
}

which auto-populates train based on the missingness of your field. (I also parameterized it in case you ever need to train/test on a different field.) This changes your use to

dmaExtendedDataNA2 <- dmaExtendedDataNA %>%
                      group_by(dma) %>%
                      nest() %>%
                      mutate(data4 = map(data, ~ my_function(.x, fld = "mean_night_flow")))

(It's important to name fld=, since otherwise it will be confused for train.)

If you're planning on reusing data2 and/or data3 later in the pipe or analysis, then this step is not necessarily what you need.

Note: I suspect your function in under-tested or incomplete. The fact that you assign all 0 to your test1[,"mean_night_flow"] and then use those zeroes in your call to predict seems suspect. I might be missing something, but I would expect perhaps

  test1 <- test
  pred  <- predict(et, newdata = test1)
  test1[ , fld] <- pred
  return(test1)

(though copying to test1 using tibble or data.frame is mostly unnecessary, since it is copied in-place and the original frame is untouched; I would be more cautious if you were using class data.table).


问:
How to get the longitude and lattitude from an address without showing map
I want to get latitude and longitude from address in one of my asp.net application, i know it s possible using google apis but i want to do it without showing google map. How can i do that?
  I also want to get distance between two pairs of latitude and longitude. Please guide me in that regards also.

Thanks
Pankaj

答:
Or try this..

Note: You will want to replace the “YabbaDabbaDoo” with your own Google Maps API Key.

In the body of your web page, lets place some textboxes on the form so that we can enter the address details that we want to find the co-ordinates for (and a button to perform the co-ordinates calculation):

Address Line 1:

Address Line 2:

Town:

Postcode:

Country:

Latitude:

Longitude:

Now all that is left to do is to create the javascript function that will perform the calculation. So here it is:

```<code>function calculateCoordinates() {

    var txtAddress1 = document.getElementById('<%= txtAddress1.ClientID%>');
    var txtAddress2 = document.getElementById('<%= txtAddress2.ClientID%>');
    var txtTown = document.getElementById('<%= txtTown.ClientID%>');
    var txtPostcode = document.getElementById('<%= txtPostcode.ClientID%>');
    var txtCountry = document.getElementById('<%= txtCountry.ClientID%>');
    var txtLatitude = document.getElementById('<%= txtLatitude.ClientID%>');
    var txtLongitude = document.getElementById('<%= txtLongitude.ClientID%>');

    var address = txtAddress1.value + ', ';
    address += txtAddress2.value + ', ';
    address += txtTown.value + ', ';
    address += txtPostcode.value + ', ';
    address += txtCountry.value;

    var geocoder;
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(address, function(latlng) {
        if (!latlng) {
            alert(address + ' not found');
        } else {
            txtLatitude.value = latlng.lat();
            txtLongitude.value = latlng.lng();
        }
    });

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Or try this..

Note: You will want to replace the “YabbaDabbaDoo” with your own Google Maps API Key.

In the body of your web page, lets place some textboxes on the form so that we can enter the address details that we want to find the co-ordinates for (and a button to perform the co-ordinates calculation):

Address Line 1:

Address Line 2:

Town:

Postcode:

Country:

Latitude:

Longitude:

Now all that is left to do is to create the javascript function that will perform the calculation. So here it is:

function calculateCoordinates() {

    var txtAddress1 = document.getElementById('<%= txtAddress1.ClientID%>');
    var txtAddress2 = document.getElementById('<%= txtAddress2.ClientID%>');
    var txtTown = document.getElementById('<%= txtTown.ClientID%>');
    var txtPostcode = document.getElementById('<%= txtPostcode.ClientID%>');
    var txtCountry = document.getElementById('<%= txtCountry.ClientID%>');
    var txtLatitude = document.getElementById('<%= txtLatitude.ClientID%>');
    var txtLongitude = document.getElementById('<%= txtLongitude.ClientID%>');

    var address = txtAddress1.value + ', ';
    address += txtAddress2.value + ', ';
    address += txtTown.value + ', ';
    address += txtPostcode.value + ', ';
    address += txtCountry.value;

    var geocoder;
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(address, function(latlng) {
        if (!latlng) {
            alert(address + ' not found');
        } else {
            txtLatitude.value = latlng.lat();
            txtLongitude.value = latlng.lng();
        }
    });

}


问:
Rename integer named columns to string text
I have a list of dataframes called: control1,control2,control3,control4,control5. I want to rename only the column named 10 (integer) for each dfs in the list.
I want to rename to this names: 'OPE_PROM_1','OPE_PROM_2','OPE_PROM_3','OPE_PROM_4','OPE_PROM_5'.
I tried this code

```<code>lista_controles=[control1,control2,control3,control4,control5]
for df in lista_controles:
    df.rename(columns={10:'OPE_PROM_'+df+''}, inplace=True)
</code>```

But is not working. Is there any possible solution to this?

答:
Simply, Use:</p>

```<code>lista_controles = [control1, control2, control3, control4, control5]
for i, df in enumerate(lista_controles, 1):
    df.rename(columns={10: f'OPE_PROM_{i}'}, inplace=True)
</code>```

Body:
I have a list of dataframes called: control1,control2,control3,control4,control5. I want to rename only the column named 10 (integer) for each dfs in the list.
I want to rename to this names: 'OPE_PROM_1','OPE_PROM_2','OPE_PROM_3','OPE_PROM_4','OPE_PROM_5'.
I tried this code

lista_controles=[control1,control2,control3,control4,control5]
for df in lista_controles:
    df.rename(columns={10:'OPE_PROM_'+df+''}, inplace=True)

But is not working. Is there any possible solution to this?

Body:
Simply, Use:

lista_controles = [control1, control2, control3, control4, control5]
for i, df in enumerate(lista_controles, 1):
    df.rename(columns={10: f'OPE_PROM_{i}'}, inplace=True)


问:
Trying to write a Fluid App userscript to disable notion sidebar auto popup behavior

Edit - working solution

Trying to disable the javascript event was a no-go, instead I ended up adding an additional element into the DOM that toggled the visibility of the sidebar with css which worked. It's not the prettiest solution as I'm just learning, but it does solve the problem.

It doesn't work as a Fluid userscript but does work as a Greasemonkey/Tampermonkey script in the browser. Full code is on Github - would love someone with more knowledge to improve on it.

Original Post

I'm a newbie in JS but am trying to learn by doing.

I use notion and am very annoyed by the sidebar that pops up whenever the mouse hovers over the left side of the app.

I read somewhere that I can use the Fluid app to push userscripts and that it might be possible to disable that functionality with custom styling.

But I can't seem to figure out how to get either the JS or CSS to disable mouseover events.

I think I found where the event is being listened for, but I'm not sure about next steps for how to remove that listener funtion, or to stop the function call.

This is where I think the event is being triggered, can anyone advise?

答:
So I wasn't able to solve this using the initial methods and ended up trying a totally different approach which worked.

Wasn't able to figure out how to get it to work in Fluid App yet, but I did manage a greasemonkey userscript.

Instead of trying to change the event listener function, I just control the visibility of the sidebar.

I add a button into the DOM, and give that button a trigger that toggles notions sidebar visibility. Click the button and the sidebar is invisible and nothing pops as you hover over the left side.

It's not the prettiest solution, because it doesn't remove notion's existing button for the sidebar, and if you don't minimize the sidebar with notion's own button, then the formatting can be a bit wonky, but as a hack it totally works.

I'm very new to JS and coding in general, so this is prob very inefficient. But if it helps anyone, here's the code in Github – I would love for someone to help me make this better.


问:
Tkinter: Can you see all bindings of a widget?
In my application I want to toggle between two states, and in each of the states I want -> don't want various keys bound.

Right now what I've done is that in my class I've created an attribute self.bindings = [] and then I have a method to create bindings:

```<code>def _create_bindings(self):
    self.bind("<Button-1>", self._canvas_on_click)
    self.bindings.append("<Button-1>")
    self.bind("<Double-Button-1>", self._canvas_on_2click)
    self.bindings.append("<Double-Button-1>")
    self.bind("<<arrow>>", self._canvas_on_arrows)
    self.bindings.append("<<arrow>>")
    self.bind("<space>", lambda event: self._toggle_selected())
    self.bindings.append("<space>")
    self.bind("<Key>", self._canvas_on_key_press)
    self.bindings.append("<Key>")
    self.bind("<BackSpace>", lambda event: self._empty_cell())
    self.bindings.append("<BackSpace>")
    self.bind("<Escape>", self._esc)
    self.bindings.append("<Escape>")
</code>```

and then to remove them:

```<code>def _remove_bindings(self):
    for b in self.bindings:
        self.unbind(b)
</code>```

It's not terrible but it does lead to some duplication (see create function: create binding + add to list).

I could create a wrapper to combine these two steps, but regardless I still have an extra attribute to manage.

Is there a function which I can call which would provide me the same information as self.bindings above?

答:
If you call the bind method without any parameters it will return a list of all events that you have bound for that widget. Your _remove_bindings could look like this:

```<code>def _remove_bindings(self):
    for event in self.bind():
       self.unbind(event)
</code>```

Body:
In my application I want to toggle between two states, and in each of the states I want -> don't want various keys bound.

Right now what I've done is that in my class I've created an attribute self.bindings = [] and then I have a method to create bindings:

def _create_bindings(self):
    self.bind("<Button-1>", self._canvas_on_click)
    self.bindings.append("<Button-1>")
    self.bind("<Double-Button-1>", self._canvas_on_2click)
    self.bindings.append("<Double-Button-1>")
    self.bind("<<arrow>>", self._canvas_on_arrows)
    self.bindings.append("<<arrow>>")
    self.bind("<space>", lambda event: self._toggle_selected())
    self.bindings.append("<space>")
    self.bind("<Key>", self._canvas_on_key_press)
    self.bindings.append("<Key>")
    self.bind("<BackSpace>", lambda event: self._empty_cell())
    self.bindings.append("<BackSpace>")
    self.bind("<Escape>", self._esc)
    self.bindings.append("<Escape>")

and then to remove them:

def _remove_bindings(self):
    for b in self.bindings:
        self.unbind(b)

It's not terrible but it does lead to some duplication (see create function: create binding + add to list).

I could create a wrapper to combine these two steps, but regardless I still have an extra attribute to manage.

Is there a function which I can call which would provide me the same information as self.bindings above?

Body:
If you call the bind method without any parameters it will return a list of all events that you have bound for that widget. Your _remove_bindings could look like this:

def _remove_bindings(self):
    for event in self.bind():
       self.unbind(event)