问:
Draw a hexagonal prism using wpf
To form a triangle prism I'm using

```<code><GeometryModel3D.Geometry>
 <MeshGeometry3D
                                    Positions="
                                      0,1,1  0,0,1  1,0,0  1,1,0
                                      1,1,0  0,1,0  0,1,1
                                      0,0,0  0,0,1  0,1,1  0,1,0
                                      0,0,0  0,1,0  1,1,0  1,0,0
                                      0,0,1  0,0,0  1,0,0

                                      "
                                    TriangleIndices="
                                       0,1,2     2,3,0
                                       4,5,6
                                       7,8,9     7,9,10
                                       11,12,13  11,13,14
                                       15,16,17
                                      " />
 </GeometryModel3D.Geometry>
</code>```

How should I change this code to make a hexagonal prism?

答:
Something like that?

```<code><GeometryModel3D.Geometry>
    <MeshGeometry3D
        Positions="
        0,0,0 1,0,0 2,1,0 1,2,0, 0,2,0, -1,1,0
        0,0,2 1,0,2 2,1,2 1,2,2, 0,2,2, -1,1,2
        "
        TriangleIndices="
        0,2,1 0,3,2 0,4,3 0,5,4
        6,7,8 6,8,9 6,9,10 6,10,11
        0,1,6 1,7,6
        1,2,7 2,8,7
        2,3,8 3,9,8
        3,4,9 4,10,9
        4,5,11 4,11,10
        5,0,6 5,6,11
        " />
</GeometryModel3D.Geometry>
</code>```

Full sample:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="20"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="25"/>
    </Grid.RowDefinitions>

    <ScrollBar Name="vscroll"
        Grid.Row="0" Grid.Column="1"
        Orientation="Vertical"
        Minimum="-180" Maximum="180"
        LargeChange="10" SmallChange="1" Value="0" />

    <ScrollBar Name="hscroll"
        Grid.Row="1" Grid.Column="0"
        Orientation="Horizontal"
        Minimum="-180" Maximum="180"
        LargeChange="10" SmallChange="1" Value="0" />

    <Viewport3D Name="myViewport">
        <Viewport3D.Camera>
            <PerspectiveCamera FarPlaneDistance="10" LookDirection="-5,2,-3"
                                   UpDirection="0,1,0" NearPlaneDistance="0"
                                   Position="4.5,-1,4" FieldOfView="60">
                <PerspectiveCamera.Transform>
                    <Transform3DGroup>
                        <RotateTransform3D>
                            <RotateTransform3D.Rotation>
                                <AxisAngleRotation3D
                                  Axis="0 1 0"
                                  Angle="{Binding ElementName=hscroll, Path=Value}" />
                            </RotateTransform3D.Rotation>
                        </RotateTransform3D>
                        <RotateTransform3D>
                            <RotateTransform3D.Rotation>
                                <AxisAngleRotation3D
                                  Axis="1 0 0"
                                  Angle="{Binding ElementName=vscroll, Path=Value}" />
                            </RotateTransform3D.Rotation>
                        </RotateTransform3D>
                    </Transform3DGroup>
                </PerspectiveCamera.Transform>
            </PerspectiveCamera>
        </Viewport3D.Camera>

        <ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <AmbientLight Color="#0A0000A0" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <DirectionalLight Color="Red" Direction="0,0,-10" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <DirectionalLight Color="Green" Direction="-5,-8,3" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <DirectionalLight Color="Pink" Direction="12,4,-3" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <DirectionalLight Color="Pink" Direction="4,2,4" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>

                    <GeometryModel3D>
                        <GeometryModel3D.Material>
                            <DiffuseMaterial>
                                <DiffuseMaterial.Brush>
                                    <SolidColorBrush Color="LightGray" Opacity="1.0" />
                                </DiffuseMaterial.Brush>
                            </DiffuseMaterial>
                        </GeometryModel3D.Material>
                        <GeometryModel3D.Geometry>
                            <MeshGeometry3D
                                Positions="
                                0,0,0 1,0,0 2,1,0 1,2,0, 0,2,0, -1,1,0
                                0,0,2 1,0,2 2,1,2 1,2,2, 0,2,2, -1,1,2
                                "
                                TriangleIndices="
                                0,2,1 0,3,2 0,4,3 0,5,4
                                6,7,8 6,8,9 6,9,10 6,10,11
                                0,1,6 1,7,6
                                1,2,7 2,8,7
                                2,3,8 3,9,8
                                3,4,9 4,10,9
                                4,5,11 4,11,10
                                5,0,6 5,6,11
                                " />
                        </GeometryModel3D.Geometry>
                    </GeometryModel3D>
                </ModelVisual3D.Content>
            </ModelVisual3D>
        </ModelVisual3D>
    </Viewport3D>
</Grid>
</code>```

The results:

Title: Draw a hexagonal prism using wpf

Body:
To form a triangle prism I'm using

<GeometryModel3D.Geometry>
 <MeshGeometry3D
                                    Positions="
                                      0,1,1  0,0,1  1,0,0  1,1,0
                                      1,1,0  0,1,0  0,1,1
                                      0,0,0  0,0,1  0,1,1  0,1,0
                                      0,0,0  0,1,0  1,1,0  1,0,0
                                      0,0,1  0,0,0  1,0,0

                                      "
                                    TriangleIndices="
                                       0,1,2     2,3,0
                                       4,5,6
                                       7,8,9     7,9,10
                                       11,12,13  11,13,14
                                       15,16,17
                                      " />
 </GeometryModel3D.Geometry>

How should I change this code to make a hexagonal prism?

Body:
Something like that?

<GeometryModel3D.Geometry>
    <MeshGeometry3D
        Positions="
        0,0,0 1,0,0 2,1,0 1,2,0, 0,2,0, -1,1,0
        0,0,2 1,0,2 2,1,2 1,2,2, 0,2,2, -1,1,2
        "
        TriangleIndices="
        0,2,1 0,3,2 0,4,3 0,5,4
        6,7,8 6,8,9 6,9,10 6,10,11
        0,1,6 1,7,6
        1,2,7 2,8,7
        2,3,8 3,9,8
        3,4,9 4,10,9
        4,5,11 4,11,10
        5,0,6 5,6,11
        " />
</GeometryModel3D.Geometry>

Full sample:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="20"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="25"/>
    </Grid.RowDefinitions>

    <ScrollBar Name="vscroll"
        Grid.Row="0" Grid.Column="1"
        Orientation="Vertical"
        Minimum="-180" Maximum="180"
        LargeChange="10" SmallChange="1" Value="0" />

    <ScrollBar Name="hscroll"
        Grid.Row="1" Grid.Column="0"
        Orientation="Horizontal"
        Minimum="-180" Maximum="180"
        LargeChange="10" SmallChange="1" Value="0" />

    <Viewport3D Name="myViewport">
        <Viewport3D.Camera>
            <PerspectiveCamera FarPlaneDistance="10" LookDirection="-5,2,-3"
                                   UpDirection="0,1,0" NearPlaneDistance="0"
                                   Position="4.5,-1,4" FieldOfView="60">
                <PerspectiveCamera.Transform>
                    <Transform3DGroup>
                        <RotateTransform3D>
                            <RotateTransform3D.Rotation>
                                <AxisAngleRotation3D
                                  Axis="0 1 0"
                                  Angle="{Binding ElementName=hscroll, Path=Value}" />
                            </RotateTransform3D.Rotation>
                        </RotateTransform3D>
                        <RotateTransform3D>
                            <RotateTransform3D.Rotation>
                                <AxisAngleRotation3D
                                  Axis="1 0 0"
                                  Angle="{Binding ElementName=vscroll, Path=Value}" />
                            </RotateTransform3D.Rotation>
                        </RotateTransform3D>
                    </Transform3DGroup>
                </PerspectiveCamera.Transform>
            </PerspectiveCamera>
        </Viewport3D.Camera>

        <ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <AmbientLight Color="#0A0000A0" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <DirectionalLight Color="Red" Direction="0,0,-10" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <DirectionalLight Color="Green" Direction="-5,-8,3" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <DirectionalLight Color="Pink" Direction="12,4,-3" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>
                    <DirectionalLight Color="Pink" Direction="4,2,4" />
                </ModelVisual3D.Content>
            </ModelVisual3D>
            <ModelVisual3D>
                <ModelVisual3D.Content>

                    <GeometryModel3D>
                        <GeometryModel3D.Material>
                            <DiffuseMaterial>
                                <DiffuseMaterial.Brush>
                                    <SolidColorBrush Color="LightGray" Opacity="1.0" />
                                </DiffuseMaterial.Brush>
                            </DiffuseMaterial>
                        </GeometryModel3D.Material>
                        <GeometryModel3D.Geometry>
                            <MeshGeometry3D
                                Positions="
                                0,0,0 1,0,0 2,1,0 1,2,0, 0,2,0, -1,1,0
                                0,0,2 1,0,2 2,1,2 1,2,2, 0,2,2, -1,1,2
                                "
                                TriangleIndices="
                                0,2,1 0,3,2 0,4,3 0,5,4
                                6,7,8 6,8,9 6,9,10 6,10,11
                                0,1,6 1,7,6
                                1,2,7 2,8,7
                                2,3,8 3,9,8
                                3,4,9 4,10,9
                                4,5,11 4,11,10
                                5,0,6 5,6,11
                                " />
                        </GeometryModel3D.Geometry>
                    </GeometryModel3D>
                </ModelVisual3D.Content>
            </ModelVisual3D>
        </ModelVisual3D>
    </Viewport3D>
</Grid>

The results:


来源: stackexchange

问:
How to apply circular reveal for activity change?
I'm trying to apply the circular reveal animation for a button click which transitions from the SplashScreen activity to the MainActivity. I've tried almost all the solutions given by people but I'm not able to understand the concept of creating the custom animations like the circular reveal for activity change. I can successfully apply it to the current activity views but not to the activity transitions.

Here's my SplashScreen.java

```<code>public class SplashScreen extends AppCompatActivity {
    boolean isOpen = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        final ImageButton startButton = (ImageButton) findViewById(R.id.button);
        final TextView textView = (TextView)findViewById(R.id.tv1);
        fadeInTextView(textView);
        circularRevealDelayedImageButton(startButton);

    }

    public void fadeInTextView(final TextView textView){
        textView.postDelayed(new Runnable() {
            @Override
            public void run() {
                final TextSwitcher textSwitcher = (TextSwitcher)findViewById(R.id.ssj1);
                textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

                    public View makeView() {
                        // TODO Auto-generated method stub
                        // create a TextView
                        TextView t = new TextView(SplashScreen.this);
                        // set the gravity of text to top and center horizontal
                        // set displayed text size
                        Resources r = getResources();
                        float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 23, r.getDisplayMetrics());
                        t.setTextSize(px);
                        t.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
                        t.setPadding(0,240,0,0);
                        Typeface type = Typeface.createFromAsset(getAssets(),"fonts/allura.ttf");
                        t.setTypeface(type);
                        t.setTextColor(getResources().getColor(R.color.black));
                        return t;
                    }
                });
                Animation anim = AnimationUtils.loadAnimation(getApplicationContext(),android.R.anim.fade_in);
                textView.setVisibility(View.VISIBLE);
                textView.setAnimation(anim);
                textSwitcher.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        textSwitcher.setText("Hey There\nJaadi :)");
                    }
                },2000);

                textSwitcher.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        textSwitcher.setText("");
                    }
                },7000);
                textSwitcher.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        textSwitcher.setText("Press That\nHeart\nFor Me");
                    }
                },9000);

            }
        },3000);

    }

    public void circularRevealDelayedImageButton(final ImageButton startButton){
        startButton.postDelayed(new Runnable() {
            @Override
            public void run() {
                // get the center for the clipping circle
                int cx = startButton.getWidth() / 2;
                int cy = startButton.getHeight() / 2;

// get the final radius for the clipping circle
                float finalRadius = (float) Math.hypot(cx, cy);

// create the animator for this view (the start radius is zero)
                Animator anim =
                        ViewAnimationUtils.createCircularReveal(startButton, cx, cy, 0, finalRadius);

// make the view visible and start the animation
                startButton.setVisibility(View.VISIBLE);
                anim.setDuration(350);
                anim.start();
                startButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(SplashScreen.this, MainActivity.class));
                      // WHAT TO ADD HERE??? FOR CIRCULAR REVEAL ANIMATION FOR THE ABOVE INTENT???
                    }
                });
            }
        },13000);
    }

    }
</code>```

I want to make the custom animation (CircularReveal) when the button is clicked and the SplashScreen transitions to MainActivity. It will be great if you can explain the code. I am trying to get solution for this for over a day now and still can not get hold of anything. And also suggest the changes needed to be done in XML

Here's MainActivity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/layoutcontent"
    android:visibility="invisible"
    android:transitionName="transition"
    android:layout_height="match_parent"
    tools:context="com.yourstrulyssj.foru.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>
</code>```

Here Is My SplashScreen.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layoutmain"
    android:transitionName="transition"
    tools:context="com.yourstrulyssj.foru.SplashScreen">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/rwall"
        android:scaleType="centerCrop"

        />

    <TextSwitcher
        android:id="@+id/ssj1"
        android:layout_width="300dip"
        android:layout_height="400dip"

        android:layout_alignStart="@+id/tv1"
        android:layout_alignTop="@+id/tv1"
        android:inAnimation="@android:anim/fade_in"
        android:outAnimation="@android:anim/fade_out">

    </TextSwitcher>

    <TextView
        android:id="@+id/tv1"
        android:layout_width="300dip"
        android:layout_height="400dip"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="51dp"
        android:background="@drawable/back1"
        android:fontFamily="cursive"
        android:gravity="center"
        android:text=""
        android:textSize="80dip"
        android:visibility="invisible" />

    <ImageButton
        android:id="@+id/button"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="26dp"
        android:layout_weight="1"
        android:background="@drawable/roundedbutton"
        android:src="@drawable/ic_favorite_black_24dp"
        android:visibility="invisible" />
</RelativeLayout>
</code>```

答:
You can use this link : here presentActivity give you idea that how to do effect while move from one class to another.

https://android.jlelse.eu/a-little-thing-that-matter-how-to-reveal-an-activity-with-circular-revelation-d94f9bfcae28

Hope it helps to you.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to apply the circular reveal animation for a button click which transitions from the SplashScreen activity to the MainActivity. I've tried almost all the solutions given by people but I'm not able to understand the concept of creating the custom animations like the circular reveal for activity change. I can successfully apply it to the current activity views but not to the activity transitions.

Here's my SplashScreen.java

public class SplashScreen extends AppCompatActivity {
    boolean isOpen = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        final ImageButton startButton = (ImageButton) findViewById(R.id.button);
        final TextView textView = (TextView)findViewById(R.id.tv1);
        fadeInTextView(textView);
        circularRevealDelayedImageButton(startButton);

    }

    public void fadeInTextView(final TextView textView){
        textView.postDelayed(new Runnable() {
            @Override
            public void run() {
                final TextSwitcher textSwitcher = (TextSwitcher)findViewById(R.id.ssj1);
                textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

                    public View makeView() {
                        // TODO Auto-generated method stub
                        // create a TextView
                        TextView t = new TextView(SplashScreen.this);
                        // set the gravity of text to top and center horizontal
                        // set displayed text size
                        Resources r = getResources();
                        float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 23, r.getDisplayMetrics());
                        t.setTextSize(px);
                        t.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
                        t.setPadding(0,240,0,0);
                        Typeface type = Typeface.createFromAsset(getAssets(),"fonts/allura.ttf");
                        t.setTypeface(type);
                        t.setTextColor(getResources().getColor(R.color.black));
                        return t;
                    }
                });
                Animation anim = AnimationUtils.loadAnimation(getApplicationContext(),android.R.anim.fade_in);
                textView.setVisibility(View.VISIBLE);
                textView.setAnimation(anim);
                textSwitcher.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        textSwitcher.setText("Hey There\nJaadi :)");
                    }
                },2000);

                textSwitcher.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        textSwitcher.setText("");
                    }
                },7000);
                textSwitcher.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        textSwitcher.setText("Press That\nHeart\nFor Me");
                    }
                },9000);

            }
        },3000);

    }

    public void circularRevealDelayedImageButton(final ImageButton startButton){
        startButton.postDelayed(new Runnable() {
            @Override
            public void run() {
                // get the center for the clipping circle
                int cx = startButton.getWidth() / 2;
                int cy = startButton.getHeight() / 2;

// get the final radius for the clipping circle
                float finalRadius = (float) Math.hypot(cx, cy);

// create the animator for this view (the start radius is zero)
                Animator anim =
                        ViewAnimationUtils.createCircularReveal(startButton, cx, cy, 0, finalRadius);

// make the view visible and start the animation
                startButton.setVisibility(View.VISIBLE);
                anim.setDuration(350);
                anim.start();
                startButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(SplashScreen.this, MainActivity.class));
                      // WHAT TO ADD HERE??? FOR CIRCULAR REVEAL ANIMATION FOR THE ABOVE INTENT???
                    }
                });
            }
        },13000);
    }

    }

I want to make the custom animation (CircularReveal) when the button is clicked and the SplashScreen transitions to MainActivity. It will be great if you can explain the code. I am trying to get solution for this for over a day now and still can not get hold of anything. And also suggest the changes needed to be done in XML

Here's MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/layoutcontent"
    android:visibility="invisible"
    android:transitionName="transition"
    android:layout_height="match_parent"
    tools:context="com.yourstrulyssj.foru.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

Here Is My SplashScreen.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layoutmain"
    android:transitionName="transition"
    tools:context="com.yourstrulyssj.foru.SplashScreen">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/rwall"
        android:scaleType="centerCrop"

        />

    <TextSwitcher
        android:id="@+id/ssj1"
        android:layout_width="300dip"
        android:layout_height="400dip"

        android:layout_alignStart="@+id/tv1"
        android:layout_alignTop="@+id/tv1"
        android:inAnimation="@android:anim/fade_in"
        android:outAnimation="@android:anim/fade_out">

    </TextSwitcher>

    <TextView
        android:id="@+id/tv1"
        android:layout_width="300dip"
        android:layout_height="400dip"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="51dp"
        android:background="@drawable/back1"
        android:fontFamily="cursive"
        android:gravity="center"
        android:text=""
        android:textSize="80dip"
        android:visibility="invisible" />

    <ImageButton
        android:id="@+id/button"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="26dp"
        android:layout_weight="1"
        android:background="@drawable/roundedbutton"
        android:src="@drawable/ic_favorite_black_24dp"
        android:visibility="invisible" />
</RelativeLayout>


问:
How to save button value to databse in django?
I'm trying to create my first django app - sports predictions game.

I want user to select from three possible results using 3 buttons (images) which pass 3 different values to the db:

1 - home team wins

0 - draw

2 - away team wins

I am able to save data using forms when I type something into it, but how do I pass value of these buttons to my database?

code on my game.html:

```<code>{% csrf_token %}

{{ form }}
<input type="submit" value = 1>
<input type="submit" value = 0>
<input type="submit" value = 2> </form>
</code>```

and my view:

```<code>def game(request, Game_id):
    thisgame = get_object_or_404(Game, pk=Game_id)
    nextgame = int(thisgame.id)+1
    template = loader.get_template('polls/game.html')
    form = NewBetForm(request.POST or None)
    current_user = request.user

    allgames = Game.objects.all()
    betchoices = BetChoice.objects.all()

    context = { 'thisgame': thisgame,
                'nextgame': nextgame,
                'form': form,
                'current_user': current_user,
                'betchoices': betchoices,}

    if form.is_valid():
        bet = form.save(commit=False)
        bet.gameid = Game.objects.get(id=Game_id)
        bet.userid_id = current_user.id
        bet.save()
    else:
        print (form.errors)
</code>```

and my form:

```<code>class NewBetForm(forms.ModelForm):
    class Meta:
        model = GameBet
        fields = ['bet']
</code>```

and the error I get is Bet - this field is required

Thank you for all ideas!

答:
you can set name for it like :

```<code><input type="submit" name="send1" value ="1">
</code>```

Note : you should value part like  value ="1"

and in views.py:

```<code>if request.method == 'POST':
      if request.POST["send1"] == "1":
            //do some thing
      elif request.POST["send1"] == "2":
             //do domthing
      else://request.POST["send1"] == "3"
             //do something
</code>```

i hope it will help you :)

Body:
I'm trying to create my first django app - sports predictions game.

I want user to select from three possible results using 3 buttons (images) which pass 3 different values to the db:

1 - home team wins

0 - draw

2 - away team wins

I am able to save data using forms when I type something into it, but how do I pass value of these buttons to my database?

code on my game.html:

{% csrf_token %}

{{ form }}
<input type="submit" value = 1>
<input type="submit" value = 0>
<input type="submit" value = 2> </form>

and my view:

def game(request, Game_id):
    thisgame = get_object_or_404(Game, pk=Game_id)
    nextgame = int(thisgame.id)+1
    template = loader.get_template('polls/game.html')
    form = NewBetForm(request.POST or None)
    current_user = request.user

    allgames = Game.objects.all()
    betchoices = BetChoice.objects.all()

    context = { 'thisgame': thisgame,
                'nextgame': nextgame,
                'form': form,
                'current_user': current_user,
                'betchoices': betchoices,}

    if form.is_valid():
        bet = form.save(commit=False)
        bet.gameid = Game.objects.get(id=Game_id)
        bet.userid_id = current_user.id
        bet.save()
    else:
        print (form.errors)

and my form:

class NewBetForm(forms.ModelForm):
    class Meta:
        model = GameBet
        fields = ['bet']

and the error I get is Bet - this field is required

Thank you for all ideas!

Body:
you can set name for it like :

<input type="submit" name="send1" value ="1">

Note : you should value part like  value ="1"

and in views.py:

if request.method == 'POST':
      if request.POST["send1"] == "1":
            //do some thing
      elif request.POST["send1"] == "2":
             //do domthing
      else://request.POST["send1"] == "3"
             //do something

i hope it will help you :)


问:
How to define that float is half of the number?
What would be the most efficient way to say that float value is half of integer for example 0.5, 1.5, 10.5?

First what coming on my mind is:

```<code>$is_half = (($number - floor($number)) === 0.5);
</code>```

Is there any better solutions?

答:
```<code>if(abs($number) - (int)(abs($number)) == 0.5) {
    // half of an integer.
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What would be the most efficient way to say that float value is half of integer for example 0.5, 1.5, 10.5?

First what coming on my mind is:

$is_half = (($number - floor($number)) === 0.5);

Is there any better solutions?


问:
JavaScript function that takes a random argument each time
I'm working on a Canvas API game and I want to create some enemies, each time I create a new instance of the enemy I want it to be create in a new position (not randomly, but rather 3 specific positions.

So let's say I have this function:

```<code>var enemy = new Enemy(0, Math.random() * 184 + 50, Math.random() * 256);
</code>```

This creates a new enemy with an Y position of 0, an X position which is random and a Speed argument that's also random.

This works fine but I want the enemies to be be created in only 3 specific positons and the speed to only increase by 10 each time new enemy instance is being created.

More info: new enemies are being called once the player get's to the final position of winning, like so:

```<code>var increaseDifficulty = function(numEnemies) {
    // remove all previous enemies on canvas
    allEnemies.length = 0;

    // load new set of enemies
    for (var i = 0; i <= numEnemies; i++) {
        var enemy = new Enemy(0, Math.random() * 184 + 50, Math.random() * 256);

        allEnemies.push(enemy);
    }
};
</code>```

What I want is a way to create a new enemy with a different argument each time. Only for the position and speed.

Something like:

```<code>var enemy = new Enemy(0, 1, 1);
</code>```

The second time it is being called it'll be different so:

```<code>var enemy = new Enemy(0, 3, 2);
</code>```

Of course the values won't be 1, 2 and 3 but you get the idea.

UPDATE:

The new enemy calls upon this:

```<code>var Enemy = function(x, y, speed) {
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.sprite = 'images/enemy-bug.png';
};

Enemy.prototype.update = function(dt) {
    this.x += this.speed * dt;
    if (this.x >= 505) {
        this.x = 0;
    }

    checkCollision(this);
};
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};
</code>```

答:
I don't know entire project, so this is only example/draft:

```<code>const createEnemiesFactory = pos => {
    let lastPos = -1;
    let lastSpeed = 0;
    return () => {
        lastPos = (lastPos + 1) % pos.length;
        lastSpeed += 10;
        return new Enemy(pos[lastPos].x, pos[lastPos].y, lastSpeed);
    };
};

let enemiesFactory = createEnemiesFactory([
    {x: 0, y: 0},
    {x: 10, y: 10},
    {x: 20, y: 20}
]);

var increaseDifficulty = function(numEnemies) {
    // remove all previous enemies on canvas
    allEnemies.length = 0;

    // load new set of enemies
    for (var i = 0; i <= numEnemies; i++) {
        allEnemies.push( enemiesFactory() );
    }
};
</code>```

Small notice: if you need to reset difficulty (i.e. on restart), than, obviously, recreate enemies factory, because there is no another way to reset lastSpeed.

Body:
I'm working on a Canvas API game and I want to create some enemies, each time I create a new instance of the enemy I want it to be create in a new position (not randomly, but rather 3 specific positions.

So let's say I have this function:

var enemy = new Enemy(0, Math.random() * 184 + 50, Math.random() * 256);

This creates a new enemy with an Y position of 0, an X position which is random and a Speed argument that's also random.

This works fine but I want the enemies to be be created in only 3 specific positons and the speed to only increase by 10 each time new enemy instance is being created.

More info: new enemies are being called once the player get's to the final position of winning, like so:

var increaseDifficulty = function(numEnemies) {
    // remove all previous enemies on canvas
    allEnemies.length = 0;

    // load new set of enemies
    for (var i = 0; i <= numEnemies; i++) {
        var enemy = new Enemy(0, Math.random() * 184 + 50, Math.random() * 256);

        allEnemies.push(enemy);
    }
};

What I want is a way to create a new enemy with a different argument each time. Only for the position and speed.

Something like:

var enemy = new Enemy(0, 1, 1);

The second time it is being called it'll be different so:

var enemy = new Enemy(0, 3, 2);

Of course the values won't be 1, 2 and 3 but you get the idea.

UPDATE:

The new enemy calls upon this:

var Enemy = function(x, y, speed) {
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.sprite = 'images/enemy-bug.png';
};

Enemy.prototype.update = function(dt) {
    this.x += this.speed * dt;
    if (this.x >= 505) {
        this.x = 0;
    }

    checkCollision(this);
};
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

Body:
I don't know entire project, so this is only example/draft:

const createEnemiesFactory = pos => {
    let lastPos = -1;
    let lastSpeed = 0;
    return () => {
        lastPos = (lastPos + 1) % pos.length;
        lastSpeed += 10;
        return new Enemy(pos[lastPos].x, pos[lastPos].y, lastSpeed);
    };
};

let enemiesFactory = createEnemiesFactory([
    {x: 0, y: 0},
    {x: 10, y: 10},
    {x: 20, y: 20}
]);

var increaseDifficulty = function(numEnemies) {
    // remove all previous enemies on canvas
    allEnemies.length = 0;

    // load new set of enemies
    for (var i = 0; i <= numEnemies; i++) {
        allEnemies.push( enemiesFactory() );
    }
};

Small notice: if you need to reset difficulty (i.e. on restart), than, obviously, recreate enemies factory, because there is no another way to reset lastSpeed.


问:
AJAX request before regular form is being submitted
I have a jQuery form validation script that is executed while user is trying to submit. I would like another function with AJaX request to be executed (and completed) after the form is validated but before it is sent.

Here is the script. The zglosip function works okay when called separately; i.e. not from inside the submit() function.

zglosip(); (function that I want to be called)

```<code>function zglosip() {
        $.ajax({
            type : 'post',
            url : 'res/php/nZglos.php',
            data : {
            "erepid" : "111",
            "ip" : "222",
            "poz" : "333"
            },
            success : function(data, textStatus, jqXHR) {
            tempor.html(data);
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
            tempor.html(errorThrown);
            },
            dataType : 'text'
            return true;
        });
    };
</code>```

validation script (created by Joren Rapini and modified by me)

pole & tempor are variables containing names of some divs

```<code>$("#forml").submit(function(){
    //Validate required fields
    if ((pole.val() == "") || (pole.val() == blad)) {
        pole.addClass("podkresl");
        pole.val(blad);
    } else {
        pole.removeClass("podkresl");
    }
    // Validate the e-mail.
    if (!/\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]/.test(pole.val())) {
        pole.addClass("podkresl");
        pole.val(blad);
    }

    if ($(":input").hasClass("podkresl")) {
        return false;
    } else {
      if (zglosip() == true) {
          return true
      }
    }
});
</code>```

As you have already found out, I had tried to return true of the submit() function after the zglosIp() returned true (the if statement at bottom of the script). This did not work unfortunately, I have also tried calling zglosip() with separate function{return true} in it but surely I have not used it properly.
Please help me.

答:
In my case I had to remove the submit type from the button and then I had to call a method that checked the validity of the data I had to submit.

```<code><input type="button" value="Save" class="btn btn-success" id="submitbutton" />
</code>```

Then I wrote a method  that does the check and returns true if I have to stop and ask to continue:

```<code> public ActionResult CheckBeforeSubbmission(datatype  var1)
 {
    if(var1>0)
         return Json(new { result1 = true });
    else
        return Json(new { result1 = false });
 }
</code>```

After that I added the javascript/ajax the code below:

```<code>  $("#submitbutton").click(function (e) {

        var self = $('#form');
        //A value from the form to post to the controller
        var var1 = $('#var1elementid').val();

        $.ajax({
            type: "POST",
            url: "/SomeController/CheckBeforeSubbmission",
            data: {
                var1: var1
            },success: function (response) {
                if (response.result1) {
                    bootbox.confirm({
                        message: "The check failed! Do you want to submit?",
                        buttons: {
                            confirm: {
                                label: 'Yes',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: 'Cancel',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                self.submit();
                            } else {
                                bootbox.hideAll();
                                return false;
                            }
                            return false;
                        }
                    });
                } else {
                    self.submit();
                }
            },
            cache: false
        });
    });
</code>```

Body:
I have a jQuery form validation script that is executed while user is trying to submit. I would like another function with AJaX request to be executed (and completed) after the form is validated but before it is sent.

Here is the script. The zglosip function works okay when called separately; i.e. not from inside the submit() function.

zglosip(); (function that I want to be called)

function zglosip() {
        $.ajax({
            type : 'post',
            url : 'res/php/nZglos.php',
            data : {
            "erepid" : "111",
            "ip" : "222",
            "poz" : "333"
            },
            success : function(data, textStatus, jqXHR) {
            tempor.html(data);
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
            tempor.html(errorThrown);
            },
            dataType : 'text'
            return true;
        });
    };

validation script (created by Joren Rapini and modified by me)

pole & tempor are variables containing names of some divs

$("#forml").submit(function(){
    //Validate required fields
    if ((pole.val() == "") || (pole.val() == blad)) {
        pole.addClass("podkresl");
        pole.val(blad);
    } else {
        pole.removeClass("podkresl");
    }
    // Validate the e-mail.
    if (!/\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]/.test(pole.val())) {
        pole.addClass("podkresl");
        pole.val(blad);
    }

    if ($(":input").hasClass("podkresl")) {
        return false;
    } else {
      if (zglosip() == true) {
          return true
      }
    }
});

As you have already found out, I had tried to return true of the submit() function after the zglosIp() returned true (the if statement at bottom of the script). This did not work unfortunately, I have also tried calling zglosip() with separate function{return true} in it but surely I have not used it properly.
Please help me.

Body:
In my case I had to remove the submit type from the button and then I had to call a method that checked the validity of the data I had to submit.

<input type="button" value="Save" class="btn btn-success" id="submitbutton" />

Then I wrote a method  that does the check and returns true if I have to stop and ask to continue:

 public ActionResult CheckBeforeSubbmission(datatype  var1)
 {
    if(var1>0)
         return Json(new { result1 = true });
    else
        return Json(new { result1 = false });
 }

After that I added the javascript/ajax the code below:

  $("#submitbutton").click(function (e) {

        var self = $('#form');
        //A value from the form to post to the controller
        var var1 = $('#var1elementid').val();

        $.ajax({
            type: "POST",
            url: "/SomeController/CheckBeforeSubbmission",
            data: {
                var1: var1
            },success: function (response) {
                if (response.result1) {
                    bootbox.confirm({
                        message: "The check failed! Do you want to submit?",
                        buttons: {
                            confirm: {
                                label: 'Yes',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: 'Cancel',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                self.submit();
                            } else {
                                bootbox.hideAll();
                                return false;
                            }
                            return false;
                        }
                    });
                } else {
                    self.submit();
                }
            },
            cache: false
        });
    });


问:
WaitForNonStaleResultsAsOfNow() in RavenDB 4
I can't seem to find the equivalent of WaitForNonStaleResultsAsOfNow() in RavenDB 4 .NET Client API.

In previous versions this was available through IRavenQueryable.Customize(), but now it contains only WaitForNonStaleResultsAsOf() and WaitForNonStaleResults(). The WaitForNonStaleResultsAsOf() accepts only an ETag and no DateTime.

Also, I tried looking for WaitForNonStaleResultsAsOfLastWrite(), but couldn't find that either. And I couldn't replicate the behaviour myself by using IDocumentStore.GetLastWrittenEtag() since it is not present in 4.0.

Digging around a bit more I found that the last ETag would be available on the Raven.Client.Documents.Operations.DatabaseStatistics-object received as a response of the Raven.Client.Documents.Commands.GetStatisticsCommand... But I can't figure out how to issue this command in 4.0 either :(

Any help on achieving this in RavenDB 4 would be greatly appreciated.

答:
In v4.0 you should only use WaitForNonStaleResults. It will work exactly as the WaitForNonStaleResultsAsOfNow was working. It is asking the server to wait on the query until the currently max etag of all the collections in the query.

Cutoff etag is used to check if the index has already process a
  document with the given etag. Unlike Cutoff, which uses dates and is
  susceptible to clock synchronization issues between machines, cutoff
  etag doesn't rely on both the server and client having a synchronized
  clock and can work without it.

WaitForNonStaleResultsAsOf is going to be removed from the client:
http://issues.hibernatingrhinos.com/issue/RavenDB-9678


问:
Delete Files older than 30 days
```<code>$Exclude = @("Folder_1","Folder-2","~snapshot")
$path = "\\\Server\Test"
$limit = (Get-Date).AddDays(-30)

$Files = Get-ChildItem -Path $PATH -Recurse -Force |
         Where-Object {!$_.PSIsContainer -and $_.LastWriteTime -lt $limit} |
         Remove-Item -Force
</code>```

I am trying to delete all files which are older then 30 days but except some folders inside that path which are defined as $Exclude.

I have 2 problems when executing this code:

Remove-Item could not delete files with longer then 248 characters.

I don't know how to define the exclusions (they are not allowed to be deleted).

答:
```<code>mkdir C:\delete
robocopy "\\Server\Test" "c:\Delete" /E /MOVE /MINLAD:30 /LOG:"C:\temp\DeleteOldFiles.txt" /XD "This folder will not be deleted" /FAT
rmdir c:\delete /s /q
</code>```

That is how I solved this Problem. this one is tested and worked!

Title: Delete Files older than 30 days

Body:
$Exclude = @("Folder_1","Folder-2","~snapshot")
$path = "\\\Server\Test"
$limit = (Get-Date).AddDays(-30)

$Files = Get-ChildItem -Path $PATH -Recurse -Force |
         Where-Object {!$_.PSIsContainer -and $_.LastWriteTime -lt $limit} |
         Remove-Item -Force

I am trying to delete all files which are older then 30 days but except some folders inside that path which are defined as $Exclude.

I have 2 problems when executing this code:

Remove-Item could not delete files with longer then 248 characters.

I don't know how to define the exclusions (they are not allowed to be deleted).

Body:
mkdir C:\delete
robocopy "\\Server\Test" "c:\Delete" /E /MOVE /MINLAD:30 /LOG:"C:\temp\DeleteOldFiles.txt" /XD "This folder will not be deleted" /FAT
rmdir c:\delete /s /q

That is how I solved this Problem. this one is tested and worked!


问:
bootstrap 4 remove make-row and make-col via scss, css
After applying the mixins make-row and make-col in scss files is there a way to remove theme via the scss files too?

ie

```<code>.contentType {
@include make-row();
&.no-row {
  @include kill-row();
}
}
</code>```

答:
If you have control over the placement/name of classes on the elements then:

```<code>.contentType {
    &.row {
        @include make-row();
    }
}
</code>```

is essentially the same as applying to all and then removing using a class (and less generated CSS). Sass cannot automatically un-apply all styles from a mixin, you would need to specifically target each style in your kill-row mixin and reset to the default.

Body:
After applying the mixins make-row and make-col in scss files is there a way to remove theme via the scss files too?

ie

.contentType {
@include make-row();
&.no-row {
  @include kill-row();
}
}

Body:
If you have control over the placement/name of classes on the elements then:

.contentType {
    &.row {
        @include make-row();
    }
}

is essentially the same as applying to all and then removing using a class (and less generated CSS). Sass cannot automatically un-apply all styles from a mixin, you would need to specifically target each style in your kill-row mixin and reset to the default.


问:
New vue component instance when prop changes
Our single page application has different views based on components. Due to the one-way-dataflow each property in the child gets updated when the respective value bound in the parent changes.

Is it possible to get a completely new component instance in case a property has changed? In combination with a transition I want to achieve that the old component slides out while the new one based on the latest property values slides in.

I am really looking forward for some cool input.

答:
You can do it by updating the key:

```<code><transition name="fade">
  <hello :key="key"></hello>
</transition>
</code>```

Then update the key:

```<code><button @click="key++">Reload</button>
</code>```

See my example fiddle:

https://jsfiddle.net/eaguad1337/w9fb1pv2/

Body:
You can do it by updating the key:

<transition name="fade">
  <hello :key="key"></hello>
</transition>

Then update the key:

<button @click="key++">Reload</button>

See my example fiddle:

https://jsfiddle.net/eaguad1337/w9fb1pv2/


问:
linq if statement problem
```<code>public IEnumerable<string> References { get; private set; }

References = hrefs.
                Select(href => href.Attributes["href"].Value).
                Distinct().
                ToArray();
</code>```

I'm trying to make it behave so that if href.Attributes["onclick"] exists then I will add onclick value to References otherwise href value. How can I check this inside linq? now I always add href value.

EDIT:

and how if class exist go to next element and don't add anything. i forget about this.

答:
Assuming the hrefs are of type HtmlNode from the HtmlAgilityPack - please verify in your question.

Edited to add checking for class attribute:

```<code>References = hrefs
                .Where( href => href.Attributes["class"]==null)
                .Select(href => (href.Attributes["onlick"]!=null)
                  ? href.Attributes["onlick"].Value
                  : href.Attributes["href"].Value)
                .Distinct()
                .ToArray();
</code>```

Title: linq if statement problem

Body:
public IEnumerable<string> References { get; private set; }

References = hrefs.
                Select(href => href.Attributes["href"].Value).
                Distinct().
                ToArray();

I'm trying to make it behave so that if href.Attributes["onclick"] exists then I will add onclick value to References otherwise href value. How can I check this inside linq? now I always add href value.

EDIT:

and how if class exist go to next element and don't add anything. i forget about this.

Body:
Assuming the hrefs are of type HtmlNode from the HtmlAgilityPack - please verify in your question.

Edited to add checking for class attribute:

References = hrefs
                .Where( href => href.Attributes["class"]==null)
                .Select(href => (href.Attributes["onlick"]!=null)
                  ? href.Attributes["onlick"].Value
                  : href.Attributes["href"].Value)
                .Distinct()
                .ToArray();


问:
Printing dictionary in a While Loop
I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

```<code>newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}
</code>```

I created this dict and I want to use a while loop to output it this way:

```<code>Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30
</code>```

I am able to do it with a for loop, just curious how it can be done with a while loop.

答:
Use following code:</p>

```<code>key=list(newDict.keys())
i=0
while i<len(key):
    print(key[i]," ",newDict[key[i]])
    i+=1
</code>```

Title: Printing dictionary in a While Loop

Body:
I have been looking around to see if anyone has actually done it but couldn't find it so hoping I can get some help here.

newDict = {'Jan':31, 'Feb':29, 'Mar':31, 'Apr':30, 'May':31, 'Jun':30, 'Jul':31, 'Aug':30}

I created this dict and I want to use a while loop to output it this way:

Jan 31
Feb 29
Mar 31
Apr 30
May 31
Jun 30
Jul 31
Aug 30

I am able to do it with a for loop, just curious how it can be done with a while loop.

Body:
Use following code:

key=list(newDict.keys())
i=0
while i<len(key):
    print(key[i]," ",newDict[key[i]])
    i+=1


问:
Multiprocessing not distributing jobs evenly - Python
I am trying to distribute all my jobs between 16 processors evenly using Pool. What I noticed is that initially 16 processes are spawned. After couple of seconds only 2 processes execute all the remaining job for a small number of jobs. No matter how much I increase load, there seems to be stead decrease no of processes working on it. Eventually, only 1 or 2 processes go through the remaining jobs.

Here is the multiprocessing snippet from my code.

```<code>c_size = len(sampled_patterns) / (cpu_count() -1)

pool = Pool(processes=cpu_count() -1)
works = [(pattern, support_set, hit_rates) for pattern,support_set in sampled_patterns.items()]
pool.starmap(get_hit_rules,works, chunksize=int(c_size))
</code>```

Is there anyway to use all 16 processors to maximize parallelization? Thanks!

Edit!
This is how the tasks are distributed. Counter with pid as keys and number of tasks as value.

```<code>Counter({30179: 14130, 30167: 13530, 30169: 12900, 30173: 12630, 30165: 12465, 30177: 12105, 30163: 11820, 30175: 11460, 30161: 10860, 30181: 10725, 30183: 9855, 30157: 8695, 30159: 6765, 30171: 4860, 30155: 1770})
</code>```

答:
Ok, I'll expand on this as an answer.

The whole point of a multiprocessing.Pool is for it to spawn a number of processes and then distribute the work over them in a first-free-first-tasked fashion. This means that if you have n items to process and p number of processes in your pool if will pick p (or p * chunksize if chunksize is defined) number of items and send each of the items to a separate process for processing. Once a process finishes processing an item and is effectively freed, if there are still unprocessed items the pool will pick up the next item, send it to the freed process and so on and so on until there are no more items left. This ensures optimal utlization of your spawned processes without the need to manage the distribution yourself.

This also means that multiprocessing.Pool is not suitable for every situation. In your case, based on the code presented, you want to split your iterable evenly over a fixed number processes, so the Pool would just be an overhead - there will be no more data to distribute once a process is finished. If you just want to split the data and send each chunk to a different process it's as simple as:

```<code>import multiprocessing

if __name__ == "__main__":  # always guard your multiprocessing code
    cores = max(multiprocessing.cpu_count() - 1, 1)  # ensure at least one process

    works = [(p, s, hit_rates) for p, s in sampled_patterns.items()]
    chunk_size = (len(works) + cores - 1) // cores  # rough chunk size estimate

    processes = []  # a simple list to hold our process references
    for i in range(cores):
        work_set = works[i*chunk_size:(i+1)*chunk_size]
        process = multiprocessing.Process(target=get_hit_rules, args=(work_set,))
        process.start()
        processes.append(process)

    results = [process.join() for process in processes]  # get the data back
</code>```

This will do exactly what you've attempted to do - initiate a cpu_count() of processes and send each a (roughly, the last process will get a bit less data on avg.) evenly sized chunk of your data in such a way that all of your data gets processed at once, in parallel.

Of course, if your data is too big as you've additionally clarified in the comment this will end up being unmanageable and then you can revert back to multiprocessing.Pool to send manageable chunks of your data to the spawned processes to process in a row. Additionally, building up the works list is then pointless, too - why would you want to build a list with billions of items that you already have the data in your sampled_patterns dict?

Why not send individual items from your sampled_patterns dict instead without building an intermediary list just so you can map it to the multiprocessing.Pool? To do so, all you need is to create some sort of an iterator slicer and feed it to multiprocessing.Pool.imap instead and let the pool manage the rest internally, so:

```<code>import multiprocessing

def patterns_slicer(patterns, size, hit_rates):
    pos = 0  # store our current position
    patterns = patterns.items()  # use the items iterator
    while pos < len(patterns):
        yield [(p, s, hit_rates) for p, s in patterns[pos:pos+size]]
        pos += size

if __name__ == "__main__":  # always guard your multiprocessing code
    cores = max(multiprocessing.cpu_count() - 1, 1)  # ensure at least one process
    pool = multiprocessing.Pool(processes=cores)
    # lets use chunks of 100 patterns each
    results = pool.imap(get_hit_rules, patterns_slicer(sampled_patterns, 100, hit_rates))
</code>```

Of course, multiprocessing.Pool.imap does a lot of lookahead so if your original data is too large, or you want to use huge chunks, you might want to consider implementing your own imap with just-in-time data retrieval. Check this answer for an example.

Body:
I am trying to distribute all my jobs between 16 processors evenly using Pool. What I noticed is that initially 16 processes are spawned. After couple of seconds only 2 processes execute all the remaining job for a small number of jobs. No matter how much I increase load, there seems to be stead decrease no of processes working on it. Eventually, only 1 or 2 processes go through the remaining jobs.

Here is the multiprocessing snippet from my code.

c_size = len(sampled_patterns) / (cpu_count() -1)

pool = Pool(processes=cpu_count() -1)
works = [(pattern, support_set, hit_rates) for pattern,support_set in sampled_patterns.items()]
pool.starmap(get_hit_rules,works, chunksize=int(c_size))

Is there anyway to use all 16 processors to maximize parallelization? Thanks!

Edit!
This is how the tasks are distributed. Counter with pid as keys and number of tasks as value.

Counter({30179: 14130, 30167: 13530, 30169: 12900, 30173: 12630, 30165: 12465, 30177: 12105, 30163: 11820, 30175: 11460, 30161: 10860, 30181: 10725, 30183: 9855, 30157: 8695, 30159: 6765, 30171: 4860, 30155: 1770})

Body:
Ok, I'll expand on this as an answer.

The whole point of a multiprocessing.Pool is for it to spawn a number of processes and then distribute the work over them in a first-free-first-tasked fashion. This means that if you have n items to process and p number of processes in your pool if will pick p (or p * chunksize if chunksize is defined) number of items and send each of the items to a separate process for processing. Once a process finishes processing an item and is effectively freed, if there are still unprocessed items the pool will pick up the next item, send it to the freed process and so on and so on until there are no more items left. This ensures optimal utlization of your spawned processes without the need to manage the distribution yourself.

This also means that multiprocessing.Pool is not suitable for every situation. In your case, based on the code presented, you want to split your iterable evenly over a fixed number processes, so the Pool would just be an overhead - there will be no more data to distribute once a process is finished. If you just want to split the data and send each chunk to a different process it's as simple as:

import multiprocessing

if __name__ == "__main__":  # always guard your multiprocessing code
    cores = max(multiprocessing.cpu_count() - 1, 1)  # ensure at least one process

    works = [(p, s, hit_rates) for p, s in sampled_patterns.items()]
    chunk_size = (len(works) + cores - 1) // cores  # rough chunk size estimate

    processes = []  # a simple list to hold our process references
    for i in range(cores):
        work_set = works[i*chunk_size:(i+1)*chunk_size]
        process = multiprocessing.Process(target=get_hit_rules, args=(work_set,))
        process.start()
        processes.append(process)

    results = [process.join() for process in processes]  # get the data back

This will do exactly what you've attempted to do - initiate a cpu_count() of processes and send each a (roughly, the last process will get a bit less data on avg.) evenly sized chunk of your data in such a way that all of your data gets processed at once, in parallel.

Of course, if your data is too big as you've additionally clarified in the comment this will end up being unmanageable and then you can revert back to multiprocessing.Pool to send manageable chunks of your data to the spawned processes to process in a row. Additionally, building up the works list is then pointless, too - why would you want to build a list with billions of items that you already have the data in your sampled_patterns dict?

Why not send individual items from your sampled_patterns dict instead without building an intermediary list just so you can map it to the multiprocessing.Pool? To do so, all you need is to create some sort of an iterator slicer and feed it to multiprocessing.Pool.imap instead and let the pool manage the rest internally, so:

import multiprocessing

def patterns_slicer(patterns, size, hit_rates):
    pos = 0  # store our current position
    patterns = patterns.items()  # use the items iterator
    while pos < len(patterns):
        yield [(p, s, hit_rates) for p, s in patterns[pos:pos+size]]
        pos += size

if __name__ == "__main__":  # always guard your multiprocessing code
    cores = max(multiprocessing.cpu_count() - 1, 1)  # ensure at least one process
    pool = multiprocessing.Pool(processes=cores)
    # lets use chunks of 100 patterns each
    results = pool.imap(get_hit_rules, patterns_slicer(sampled_patterns, 100, hit_rates))

Of course, multiprocessing.Pool.imap does a lot of lookahead so if your original data is too large, or you want to use huge chunks, you might want to consider implementing your own imap with just-in-time data retrieval. Check this answer for an example.


问:
Get form attribute value with PHP
Is there a way to get submitted form's attribute value using PHP, when the submit button is clicked?

I have a form which has attribute data-id: someid, I need to get this value.

答:
If You Wants Data id on submit

$(document).ready(function(){
  $('#formid').on('submit', function(){
    var id = $(this).data("id")
    alert(id);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <form action="" method="POST" name="myformName" id="formid" data-id="someid">
 <input type="submit" name="submit">
</form></code>```

Title: Get form attribute value with PHP

Body:
If You Wants Data id on submit

$(document).ready(function(){
  $('#formid').on('submit', function(){
    var id = $(this).data("id")
    alert(id);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <form action="" method="POST" name="myformName" id="formid" data-id="someid">
 <input type="submit" name="submit">
</form>


问:
Confusing comparison output
I am confused about the following:

```<code>>>> 1,2 == 1,2
(1, False, 2)
</code>```

The == operator should return only a bool (or at least I thought so).
I would have expected to have, (True, True) assuming that the line would have been processed like a,b = 1,2 but performing comparison instead of assignment. Or, to have an error. But definitely not (1, False, 2).

Can anyone explain what is going on here?

答:
This:

```<code>1,2 == 1,2
</code>```

is evaluated as a three element tuple that contains 1, 2 == 1 and 2 respectively. You need to use a couple of parentheses here:

```<code>(1, 2) == (1, 2)
</code>```

This is stated in the Language Reference:

Except when part of a list or set display, an expression list
  containing at least one comma yields a tuple. The length of the tuple
  is the number of expressions in the list. The expressions are
  evaluated from left to right.

Title: Confusing comparison output

Body:
I am confused about the following:

>>> 1,2 == 1,2
(1, False, 2)

The == operator should return only a bool (or at least I thought so).
I would have expected to have, (True, True) assuming that the line would have been processed like a,b = 1,2 but performing comparison instead of assignment. Or, to have an error. But definitely not (1, False, 2).

Can anyone explain what is going on here?

Body:
This:

1,2 == 1,2

is evaluated as a three element tuple that contains 1, 2 == 1 and 2 respectively. You need to use a couple of parentheses here:

(1, 2) == (1, 2)

This is stated in the Language Reference:

Except when part of a list or set display, an expression list
  containing at least one comma yields a tuple. The length of the tuple
  is the number of expressions in the list. The expressions are
  evaluated from left to right.


问:
Retrieving Multiple Data Firebase
I'm new in firebase, so I'm trying to know how can get all the names of each of the products in the table Products, thank you

答:
To the name, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = rootRef.child("Products");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
                String name = ds.child("name").getValue(String.class);
                Log.d("TAG", name);
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
productsRef.addListenerForSingleValueEvent(eventListener);
</code>```

Your output will be:

```<code>ps4
Asus
galaxy 8
</code>```

Title: Retrieving Multiple Data Firebase

Body:
To the name, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = rootRef.child("Products");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
                String name = ds.child("name").getValue(String.class);
                Log.d("TAG", name);
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
productsRef.addListenerForSingleValueEvent(eventListener);

Your output will be:

ps4
Asus
galaxy 8


问:
What is the correct way of <use>ing an svg?
I'm very confused about the <svg> spec as it relates to the <use> tag because everything I've read about it online seems to implement the tag with subtle differences.

On css-tricks the <svg> is added with a viewBox in the <symbol>:

```<code><svg style="display: none;">
  <defs>
    <symbol id="basketball" viewBox="0 0 100 100">
      <title>Basketball</title>
      <path d="M28.1,3 ... "/>
    </symbol>
  </defs>
</svg>
</code>```

and then the <symbol> is plainly referenced just with the id:

```<code><svg class="icon-basketball">
  <use xlink:href="#basketball"></use>
</svg>
</code>```

The same is true for this article and even more so in this article by Chris Coyier, where he explicitly points out that <symbol> is a better tag because you don't need a viewBox when referencing it.

However, referencing a symbol with a viewBox does not work for me, and I end up with the same error as in this SO question, which concludes that you do, in fact, need the viewBox when referencing a <symbol>. This article even proposes a hack for dealing with 'intrinsic svg sizing'.

Indeed, in this short jsfiddle/snippet, you can see that with a single <symbol>, if I add the viewbox into the <svg> reference it is sized correctly, without any whitespace. Yet, with the viewbox removed, there are large 'margins' at the top and bottom.

<link href="https://unpkg.com/tachyons@4.9.0/css/tachyons.min.css" rel="stylesheet"/>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><symbol viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-zap" id="zap"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" /></symbol></defs></svg>

 <svg class="outline w3 bg-red">
  <use xlink:href="#zap"></use>
 </svg>

 <svg class="outline w3 bg-green"  viewBox="0 0 24 24">
  <use class="black" xlink:href="#zap"></use>
 </svg>

```

So what am I getting wrong about <use> is it the way I am defining the <symbol>, which currently is being generated through svg-sprite on webpack. Or has there been a recent change in the way <svg>s are externally referenced?

Thanks!

答:
In the article you refer to, Chris Coyier used symbol to store icons in the sprite.

Each symbol in the sprite can have its ownviewBox, with individual parameter values, which allows you to additionally scale and position each icon individually.

```<code><svg xmlns="http://www.w3.org/2000/svg" style="display: none;">

  <symbol id="beaker" viewBox="214.7 0 182.6 792">
    <!-- <path>s and whatever other shapes in here -->
  </symbol>

  <symbol id="shape-icon-2" viewBox="0 26 100 48">
    <!-- <path>s and whatever other shapes in here -->
  </symbol>

</svg>
</code>```

In your case, when using the <use>, as Robert Longson wrote:

in one instance it has size information, in the other it does not.

In the nested svg, there is also an additional scaling.

Therefore, if you want both clones to be the same size, add a svg viewBox to the second instance with the same parameters viewBox =" 0 0 24 24 "

<link href="https://unpkg.com/tachyons@4.9.0/css/tachyons.min.css" rel="stylesheet"/>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><symbol viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-zap" id="zap"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" /></symbol></defs></svg>

 <svg class="outline w3 bg-red" viewBox="0 0 24 24">
  <use xlink:href="#zap"></use>
 </svg>

 <svg class="outline w3 bg-green"  viewBox="0 0 24 24">
  <use class="black" xlink:href="#zap"></use>
 </svg>

```

Body:
I'm very confused about the <svg> spec as it relates to the <use> tag because everything I've read about it online seems to implement the tag with subtle differences.

On css-tricks the <svg> is added with a viewBox in the <symbol>:

<svg style="display: none;">
  <defs>
    <symbol id="basketball" viewBox="0 0 100 100">
      <title>Basketball</title>
      <path d="M28.1,3 ... "/>
    </symbol>
  </defs>
</svg>

and then the <symbol> is plainly referenced just with the id:

<svg class="icon-basketball">
  <use xlink:href="#basketball"></use>
</svg>

The same is true for this article and even more so in this article by Chris Coyier, where he explicitly points out that <symbol> is a better tag because you don't need a viewBox when referencing it.

However, referencing a symbol with a viewBox does not work for me, and I end up with the same error as in this SO question, which concludes that you do, in fact, need the viewBox when referencing a <symbol>. This article even proposes a hack for dealing with 'intrinsic svg sizing'.

Indeed, in this short jsfiddle/snippet, you can see that with a single <symbol>, if I add the viewbox into the <svg> reference it is sized correctly, without any whitespace. Yet, with the viewbox removed, there are large 'margins' at the top and bottom.

<link href="https://unpkg.com/tachyons@4.9.0/css/tachyons.min.css" rel="stylesheet"/>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><symbol viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-zap" id="zap"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" /></symbol></defs></svg>

 <svg class="outline w3 bg-red">
  <use xlink:href="#zap"></use>
 </svg>

 <svg class="outline w3 bg-green"  viewBox="0 0 24 24">
  <use class="black" xlink:href="#zap"></use>
 </svg>

So what am I getting wrong about <use> is it the way I am defining the <symbol>, which currently is being generated through svg-sprite on webpack. Or has there been a recent change in the way <svg>s are externally referenced?

Thanks!

Body:
In the article you refer to, Chris Coyier used symbol to store icons in the sprite.

Each symbol in the sprite can have its ownviewBox, with individual parameter values, which allows you to additionally scale and position each icon individually.

<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">

  <symbol id="beaker" viewBox="214.7 0 182.6 792">
    <!-- <path>s and whatever other shapes in here -->
  </symbol>

  <symbol id="shape-icon-2" viewBox="0 26 100 48">
    <!-- <path>s and whatever other shapes in here -->
  </symbol>

</svg>

In your case, when using the <use>, as Robert Longson wrote:

in one instance it has size information, in the other it does not.

In the nested svg, there is also an additional scaling.

Therefore, if you want both clones to be the same size, add a svg viewBox to the second instance with the same parameters viewBox =" 0 0 24 24 "

<link href="https://unpkg.com/tachyons@4.9.0/css/tachyons.min.css" rel="stylesheet"/>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><defs><symbol viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-zap" id="zap"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" /></symbol></defs></svg>

<div class="tc">

 <!-- svg is the correct size -->
 <svg class="outline w3 bg-red" viewBox="0 0 24 24">
  <use xlink:href="#zap"></use>
 </svg>

 <!-- svg is the correct size -->
 <svg class="outline w3 bg-green"  viewBox="0 0 24 24">
  <use class="black" xlink:href="#zap"></use>
 </svg>

</div>


问:
Swift Bridging Header - Use of undeclared type 'FMDatabase' error
I have looked at all the other posts with the same error (use of undeclared type) but still can’t figure out what is wrong with my project.

The difference with the other cases is that I can successfully use the FMDatabase in AppDelegate and ViewController classes but not from another class I've created, though in the same project as the AppDelegate and ViewController classes.

And by "successfully use", I mean I can access the database and tables in it.

Also note that I didn’t have to import anything to use FMDatabase in AppDelegate or ViewController.

So far what I have done (Xcode. 6.4 Swift 1.2):

Created a single view swift project.

Installed FMDB using cocoapods (https://cocoapods.org/?q=fmdb)

Created a bridging header for FMDB

I can successfully declare and use FMDatabase from the AppDelegate.swift and ViewController.swift classes.

AppDelegate.swift

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var database: FMDatabase? // OK
    ...
</code>```

ViewController.swift

```<code>class ViewController: UIViewController {

    var database: FMDatabase? // OK
    ...
</code>```

In DBUtil.swift though I’m getting the “Use of undeclared type ‘FMDatabase’” error.

DBUtil.swift

```<code>class DBUtil {

    var database: FMDatabase? // Error: "Use of undeclared type 'FMDatabase'

}
</code>```

A reproducer is available at Swift Bridging Header.

For any hints or ideas, thank you in advance.

答:
If you installed FMDB with CocoaPods, just add

```<code>import FMDB
</code>```

in the swift file where you're using FMDatabase..

Body:
I have looked at all the other posts with the same error (use of undeclared type) but still can’t figure out what is wrong with my project.

The difference with the other cases is that I can successfully use the FMDatabase in AppDelegate and ViewController classes but not from another class I've created, though in the same project as the AppDelegate and ViewController classes.

And by "successfully use", I mean I can access the database and tables in it.

Also note that I didn’t have to import anything to use FMDatabase in AppDelegate or ViewController.

So far what I have done (Xcode. 6.4 Swift 1.2):

Created a single view swift project.

Installed FMDB using cocoapods (https://cocoapods.org/?q=fmdb)

Created a bridging header for FMDB

I can successfully declare and use FMDatabase from the AppDelegate.swift and ViewController.swift classes.

AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var database: FMDatabase? // OK
    ...

ViewController.swift

class ViewController: UIViewController {

    var database: FMDatabase? // OK
    ...

In DBUtil.swift though I’m getting the “Use of undeclared type ‘FMDatabase’” error.

DBUtil.swift

class DBUtil {

    var database: FMDatabase? // Error: "Use of undeclared type 'FMDatabase'

}

A reproducer is available at Swift Bridging Header.

For any hints or ideas, thank you in advance.

Body:
If you installed FMDB with CocoaPods, just add

import FMDB

in the swift file where you're using FMDatabase..


问:
Questions about typedef class
Recently, I found some C++ code in OpenJDK 9, like this:

```<code>typedef class oopDesc * opp;
class oop { /* ... */ }
</code>```

Who can explain the code, I just know about a little of C++.

答:
This is equivalent to:

```<code>class oopDesc;
using opp = oppDesc*;
</code>```

And the second line is without interest oop is not opp.

This is horrible code.

Title: Questions about typedef class

Body:
Recently, I found some C++ code in OpenJDK 9, like this:

typedef class oopDesc * opp;
class oop { /* ... */ }

Who can explain the code, I just know about a little of C++.

Body:
This is equivalent to:

class oopDesc;
using opp = oppDesc*;

And the second line is without interest oop is not opp.

This is horrible code.


问:
How to cancel ajax request that has run (on server side)
I was wondering if there's a simple way to cancel an AJAX request?

Beyond just calling an 'abort' on the XMLHTTPRequest on the client side, is there a way to easily stop the server process?  The server is using Apache.

Thanks

答:
For PHP I have found a way to stop or abort by using session_write_close();. Just put this after session_start() on your script. If you are using framwework or OOP then keep it as first line of your method. This happens because session data is locked until the ajax has finished.

Tested & saw another page is now loading after xhr.abort()

Solution hints found here
Abort Ajax requests using jQuery


问:
Getting "type or namespace name could not be found" but everything seems ok?
I'm getting a:

type or namespace name could not be found

error for a C# WPF app in VS2010. This area of code was compiling fine, but suddenly I'm getting this error. I've tried removing the Project Reference and the using statement, shutting VS2010 and restarting, but still I have this issue.

Any ideas why this might be occurring, where it seems like I'm doing the right thing re Reference & using statement?

I also noted in VS2010 that intellisense for that namespace is working ok, so it seems like VS2010 has the project reference and is seeing the namespace on one hand, but during compile doesn't see it?

答: To solve this issue it can also help to delete and recreate the *.sln.DotSettings file of the associated solution.

ContentLicense: CC BY-SA 4.0


问:
How do you get an activity to resolve higher up in a Share via menu?
I have an activity that has the following intent filter:

```<code><intent-filter android:label="Name Of Activity">
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
</intent-filter>
</code>```

However, if I try to share some plain text, for example, from the browser's "Share link" option, the activity appears at the very bottom of the list with several other actions/apps that are far less relevant to sharing this type of content.

How can I improve the intent filter so that the OS recognizes that this can handle this type of content better, so it doesn't have to be below things that are far less relevant to the user?

Thanks

答: Afaik it's not possible, the options seem to always be displayed in alphabetical order.</p>

Body:
I have an activity that has the following intent filter:

<intent-filter android:label="Name Of Activity">
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/plain" />
</intent-filter>

However, if I try to share some plain text, for example, from the browser's "Share link" option, the activity appears at the very bottom of the list with several other actions/apps that are far less relevant to sharing this type of content.

How can I improve the intent filter so that the OS recognizes that this can handle this type of content better, so it doesn't have to be below things that are far less relevant to the user?

Thanks


问:
size of bitmap in drawImage
I've asked question on proper scaling without rim on right and bottom. link

I've checked and size of bitmap is 32 by 32 pixels.
When i try to draw it on pictureBox with drawImage(Image, int, int) it draws it little bit bigger than size of bitmap like 36 by 36 or 40 by 40. Not sure.
But when i add width and height to drawImage it draws it 32 by 32. Is this supposed to happend.

Edit:

```<code>    internal void draw(Graphics g, int x, int y)
    {
        int s = Game.scale;
        Bitmap resized = (s > 1) ? ResizeImage(image, width*s, height*s) : image;

        g.DrawImage(resized, x * width * s, y * height * s);
    }

    private static Bitmap ResizeImage(Image image, int width, int height)
    {
        var destRect = new Rectangle(0, 0, width, height);
        var destImage = new Bitmap(width, height);
        destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

        using (var graphics = Graphics.FromImage(destImage))
        {
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            using (var wrapMode = new ImageAttributes())
            {
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);

            }
        }

        return destImage;
    }
</code>```

答:
Feature, not a bug.  If you don't specify the target size then DrawImage() pays attention to the physical size of the image.  The size it had when it was created, in inches.  Something you can see back in the debugger, look at the bitmap's HorizontalResolution and VerticalResolution properties.

With the diagnostic that it is probably 120 dots-per-inch, programmers commonly run their video adapter at 125% today.  So the drawn image becomes 1.25 * 32 = 40 pixels.

Keep in mind that this kind of rescaling tends to be important, such an image can easily turn into but a fleck of dust on an upscale 4K monitor.  They are getting pretty affordable today.  Whether you want this or not depends on how the rest of your UI rescales.  Check out this post about dpiAwareness in a Winforms app.

Title: size of bitmap in drawImage

Body:
I've asked question on proper scaling without rim on right and bottom. link

I've checked and size of bitmap is 32 by 32 pixels.
When i try to draw it on pictureBox with drawImage(Image, int, int) it draws it little bit bigger than size of bitmap like 36 by 36 or 40 by 40. Not sure.
But when i add width and height to drawImage it draws it 32 by 32. Is this supposed to happend.

Edit:

    internal void draw(Graphics g, int x, int y)
    {
        int s = Game.scale;
        Bitmap resized = (s > 1) ? ResizeImage(image, width*s, height*s) : image;

        g.DrawImage(resized, x * width * s, y * height * s);
    }

    private static Bitmap ResizeImage(Image image, int width, int height)
    {
        var destRect = new Rectangle(0, 0, width, height);
        var destImage = new Bitmap(width, height);
        destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

        using (var graphics = Graphics.FromImage(destImage))
        {
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            using (var wrapMode = new ImageAttributes())
            {
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);

            }
        }

        return destImage;
    }