问:
Android - Movable/Draggable Floating Action Button (FAB)
I am using a FloatingActionButton in my app. Occasionally, it overlaps essential content, so I would like to make it so the user can drag the FAB out of the way.

No drag and drop functionality, per se, is required. It just needs to be movable. The docs do not mention this, but I'm sure I've seen such functionality in other apps.

Can you anyone advise / provide a code snippet on how to do it (preferably in XML).

答:
Based on @ban-geoengineering answer I updated as perform ripple effect and left and right gravity like faceebook chat bubble. I created custom click listener cuz if consume touch event inside this code block, ripple effect doesnt work clearly.</p>

```<code>    <com.sample.DraggableFloatingActionButton
    android:id="@+id/connect_to_support_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_marginLeft="@dimen/spacing_10pt"
    android:layout_marginRight="@dimen/spacing_10pt"
    android:layout_marginBottom="@dimen/spacing_16pt"
    android:clickable="true"
    android:focusable="true"
    app:backgroundTint="@color/colorGreen"
    app:fabSize="normal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:rippleColor="@color/colorWhite"
    app:srcCompat="@drawable/ic_live_support"
    app:tint="@color/colorWhite" />
</code>```

```<code>package com.sample;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

public class DraggableFloatingActionButton extends FloatingActionButton implements View.OnTouchListener {
    CustomClickListener customClickListener;

    private final static float CLICK_DRAG_TOLERANCE = 10; // Often, there will be a slight, unintentional, drag when the user taps the FAB, so we need to account for this.

    private float downRawX, downRawY;
    private float dX, dY;

    int viewWidth;
    int viewHeight;

    int parentWidth;
    int parentHeight;

    float newX;
    float newY;

    public DraggableFloatingActionButton(Context context) {
        super(context);
        init();
    }

    public DraggableFloatingActionButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DraggableFloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();

        int action = motionEvent.getAction();
        if (action == MotionEvent.ACTION_DOWN) {

            downRawX = motionEvent.getRawX();
            downRawY = motionEvent.getRawY();
            dX = view.getX() - downRawX;
            dY = view.getY() - downRawY;

            return false; // not Consumed for ripple effect

        } else if (action == MotionEvent.ACTION_MOVE) {

            viewWidth = view.getWidth();
            viewHeight = view.getHeight();

            View viewParent = (View) view.getParent();
            parentWidth = viewParent.getWidth();
            parentHeight = viewParent.getHeight();

            newX = motionEvent.getRawX() + dX;
            newX = Math.max(layoutParams.leftMargin, newX); // Don't allow the FAB past the left hand side of the parent
            newX = Math.min(parentWidth - viewWidth - layoutParams.rightMargin, newX); // Don't allow the FAB past the right hand side of the parent

            newY = motionEvent.getRawY() + dY;
            newY = Math.max(layoutParams.topMargin, newY); // Don't allow the FAB past the top of the parent
            newY = Math.min(parentHeight - viewHeight - layoutParams.bottomMargin, newY); // Don't allow the FAB past the bottom of the parent

            view.animate()
                    .x(newX)
                    .y(newY)
                    .setDuration(0)
                    .start();

            return true; // Consumed

        } else if (action == MotionEvent.ACTION_UP) {

            float upRawX = motionEvent.getRawX();
            float upRawY = motionEvent.getRawY();

            float upDX = upRawX - downRawX;
            float upDY = upRawY - downRawY;

            if (newX > ((parentWidth - viewWidth - layoutParams.rightMargin) / 2)) {
                newX = parentWidth - viewWidth - layoutParams.rightMargin;
            } else {
                newX = layoutParams.leftMargin;
            }

            view.animate()
                    .x(newX)
                    .y(newY)
                    .setInterpolator(new OvershootInterpolator())
                    .setDuration(300)
                    .start();

            if (Math.abs(upDX) < CLICK_DRAG_TOLERANCE && Math.abs(upDY) < CLICK_DRAG_TOLERANCE) { // A click
                if (customClickListener != null) {
                    customClickListener.onClick(view);
                }
                return false;// not Consumed for ripple effect
            } else { // A drag
                return false; // not Consumed for ripple effect
            }

        } else {
            return super.onTouchEvent(motionEvent);
        }

    }

    public void setCustomClickListener(CustomClickListener customClickListener) {
        this.customClickListener = customClickListener;
    }

    public interface CustomClickListener {
        void onClick(View view);
    }

}
</code>```

Body:
Based on @ban-geoengineering answer I updated as perform ripple effect and left and right gravity like faceebook chat bubble. I created custom click listener cuz if consume touch event inside this code block, ripple effect doesnt work clearly.

    <com.sample.DraggableFloatingActionButton
    android:id="@+id/connect_to_support_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_marginLeft="@dimen/spacing_10pt"
    android:layout_marginRight="@dimen/spacing_10pt"
    android:layout_marginBottom="@dimen/spacing_16pt"
    android:clickable="true"
    android:focusable="true"
    app:backgroundTint="@color/colorGreen"
    app:fabSize="normal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:rippleColor="@color/colorWhite"
    app:srcCompat="@drawable/ic_live_support"
    app:tint="@color/colorWhite" />

package com.sample;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

public class DraggableFloatingActionButton extends FloatingActionButton implements View.OnTouchListener {
    CustomClickListener customClickListener;

    private final static float CLICK_DRAG_TOLERANCE = 10; // Often, there will be a slight, unintentional, drag when the user taps the FAB, so we need to account for this.

    private float downRawX, downRawY;
    private float dX, dY;

    int viewWidth;
    int viewHeight;

    int parentWidth;
    int parentHeight;

    float newX;
    float newY;

    public DraggableFloatingActionButton(Context context) {
        super(context);
        init();
    }

    public DraggableFloatingActionButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DraggableFloatingActionButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setOnTouchListener(this);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();

        int action = motionEvent.getAction();
        if (action == MotionEvent.ACTION_DOWN) {

            downRawX = motionEvent.getRawX();
            downRawY = motionEvent.getRawY();
            dX = view.getX() - downRawX;
            dY = view.getY() - downRawY;

            return false; // not Consumed for ripple effect

        } else if (action == MotionEvent.ACTION_MOVE) {

            viewWidth = view.getWidth();
            viewHeight = view.getHeight();

            View viewParent = (View) view.getParent();
            parentWidth = viewParent.getWidth();
            parentHeight = viewParent.getHeight();

            newX = motionEvent.getRawX() + dX;
            newX = Math.max(layoutParams.leftMargin, newX); // Don't allow the FAB past the left hand side of the parent
            newX = Math.min(parentWidth - viewWidth - layoutParams.rightMargin, newX); // Don't allow the FAB past the right hand side of the parent

            newY = motionEvent.getRawY() + dY;
            newY = Math.max(layoutParams.topMargin, newY); // Don't allow the FAB past the top of the parent
            newY = Math.min(parentHeight - viewHeight - layoutParams.bottomMargin, newY); // Don't allow the FAB past the bottom of the parent

            view.animate()
                    .x(newX)
                    .y(newY)
                    .setDuration(0)
                    .start();

            return true; // Consumed

        } else if (action == MotionEvent.ACTION_UP) {

            float upRawX = motionEvent.getRawX();
            float upRawY = motionEvent.getRawY();

            float upDX = upRawX - downRawX;
            float upDY = upRawY - downRawY;

            if (newX > ((parentWidth - viewWidth - layoutParams.rightMargin) / 2)) {
                newX = parentWidth - viewWidth - layoutParams.rightMargin;
            } else {
                newX = layoutParams.leftMargin;
            }

            view.animate()
                    .x(newX)
                    .y(newY)
                    .setInterpolator(new OvershootInterpolator())
                    .setDuration(300)
                    .start();

            if (Math.abs(upDX) < CLICK_DRAG_TOLERANCE && Math.abs(upDY) < CLICK_DRAG_TOLERANCE) { // A click
                if (customClickListener != null) {
                    customClickListener.onClick(view);
                }
                return false;// not Consumed for ripple effect
            } else { // A drag
                return false; // not Consumed for ripple effect
            }

        } else {
            return super.onTouchEvent(motionEvent);
        }

    }

    public void setCustomClickListener(CustomClickListener customClickListener) {
        this.customClickListener = customClickListener;
    }

    public interface CustomClickListener {
        void onClick(View view);
    }

}


来源: stackexchange

问:
Errors on building Tensorflow on Intel Atom
I build Tensorflow on Intel Atom. Bazel is 0.15. The console command to build is

```<code>bazel build --config=mkl --cxxopt=-D_GLIBCXX_USE_CXX11_ABI=0 --copt=-march=atom --copt=-mtune=atom //tensorflow/tools/pip_package:build_pip_package
</code>```

I have

```<code>Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
</code>```

Two errors are

```<code>ERROR: /home/upsquared/tensorflow/tensorflow/BUILD:533:1: Executing genrule //tensorflow:tf_python_api_gen_v1 failed (Exit 1)
Traceback (most recent call last):
ImportError: /home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/_pywrap_tensorflow_internal.so: undefined symbol: PyClass_Type
</code>```

The whole error messages are

```<code>At global scope:
cc1plus: warning: unrecognized command line option '-Wno-self-assign'
ERROR: /home/upsquared/tensorflow/tensorflow/BUILD:533:1: Executing genrule //tensorflow:tf_python_api_gen_v1 failed (Exit 1)
Traceback (most recent call last):
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/upsquared/venv/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/home/upsquared/venv/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: /home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/_pywrap_tensorflow_internal.so: undefined symbol: PyClass_Type

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/tools/api/generator/create_python_api.py", line 27, in <module>
    from tensorflow.python.tools.api.generator import doc_srcs
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/upsquared/venv/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/home/upsquared/venv/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: /home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/_pywrap_tensorflow_internal.so: undefined symbol: PyClass_Type

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
Target //tensorflow/tools/pip_package:build_pip_package failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 7602.740s, Critical Path: 240.17s
INFO: 5845 processes: 5845 local.
FAILED: Build did NOT complete successfully
</code>```

答:
Installation instructions:

Ensure numpy, keras-applications, keras-preprocessing, pip, six,
wheel, mock packages are installed in the Python environment where
TensorFlow is being built and installed.

Clone the TensorFlow source code and checkout 1.12 branch

```<code>git clone https://github.com/tensorflow/tensorflow
git checkout r1.12
</code>```

Run "./configure" from the TensorFlow source directory

Execute the following commands to create a pip package that can be used to install the optimized TensorFlow build.

PATH can be changed to point to a specific version of GCC compiler:

```<code>  export PATH=/PATH//bin:$PATH
</code>```

LD_LIBRARY_PATH can also be to new:

```<code>  export LD_LIBRARY_PATH=/PATH//lib64:$LD_LIBRARY_PATH
</code>```

Set the compiler flags support by the GCC on your machine  to build TensorFlow with Intel® Math Kernel Library (Intel® MKL). Ensure appropriate "march" and "mtune" flags are set.

```<code>  bazel build --config=mkl --cxxopt=-D_GLIBCXX_USE_CXX11_ABI=0 --copt=-march=sandybridge --copt=-mtune=ivybridge --copt=-O3 //tensorflow/tools/pip_package:build_pip_package
</code>```

(or)

Alternatively, set appropriate "Instruction sets" flags you want to compile the library with:

Flags set in the command below will add AVX, AVX2 and AVX512 instructions which will result in "illegal instruction" errors when you use older CPUs. If you want to build on older CPUs, set the instruction flags accordingly

```<code>       bazel build --config=mkl -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mavx512f --copt=-mavx512pf --copt=-mavx512cd --copt=-mavx512er //tensorflow/tools/pip_package:build_pip_package
</code>```

Install the optimized TensorFlow wheel

```<code>bazel-bin/tensorflow/tools/pip_package/build_pip_package ~/path_to_save_wheel

pip install --upgrade --user ~/path_to_save_wheel/<wheel_name.whl>
</code>```

For reference, please go through this link: https://software.intel.com/en-us/articles/intel-optimization-for-tensorflow-installation-guide

ContentLicense: CC BY-SA 4.0

Body:
I build Tensorflow on Intel Atom. Bazel is 0.15. The console command to build is

bazel build --config=mkl --cxxopt=-D_GLIBCXX_USE_CXX11_ABI=0 --copt=-march=atom --copt=-mtune=atom //tensorflow/tools/pip_package:build_pip_package

I have

Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux

Two errors are

ERROR: /home/upsquared/tensorflow/tensorflow/BUILD:533:1: Executing genrule //tensorflow:tf_python_api_gen_v1 failed (Exit 1)
Traceback (most recent call last):
ImportError: /home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/_pywrap_tensorflow_internal.so: undefined symbol: PyClass_Type

The whole error messages are

At global scope:
cc1plus: warning: unrecognized command line option '-Wno-self-assign'
ERROR: /home/upsquared/tensorflow/tensorflow/BUILD:533:1: Executing genrule //tensorflow:tf_python_api_gen_v1 failed (Exit 1)
Traceback (most recent call last):
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/upsquared/venv/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/home/upsquared/venv/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: /home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/_pywrap_tensorflow_internal.so: undefined symbol: PyClass_Type

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/tools/api/generator/create_python_api.py", line 27, in <module>
    from tensorflow.python.tools.api.generator import doc_srcs
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "/home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "/home/upsquared/venv/lib/python3.5/imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "/home/upsquared/venv/lib/python3.5/imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: /home/upsquared/.cache/bazel/_bazel_upsquared/64ad7d1d27724ec626c14ec5fee17883/execroot/org_tensorflow/bazel-out/host/bin/tensorflow/create_tensorflow.python_api_1.runfiles/org_tensorflow/tensorflow/python/_pywrap_tensorflow_internal.so: undefined symbol: PyClass_Type

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
Target //tensorflow/tools/pip_package:build_pip_package failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 7602.740s, Critical Path: 240.17s
INFO: 5845 processes: 5845 local.
FAILED: Build did NOT complete successfully

Body:
Installation instructions:

Ensure numpy, keras-applications, keras-preprocessing, pip, six,
wheel, mock packages are installed in the Python environment where
TensorFlow is being built and installed.

Clone the TensorFlow source code and checkout 1.12 branch

git clone https://github.com/tensorflow/tensorflow
git checkout r1.12

Run "./configure" from the TensorFlow source directory

Execute the following commands to create a pip package that can be used to install the optimized TensorFlow build.

PATH can be changed to point to a specific version of GCC compiler:

  export PATH=/PATH//bin:$PATH

LD_LIBRARY_PATH can also be to new:

  export LD_LIBRARY_PATH=/PATH//lib64:$LD_LIBRARY_PATH

Set the compiler flags support by the GCC on your machine  to build TensorFlow with Intel® Math Kernel Library (Intel® MKL). Ensure appropriate "march" and "mtune" flags are set.

  bazel build --config=mkl --cxxopt=-D_GLIBCXX_USE_CXX11_ABI=0 --copt=-march=sandybridge --copt=-mtune=ivybridge --copt=-O3 //tensorflow/tools/pip_package:build_pip_package

(or)

Alternatively, set appropriate "Instruction sets" flags you want to compile the library with:

Flags set in the command below will add AVX, AVX2 and AVX512 instructions which will result in "illegal instruction" errors when you use older CPUs. If you want to build on older CPUs, set the instruction flags accordingly

       bazel build --config=mkl -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mavx512f --copt=-mavx512pf --copt=-mavx512cd --copt=-mavx512er //tensorflow/tools/pip_package:build_pip_package

Install the optimized TensorFlow wheel

bazel-bin/tensorflow/tools/pip_package/build_pip_package ~/path_to_save_wheel

pip install --upgrade --user ~/path_to_save_wheel/<wheel_name.whl>

For reference, please go through this link: https://software.intel.com/en-us/articles/intel-optimization-for-tensorflow-installation-guide


问:
Div with margin-left and width:100% overflowing on the right side
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

```<code><div style="width:100%;">
    <div style="margin-left:45px; width:100%;">
    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>
</code>```

If I don't do the 100%, then the textbox is not 100% wide.

答:
Just remove the width from both divs.

A div is a block level element and will use all available space (unless you start floating or positioning them) so the outer div will automatically be 100% wide and the inner div will use all remaining space after setting the left margin.

I have added an example with a textarea on jsfiddle.

Updated example with an input.

ContentLicense: CC BY-SA 3.0

Body:
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox>

If I don't do the 100%, then the textbox is not 100% wide.


问:
When are x:Static type converters evaluated: runtime or compile time?
I have a wpf application and I'm starting to localize it. The strategy for localization I chose was to create my custom MarkupExtension class.

I won't be using the .res files since at my company there is a solution that is already made which creates an encrypted map with all the strings and it requires int keys to refer to each string. So I wrote a custom generator that creates an enum with all the 'int' keys (could be a static class with ints, it doesn't really matter).

So I want to refer to each of these enum keys at my XAML files, doing:

```<code><Label Content="{l:Translator {x:Static l:TranslatedEnums.MainWindow_WelcomeMessage}}" />
</code>```

The created enum is TranslatedEnums and my translator class is called Translator (dhu).

But after reading the x:Static documentation and the type converters documentation, the following question came to my mind:

Does the "compiled xaml" (baml) actually evaluates each of these types (via x:Static) at runtime or compile-time?

I'm asking this because one of the reasons I'm referring to the enum value statically is so that I don't have the exact enum string key, but rather it's value, which would make hacking the application a little bit harder.

If the resolution is done at runtime, then I could narrow my previous code to:

```<code><Label Content="{l:Translator MainWindow_WelcomeMessage}" />
</code>```

Which would require the lookup for the enum value by my own, but this is a one-liner:

```<code>TranslatedEnums result;
Enum.TryParse(key, out result);
</code>```

Which would make the Xaml code smaller (which is good), but it would fail at compile-time if the key didn't exist (which is not a problem).

答: It's actually at xaml load-time (as stated here). if you only load your xaml onece, you could consider it at run-time.</p>

Body:
I have a wpf application and I'm starting to localize it. The strategy for localization I chose was to create my custom MarkupExtension class.

I won't be using the .res files since at my company there is a solution that is already made which creates an encrypted map with all the strings and it requires int keys to refer to each string. So I wrote a custom generator that creates an enum with all the 'int' keys (could be a static class with ints, it doesn't really matter).

So I want to refer to each of these enum keys at my XAML files, doing:

The created enum is TranslatedEnums and my translator class is called Translator (dhu).

But after reading the x:Static documentation and the type converters documentation, the following question came to my mind:

Does the "compiled xaml" (baml) actually evaluates each of these types (via x:Static) at runtime or compile-time?

I'm asking this because one of the reasons I'm referring to the enum value statically is so that I don't have the exact enum string key, but rather it's value, which would make hacking the application a little bit harder.

If the resolution is done at runtime, then I could narrow my previous code to:

Which would require the lookup for the enum value by my own, but this is a one-liner:

TranslatedEnums result;
Enum.TryParse(key, out result);

Which would make the Xaml code smaller (which is good), but it would fail at compile-time if the key didn't exist (which is not a problem).


问:
Tableau Query for using DateDiff and DateTrun at same time
I am new to tableau and i need to find all row set filter on basis of given time frame and then grouping the result of same minute.I can crack this problem in Sql as following

```<code>select count(x)
from table t
where datediff(30, min, date)
group by datepart(min, date)
</code>```

How to fix it in tableau ?

答:
It isn't obvious what your SQL is trying to do here as the standard SQL datediff function works like this datediff(datepart,startdate,enddate) and returns the difference between two dates in the units specified.

If that is what you want, then the Tableau function datediff does much the same job and datediff('minute',start date,enddate) will return the number of minutes between two datetimes and it will be grouped already because the result is discrete.

You can then count the number of records matching each minute difference.

Body:
I am new to tableau and i need to find all row set filter on basis of given time frame and then grouping the result of same minute.I can crack this problem in Sql as following

select count(x)
from table t
where datediff(30, min, date)
group by datepart(min, date)

How to fix it in tableau ?


问:
TypeError: f1_score() got an unexpected keyword argument 'average'
I'm extracting the F1_macro value using f1_score sklearn function.

I doing that for my Keras network, this is the code:

```<code>Y_dev_pred = self.model.predict([self.dev[0], self.dev[1]], batch_size=self.BatchSize, verbose=0)
Y_dev_pred = np.argmax(Y_dev_pred, axis=1)
self.Y_dev = np.argmax(self.dev[2], axis=1)
print('####### ', self.Y_dev.shape, ' ', Y_dev_pred.shape)
print(self.Y_dev, ' ### ', Y_dev_pred)
print(f1_score(self.Y_dev, Y_dev_pred, average='macro'))
</code>```

Output:

```<code>#######  (19647,)   (19647,)
[1 0 0 ... 2 0 2]  ###  [0 0 0 ... 2 1 0]

Traceback (most recent call last):
  File "main.py", line 185, in <module>
    deep.run_model(reTrain=True)
  File ".../models/DL.py", line 477, in run_model
    self.evaluate_on_test()
  File ".../models/DL.py", line 448, in evaluate_on_test
    print(f1_score(self.Y_dev, Y_dev_pred, average='macro'))
TypeError: f1_score() got an unexpected keyword argument 'average'
</code>```

What is the problem, did I miss something?

答:
Check if any of your y_true labels or y_predicted labels has only two classes? check the unique values in each. average macro works only for multiclass if any of the variables has only two classes it throws a error like this!
and yes check version of your sklearn, </p>

Body:
I'm extracting the F1_macro value using f1_score sklearn function.

I doing that for my Keras network, this is the code:

Y_dev_pred = self.model.predict([self.dev[0], self.dev[1]], batch_size=self.BatchSize, verbose=0)
Y_dev_pred = np.argmax(Y_dev_pred, axis=1)
self.Y_dev = np.argmax(self.dev[2], axis=1)
print('####### ', self.Y_dev.shape, ' ', Y_dev_pred.shape)
print(self.Y_dev, ' ### ', Y_dev_pred)
print(f1_score(self.Y_dev, Y_dev_pred, average='macro'))

Output:

#######  (19647,)   (19647,)
[1 0 0 ... 2 0 2]  ###  [0 0 0 ... 2 1 0]

Traceback (most recent call last):
  File "main.py", line 185, in <module>
    deep.run_model(reTrain=True)
  File ".../models/DL.py", line 477, in run_model
    self.evaluate_on_test()
  File ".../models/DL.py", line 448, in evaluate_on_test
    print(f1_score(self.Y_dev, Y_dev_pred, average='macro'))
TypeError: f1_score() got an unexpected keyword argument 'average'

What is the problem, did I miss something?


问:
CardView not showing shadow elevation
I am working with cardviews but the problem is my CardView is not showing any elevation or shadow. I have already tried some of the methods suggested in stackoverflow answers like I have tried using elevation and shadow property. I have also tried using card_view:cardUseCompatPadding="true", but without any success. This is my xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    android:layout_marginTop="6dp"
    android:layout_marginBottom="6dp"
    app:cardBackgroundColor="#FAFBFD"
    app:cardElevation="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/post_profile_image"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:src="@mipmap/ic_launcher"
                android:layout_marginLeft="12dp"
                android:layout_marginTop="12dp"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/post_profile_image"
                android:layout_marginLeft="12dp"
                android:orientation="vertical"
                android:layout_marginTop="16dp">

                <TextView
                    android:id="@+id/post_username"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Name"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000000"/>

                <TextView
                    android:id="@+id/post_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="2dp"
                    android:text="Time"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="@color/grayColor"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true">

                <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@android:drawable/ic_delete"
                    android:id="@+id/post_delete_btn"
                    android:visibility="invisible"/>

            </LinearLayout>

        </RelativeLayout>

        <ImageView
            android:id="@+id/post_image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="12dp"
            android:adjustViewBounds="true"
            android:background="#00ffffff"
            android:src="@drawable/add_btn"
            android:visibility="gone"/>

        <TextView
            android:id="@+id/post_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:layout_marginLeft="12dp"
            android:text="Text about Posting...."
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:layout_marginBottom="8dp">

            <ImageButton
                android:id="@+id/like_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="12dp"
                android:background="#00ffffff"
                android:src="@drawable/grey_like_bt"/>

            <TextView
                android:id="@+id/post_like_count"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="4dp"
                android:layout_marginTop="8dp"
                android:text="0 Likes"
                android:textColor="#2196F3"/>

            <ImageButton
                android:id="@+id/comment_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="32dp"
                android:background="#00ffffff"
                android:src="@drawable/comment_btn_gray"/>

            <TextView
                android:id="@+id/post_comment_count"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="4dp"
                android:layout_marginTop="8dp"
                android:text="0 Comments"
                android:textColor="#2196F3"/>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@android:drawable/ic_menu_edit"
                    android:visibility="invisible"
                    android:id="@+id/post_edit_btn"
                    android:layout_alignParentRight="true"/>

            </RelativeLayout>

        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>
</code>```

Dont know why it is not showing any elevation and shadow

答:
You forget two things.

First of all, check your project's AndroidManifest.xml file, in the Application tag you have to write

<application android:hardwareAccelerated="true" ...>

instead of

<application android:hardwareAccelerated="false" ...>

Then check the parent tag of your layout file is there written like below line.

if you wanna use app: xmlns. then write :
xmlns:app="http://schemas.android.com/apk/res-auto"

OR
xmlns:card_view="http://schemas.android.com/apk/res-auto"

NOTE:  You don't need to write both simultaneous. Because it gives you duplicate attribute error.

The above line is most important when you use the attributes of res-auto.

```<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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="@android:color/white"
        app:cardCornerRadius="4dp"
        app:cardElevation="4dp" />

</RelativeLayout>
</code>```

Title: CardView not showing shadow elevation

Body:
I am working with cardviews but the problem is my CardView is not showing any elevation or shadow. I have already tried some of the methods suggested in stackoverflow answers like I have tried using elevation and shadow property. I have also tried using card_view:cardUseCompatPadding="true", but without any success. This is my xml file

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:card_view="http://schemas.android.com/tools"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    android:layout_marginTop="6dp"
    android:layout_marginBottom="6dp"
    app:cardBackgroundColor="#FAFBFD"
    app:cardElevation="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/post_profile_image"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:src="@mipmap/ic_launcher"
                android:layout_marginLeft="12dp"
                android:layout_marginTop="12dp"/>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/post_profile_image"
                android:layout_marginLeft="12dp"
                android:orientation="vertical"
                android:layout_marginTop="16dp">

                <TextView
                    android:id="@+id/post_username"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Name"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#000000"/>

                <TextView
                    android:id="@+id/post_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="2dp"
                    android:text="Time"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="@color/grayColor"/>
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true">

                <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@android:drawable/ic_delete"
                    android:id="@+id/post_delete_btn"
                    android:visibility="invisible"/>

            </LinearLayout>

        </RelativeLayout>

        <ImageView
            android:id="@+id/post_image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="12dp"
            android:adjustViewBounds="true"
            android:background="#00ffffff"
            android:src="@drawable/add_btn"
            android:visibility="gone"/>

        <TextView
            android:id="@+id/post_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:layout_marginLeft="12dp"
            android:text="Text about Posting...."
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:layout_marginBottom="8dp">

            <ImageButton
                android:id="@+id/like_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="12dp"
                android:background="#00ffffff"
                android:src="@drawable/grey_like_bt"/>

            <TextView
                android:id="@+id/post_like_count"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="4dp"
                android:layout_marginTop="8dp"
                android:text="0 Likes"
                android:textColor="#2196F3"/>

            <ImageButton
                android:id="@+id/comment_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="32dp"
                android:background="#00ffffff"
                android:src="@drawable/comment_btn_gray"/>

            <TextView
                android:id="@+id/post_comment_count"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="4dp"
                android:layout_marginTop="8dp"
                android:text="0 Comments"
                android:textColor="#2196F3"/>

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@android:drawable/ic_menu_edit"
                    android:visibility="invisible"
                    android:id="@+id/post_edit_btn"
                    android:layout_alignParentRight="true"/>

            </RelativeLayout>

        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

Dont know why it is not showing any elevation and shadow

Body:
You forget two things.

First of all, check your project's AndroidManifest.xml file, in the Application tag you have to write

<application android:hardwareAccelerated="true" ...>

instead of

<application android:hardwareAccelerated="false" ...>

Then check the parent tag of your layout file is there written like below line.

if you wanna use app: xmlns. then write :
xmlns:app="http://schemas.android.com/apk/res-auto"

OR
xmlns:card_view="http://schemas.android.com/apk/res-auto"

NOTE:  You don't need to write both simultaneous. Because it gives you duplicate attribute error.

The above line is most important when you use the attributes of res-auto.

<?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="@android:color/white"
        app:cardCornerRadius="4dp"
        app:cardElevation="4dp" />

</RelativeLayout>


问:
Android - Make an envelope shape background in xml/vector
I'm trying to do a shape as this one in xml:

It is a simple rectangle, with a solid color and a little transparent triangle in the top-center, from the inner side.

Can this be achieved using vectors?

答:
Use the Vector Asset Studio in latest Android Studio IDE and use the local file

Vector Asset Studio adds a vector graphic to the project as an XML file that describes the image. Maintaining one XML file can be easier than updating multiple raster graphics at various resolutions.

https://developer.android.com/studio/write/vector-asset-studio#svg


问:
when to use and when not to use the DP and PX measures Android
I am trying to understand the "Best practices for Screen Independence".
 Can someone explain me when to use and when not to use the DP and PX measures ? (of course it is in documentation but my understanding is little vague from it..)

Thanks

答:
Have you read Supporting Multiple Screens? Essentially, if you want to scale to keep the same relative size on different screens, use DP; if you want to shrink on larger displays (and grow on smaller ones), use PX.

Hope this helps,

Phil Lello


问:
TypeScript complex generic method
I currently have this method

```<code>create<T extends ElementType | string>(type: T): Element<T>;
</code>```

which uses

```<code>export type ElementType = 'ExtensionElements' | 'Documentation';

export type Element<T> =
  T extends 'ExtensionElements' ? ExtensionElements :
    T extends 'Documentation' ? Documentation :
      GenericElement;
</code>```

This method is in a .d.ts, and it guarantees the result is always typed, so that

```<code>const e1 = obj.create('ExtensionElements');
      ^^ type is ExtensionElements

const e2 = obj.create('Documentation');
      ^^ type is Documentation

const e3 = obj.create('Other');
      ^^ type is GenericElement
</code>```

Now, I'd like to let the users of this method extend the possible typed choices, so that, for example

```<code>type CustomElementType = 'Other' | ElementType;

type CustomElement<T> =
  T extends 'Other' ? CustomOtherElement : Element<T>;

const e4 = obj.create<CustomElementType, CustomElement>('Other');
      ^^ type is CustomOtherElement
</code>```

However this doesn't seem to work correctly, as I always receive an union of all types, and I cannot use arbitrary strings.

Do you have any other idea how I could implement this?

答:
You can use an interface to map from the string type to the true type. Since interfaces are open ended clients can use module augmentation to add extra options:

```<code>// create.ts
export declare let obj: {
    create<T extends ElementType | string>(type: T): Element<T>;
}
type ExtensionElements = { e: string }
type Documentation = { d: string }
type GenericElement = { g: string }

export type ElementType = 'ExtensionElements' | 'Documentation';
export interface ElementMap {
    'ExtensionElements': ExtensionElements;
    'Documentation': Documentation;
}
export type Element<T extends string> = ElementMap extends Record<T, infer E> ? E :
    GenericElement;

const e1 = obj.create('ExtensionElements'); // ExtensionElements
const e2 = obj.create('Documentation'); // Documentation
const e3 = obj.create('Else'); //GenericElement

// create-usage.ts
import { obj } from './create'
type CustomOtherElement = { x: string }

declare module './create' {
    export interface ElementMap {
        'Other': CustomOtherElement
    }
}
const e4 = obj.create('Other'); //  CustomOtherElement
</code>```

If you want to do scoped extension you will need an extra function that will change the interface used to map the string to the object type. This method can just return the current object cast as the expected result (since types don't matter at runtime nothing needs to be different)

```<code>// create.ts
interface Creator<TMap = ElementMap>{
    create<T extends keyof TMap | string>(type: T): Element<TMap, T>;
    extend<TMapExt extends TMap>(): Creator<TMapExt>
}
export declare let obj: Creator
type ExtensionElements = { e: string }
type Documentation = { d: string }
type GenericElement = { g: string }

import { obj, ElementMap } from './create'
type CustomOtherElement = { x: string }

export type ElementType = 'ExtensionElements' | 'Documentation';
export interface ElementMap {
    'ExtensionElements': ExtensionElements;
    'Documentation': Documentation;
}
export type Element<TMap, T extends PropertyKey> = TMap extends Record<T, infer E> ? E : GenericElement;

const e1 = obj.create('ExtensionElements'); // ExtensionElements
const e2 = obj.create('Documentation'); // Documentation
const e3 = obj.create('Else'); //GenericElement

// create-usage.ts
export interface CustomElementMap extends ElementMap {
    'Other': CustomOtherElement
}
const customObj = obj.extend<CustomElementMap>()
const e4 = customObj.create('Other'); //  CustomOtherElement
</code>```

Title: TypeScript complex generic method

Body:
I currently have this method

create<T extends ElementType | string>(type: T): Element<T>;

which uses

export type ElementType = 'ExtensionElements' | 'Documentation';

export type Element<T> =
  T extends 'ExtensionElements' ? ExtensionElements :
    T extends 'Documentation' ? Documentation :
      GenericElement;

This method is in a .d.ts, and it guarantees the result is always typed, so that

const e1 = obj.create('ExtensionElements');
      ^^ type is ExtensionElements

const e2 = obj.create('Documentation');
      ^^ type is Documentation

const e3 = obj.create('Other');
      ^^ type is GenericElement

Now, I'd like to let the users of this method extend the possible typed choices, so that, for example

type CustomElementType = 'Other' | ElementType;

type CustomElement<T> =
  T extends 'Other' ? CustomOtherElement : Element<T>;

const e4 = obj.create<CustomElementType, CustomElement>('Other');
      ^^ type is CustomOtherElement

However this doesn't seem to work correctly, as I always receive an union of all types, and I cannot use arbitrary strings.

Do you have any other idea how I could implement this?

Body:
You can use an interface to map from the string type to the true type. Since interfaces are open ended clients can use module augmentation to add extra options:

// create.ts
export declare let obj: {
    create<T extends ElementType | string>(type: T): Element<T>;
}
type ExtensionElements = { e: string }
type Documentation = { d: string }
type GenericElement = { g: string }

export type ElementType = 'ExtensionElements' | 'Documentation';
export interface ElementMap {
    'ExtensionElements': ExtensionElements;
    'Documentation': Documentation;
}
export type Element<T extends string> = ElementMap extends Record<T, infer E> ? E :
    GenericElement;

const e1 = obj.create('ExtensionElements'); // ExtensionElements
const e2 = obj.create('Documentation'); // Documentation
const e3 = obj.create('Else'); //GenericElement

// create-usage.ts
import { obj } from './create'
type CustomOtherElement = { x: string }

declare module './create' {
    export interface ElementMap {
        'Other': CustomOtherElement
    }
}
const e4 = obj.create('Other'); //  CustomOtherElement

If you want to do scoped extension you will need an extra function that will change the interface used to map the string to the object type. This method can just return the current object cast as the expected result (since types don't matter at runtime nothing needs to be different)

// create.ts
interface Creator<TMap = ElementMap>{
    create<T extends keyof TMap | string>(type: T): Element<TMap, T>;
    extend<TMapExt extends TMap>(): Creator<TMapExt>
}
export declare let obj: Creator
type ExtensionElements = { e: string }
type Documentation = { d: string }
type GenericElement = { g: string }

import { obj, ElementMap } from './create'
type CustomOtherElement = { x: string }

export type ElementType = 'ExtensionElements' | 'Documentation';
export interface ElementMap {
    'ExtensionElements': ExtensionElements;
    'Documentation': Documentation;
}
export type Element<TMap, T extends PropertyKey> = TMap extends Record<T, infer E> ? E : GenericElement;

const e1 = obj.create('ExtensionElements'); // ExtensionElements
const e2 = obj.create('Documentation'); // Documentation
const e3 = obj.create('Else'); //GenericElement

// create-usage.ts
export interface CustomElementMap extends ElementMap {
    'Other': CustomOtherElement
}
const customObj = obj.extend<CustomElementMap>()
const e4 = customObj.create('Other'); //  CustomOtherElement


问:
How to define robots.txt for anguluarjs application
I want defined robots.txt as you can see below to block robots from login url:

```<code>user-agent: *
disallow: /#!/login

Sitemap: http://mysite.ir/sitemap.xml
</code>```

but google does not recognize # sign and ignore whole the site. how can i fix that problem.

答:
I resolved this problem with $locationProvider.html5Mode(true); as you can see below:

```<code>(function() {
    'use strict';

    angular.module('myapp').config(stateConfig);

    function stateConfig($locationProvider) {
        $locationProvider.html5Mode(true);

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

and set this in head section of index.html:

```<code><base href="/">
</code>```

with this changes angularjs removes # from urls in the, keep in mind that you should make some changes in server side.

Body:
I want defined robots.txt as you can see below to block robots from login url:

user-agent: *
disallow: /#!/login

Sitemap: http://mysite.ir/sitemap.xml

but google does not recognize # sign and ignore whole the site. how can i fix that problem.

Body:
I resolved this problem with $locationProvider.html5Mode(true); as you can see below:

(function() {
    'use strict';

    angular.module('myapp').config(stateConfig);

    function stateConfig($locationProvider) {
        $locationProvider.html5Mode(true);

    }
})();

and set this in head section of index.html:

<base href="/">

with this changes angularjs removes # from urls in the, keep in mind that you should make some changes in server side.


问:
Ajax call returning users error: length of the string exceeds the value set on the maxJsonLength property
I am making use of an ajax call to my controller that returns an array of around 10k users back to my view, which is used for pinning users. However, I am getting this error.

I have read up on a lot of posts and have see the following, and tried it, but still getting the same issue:

Tried adding the below into my web.config:

```<code><system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength = "2147483647"></jsonSerialization>
      </webServices>
    </scripting>
</system.web.extensions>
</code>```

I have also added this to my actionresult:

```<code>var objJSS = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

return Json(objJSS.Serialize(pinnedUsers), JsonRequestBehavior.AllowGet);
</code>```

Below is my entire actionresult:

```<code>public ActionResult GetPinnedUsers()
        {
            clsComments clsComments = new clsComments();
            PinnedUsersViewModel[] pinnedUsers;

            pinnedUsers = clsComments.GetPinnedUsers();

            //var jsonResult = Json(pinnedUsers, JsonRequestBehavior.AllowGet);
            //jsonResult.MaxJsonLength = int.MaxValue;

            var objJSS = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

            return Json(objJSS.Serialize(pinnedUsers), JsonRequestBehavior.AllowGet);
        }
</code>```

Below is my Ajax call:

```<code>$.ajax({
        type: 'get',
        traditional: true,
        url: '@Url.Action("GetPinnedUsers", "ILearn")',
        success: function (usersArray) {
                                    success(usersArray)
                                 },
                                error: error
                            });
</code>```

Am I doing something incorrect or missing something ? Or is there another way of getting all the users passed to my view ?

Thanks for any assistance.

答:
So i was able to find a solution to my problem. Thanks to this link: HANDLING LARGER JSON STRING VALUES SERIALIZATION IN MVC

Below is the code I used:

```<code>        public ActionResult GetPinnedUsers()
        {
            clsComments clsComments = new clsComments();
            PinnedUsersViewModel[] pinnedUsers;

            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //serializer.MaxJsonLength = Int32.MaxValue; //Or any size you want to use, basically int maxValue is 2GB, you shouldn't need this big json string to deserialize, else you are doing it wrong.

            pinnedUsers = clsComments.GetPinnedUsers();

            return SerializeJSON(pinnedUsers);
        }

        private ContentResult SerializeJSON(PinnedUsersViewModel[] users)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength = Int32.MaxValue;
            var resultData = users;

            ContentResult result = new ContentResult();
            result.Content = serializer.Serialize(resultData);
            result.ContentType = "application/json";

            return result;
        }
</code>```

Body:
I am making use of an ajax call to my controller that returns an array of around 10k users back to my view, which is used for pinning users. However, I am getting this error.

I have read up on a lot of posts and have see the following, and tried it, but still getting the same issue:

Tried adding the below into my web.config:

<system.web.extensions>

</system.web.extensions>

I have also added this to my actionresult:

var objJSS = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

return Json(objJSS.Serialize(pinnedUsers), JsonRequestBehavior.AllowGet);

Below is my entire actionresult:

public ActionResult GetPinnedUsers()
        {
            clsComments clsComments = new clsComments();
            PinnedUsersViewModel[] pinnedUsers;

            pinnedUsers = clsComments.GetPinnedUsers();

            //var jsonResult = Json(pinnedUsers, JsonRequestBehavior.AllowGet);
            //jsonResult.MaxJsonLength = int.MaxValue;

            var objJSS = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

            return Json(objJSS.Serialize(pinnedUsers), JsonRequestBehavior.AllowGet);
        }

Below is my Ajax call:

$.ajax({
        type: 'get',
        traditional: true,
        url: '@Url.Action("GetPinnedUsers", "ILearn")',
        success: function (usersArray) {
                                    success(usersArray)
                                 },
                                error: error
                            });

Am I doing something incorrect or missing something ? Or is there another way of getting all the users passed to my view ?

Thanks for any assistance.

Body:
So i was able to find a solution to my problem. Thanks to this link: HANDLING LARGER JSON STRING VALUES SERIALIZATION IN MVC

Below is the code I used:

        public ActionResult GetPinnedUsers()
        {
            clsComments clsComments = new clsComments();
            PinnedUsersViewModel[] pinnedUsers;

            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //serializer.MaxJsonLength = Int32.MaxValue; //Or any size you want to use, basically int maxValue is 2GB, you shouldn't need this big json string to deserialize, else you are doing it wrong.

            pinnedUsers = clsComments.GetPinnedUsers();

            return SerializeJSON(pinnedUsers);
        }

        private ContentResult SerializeJSON(PinnedUsersViewModel[] users)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength = Int32.MaxValue;
            var resultData = users;

            ContentResult result = new ContentResult();
            result.Content = serializer.Serialize(resultData);
            result.ContentType = "application/json";

            return result;
        }


问:
Finding nth Match in a List in Excel
I have a table in Excel from A1:A5

```<code>a
a
b
a
b
</code>```

I want to find the row of the nth occurrence of the value 'a' using Excel Functions and not VBA

If I put in 1 into this function, I want to get 1.

If I put in 2 into this function, I want to get 2.

If I put in 3 into this function, I want to get 4

A solution that works is to add the following formula
=COUNTIF($A5:A5,"a") in B1 and then drag it down to B5.

I can then use =MATCH(C1,B1:B5,0) where C1 holds the variable n.

However is there a neater way without having to add extra columns?

答:
```<code>=AGGREGATE(15,6,1/(myMatch=myRange)*ROW(myRange),Occurrence)
</code>```

The 1/(..) portion of the formula converts non-matches to DIV/0! errors, which the AGGREGATE function can ignore.  So the Smallest value will be the first matching value; etc.

Title: Finding nth Match in a List in Excel

Body:
I have a table in Excel from A1:A5

a
a
b
a
b

I want to find the row of the nth occurrence of the value 'a' using Excel Functions and not VBA

If I put in 1 into this function, I want to get 1.

If I put in 2 into this function, I want to get 2.

If I put in 3 into this function, I want to get 4

A solution that works is to add the following formula
=COUNTIF($A5:A5,"a") in B1 and then drag it down to B5.

I can then use =MATCH(C1,B1:B5,0) where C1 holds the variable n.

However is there a neater way without having to add extra columns?

Body:
=AGGREGATE(15,6,1/(myMatch=myRange)*ROW(myRange),Occurrence)

The 1/(..) portion of the formula converts non-matches to DIV/0! errors, which the AGGREGATE function can ignore.  So the Smallest value will be the first matching value; etc.


问:
Wrong UIToolbar Appears After Popping View
I'm new to Objective-C/Cocoa Touch and hope someone can help with the following issue.

I've got a view with a mapview control and a UIToolBar at the bottom of the screen. When a user clicks a pin on the map they can drill down to a grouped UITableView with details of the location.

This is done by pushing a new navigationController:

```<code>MapAnnotation *tappedLocation = (MapAnnotation *)[view annotation];

LocationDetailsViewController *placeDetails = [[LocationDetailsViewController alloc] initWithNibName:@"LocationDetailsViewController" bundle:nil];
[self.navigationController pushViewController:placeDetails animated:YES];
[placeDetails release];
</code>```

In the grouped UITableView there's also a UIToolbar at the bottom of the screen, but it's set up programmatically (code below).

The issue is that when the user leaves the grouped UITableView and comes back to the main view with the map, they still see the UIToolbar from the UITableView, not the original one that was set up in IB.

Anyone know how I can 'cancel' the UIToolbar from the grouped UITableView?

```<code>UIToolbar *toolbar = [UIToolbar new];
toolbar.barStyle = UIBarStyleDefault;
[toolbar sizeToFit];
toolbar.frame = CGRectMake(0, 436, 320, 44);
toolbar.tag = 123;

UIBarButtonItem *flexItem = [[UIBarButtonItem alloc]
    initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
    target:nil
    action:nil];

UIBarButtonItem *emailButton = [[UIBarButtonItem alloc]
    initWithBarButtonSystemItem:UIBarButtonSystemItemAction
    target:self
    action:@selector(email:)];

//Add buttons to the array
NSArray *items = [NSArray arrayWithObjects: flexItem, flexItem, flexItem, emailButton, nil];
[emailButton release];
[flexItem release];

//add array of buttons to toolbar
[toolbar setItems:items animated:YES];

[self.navigationController.view addSubview:toolbar];
</code>```

答:
Don't add the toolbar as a subview of the navigationController. That view stays on screen as long as the app is running (you'll be stacking up a lot of them if you keep on going into the details view and back).

Simply set the toolbar's items using [UIViewController setToolbarItems:animated:]

Body:
I'm new to Objective-C/Cocoa Touch and hope someone can help with the following issue.

I've got a view with a mapview control and a UIToolBar at the bottom of the screen. When a user clicks a pin on the map they can drill down to a grouped UITableView with details of the location.

This is done by pushing a new navigationController:

MapAnnotation *tappedLocation = (MapAnnotation *)[view annotation];

LocationDetailsViewController *placeDetails = [[LocationDetailsViewController alloc] initWithNibName:@"LocationDetailsViewController" bundle:nil];
[self.navigationController pushViewController:placeDetails animated:YES];
[placeDetails release];

In the grouped UITableView there's also a UIToolbar at the bottom of the screen, but it's set up programmatically (code below).

The issue is that when the user leaves the grouped UITableView and comes back to the main view with the map, they still see the UIToolbar from the UITableView, not the original one that was set up in IB.

Anyone know how I can 'cancel' the UIToolbar from the grouped UITableView?

UIToolbar *toolbar = [UIToolbar new];
toolbar.barStyle = UIBarStyleDefault;
[toolbar sizeToFit];
toolbar.frame = CGRectMake(0, 436, 320, 44);
toolbar.tag = 123;

UIBarButtonItem *flexItem = [[UIBarButtonItem alloc]
    initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
    target:nil
    action:nil];

UIBarButtonItem *emailButton = [[UIBarButtonItem alloc]
    initWithBarButtonSystemItem:UIBarButtonSystemItemAction
    target:self
    action:@selector(email:)];

//Add buttons to the array
NSArray *items = [NSArray arrayWithObjects: flexItem, flexItem, flexItem, emailButton, nil];
[emailButton release];
[flexItem release];

//add array of buttons to toolbar
[toolbar setItems:items animated:YES];

[self.navigationController.view addSubview:toolbar];


问:
Error 500 when start install Magento 2 in my server
I start install Magneto 2 in my server.

And i see this error :

`Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.`

Where is problem ?

答:
Try to enable error reporting inside app/bootstrap.php

```<code>error_reporting(E_ALL);
ini_set('display_errors', 1);
</code>```

this will show you an exact error,

second check your database connections,

third check file permissions

UPDATED :

as per @jas said, also enable developer mode for easier debugging sessions

Body:
Try to enable error reporting inside app/bootstrap.php

error_reporting(E_ALL);
ini_set('display_errors', 1);

this will show you an exact error,

second check your database connections,

third check file permissions

UPDATED :

as per @jas said, also enable developer mode for easier debugging sessions


问:
Use the current value of a DatePicker as the minimum/maximum value of another DatePicker
I have a JavaFX UI that allows the user to specify a time span. It consists of two DatePickers, one for selecting the start date and one for selecting the end date of the time span.

Obviously, I don't want the user to be able to select a start date that lies after the end date and vice-versa.

I've already set up a custom DayCellFactory for both date pickers, as described in https://stackoverflow.com/a/46372951/5801146. This works as intended for the initial time range specified during the initialisation of the DatePickers. However, if the user then selects, for instance, a different start date, the end date DatePicker still shows the initial selectable dates and doesn't adapt its selectable dates to the new start date. Here's my approach using property listeners, which - of course - does not work:

```<code>public final class DatePickerUtil {

    public static void constrainLowerUpperBounds(DatePicker lowerBoundDatePicker, DatePicker upperBoundDatePicker) {
        LocalDate lowerBound = lowerBoundDatePicker.getValue();
        LocalDate upperBound = upperBoundDatePicker.getValue();

        if (lowerBound.isAfter(upperBound)) {
            throw new IllegalStateException("Upper bound date picker has older date than lower bound date picker");
        }

        lowerBoundDatePicker.setEditable(true);
        upperBoundDatePicker.setEditable(true);

        lowerBoundDatePicker.setDayCellFactory(createDayCellFactory(null, upperBound));
        upperBoundDatePicker.setDayCellFactory(createDayCellFactory(lowerBound, null));

        lowerBoundDatePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
            upperBoundDatePicker.setDayCellFactory(createDayCellFactory(newValue, null));
        });

        upperBoundDatePicker.valueProperty().addListener(((observable, oldValue, newValue) -> {
            lowerBoundDatePicker.setDayCellFactory(createDayCellFactory(null, newValue));
        }));
    }

    private static Callback<DatePicker, DateCell> createDayCellFactory(LocalDate lowerBound, LocalDate upperBound) {
        return picker -> new DateCell() {
            @Override
            public void updateItem(LocalDate date, boolean empty) {
                super.updateItem(date, empty);
                boolean isBeforeLowerBound = lowerBound != null && date.isBefore(lowerBound);
                boolean isAfterUpperBound = upperBound != null && date.isAfter(upperBound);
                Platform.runLater(() -> setDisable(empty || isBeforeLowerBound || isAfterUpperBound));
            }
        };
    }
}
</code>```

What I want to achieve is some sort of binding like in WPF/UWP where you can bind the minimum value of the end date DatePicker to the current value of the start date DatePicker, and the maximum value of the start date DatePicker to the current value of the end date DatePicker. How can I achieve this behaviour in JavaFX?

答:
you can pass the first DatePicker's value to the second one and after it changes it updates the second one.

Here is a simple example:

```<code>public class MinMaxDate {

    private void test() {
        DatePicker firstDP = new DatePicker();
        DatePicker secondDP = new DatePicker();

        // set the min date
        secondDP.setDayCellFactory(cf -> new MinDateCell(firstDP.valueProperty()));
        // set the max date
        secondDP.setDayCellFactory(cf -> new MaxDateCell(firstDP.valueProperty()));
    }

    private class MinDateCell extends DateCell {

        private ObjectProperty<LocalDate> date;

        private MinDateCell(ObjectProperty<LocalDate> date) {
            this.date = date;
        }

        @Override
        public void updateItem(LocalDate item, boolean empty) {
            super.updateItem(item, empty);
            if (item.isBefore(date.get())) {
                this.setDisable(true);
                setStyle("-fx-background-color: #7e7e7e;"); // I used a different coloring to see which are disabled.
            }
        }

    }

    private class MaxDateCell extends DateCell {

        private ObjectProperty<LocalDate> date;

        private MaxDateCell(ObjectProperty<LocalDate> date) {
            this.date = date;
        }

        @Override
        public void updateItem(LocalDate item, boolean empty) {
            super.updateItem(item, empty);
            if (item.isAfter(date.get())) {
                this.setDisable(true);
                setStyle("-fx-background-color: #7e7e7e;"); // Same here
            }
        }

    }

}
</code>```

I have created two different classes, but I am sure it can be solved using some fancy java8 function to make it much more general then you could use in that if any condition to disable a date.

Update

Here is the generic solution:

```<code>private class FilterDateCell extends DateCell {

        private ObjectProperty<LocalDate> date;
        private BiPredicate<LocalDate, LocalDate> filterPredicate;

        private FilterDateCell(
                ObjectProperty<LocalDate> date,
                BiPredicate<LocalDate, LocalDate> filterPredicate) {
            this.date = date;
            this.filterFunction = filterFunction;
        }

        @Override
        public void updateItem(LocalDate item, boolean empty) {
            super.updateItem(item, empty);
            if (filterPredicate.test(item, date.get())) {
                this.setDisable(true);
                setStyle("-fx-background-color: #7e7e7e;"); // I used a different coloring to see which are disabled.
            }
        }

    }
</code>```

It can be used like:

```<code>// set the min date
secondDP.setDayCellFactory(cf -> new FilterDateCell(firstDP.valueProperty(),LocalDate::isBefore));
// set the max date
secondDP.setDayCellFactory(cf -> new FilterDateCell(firstDP.valueProperty(),LocalDate::isAfter));
</code>```

Body:
I have a JavaFX UI that allows the user to specify a time span. It consists of two DatePickers, one for selecting the start date and one for selecting the end date of the time span.

Obviously, I don't want the user to be able to select a start date that lies after the end date and vice-versa.

I've already set up a custom DayCellFactory for both date pickers, as described in https://stackoverflow.com/a/46372951/5801146. This works as intended for the initial time range specified during the initialisation of the DatePickers. However, if the user then selects, for instance, a different start date, the end date DatePicker still shows the initial selectable dates and doesn't adapt its selectable dates to the new start date. Here's my approach using property listeners, which - of course - does not work:

public final class DatePickerUtil {

    public static void constrainLowerUpperBounds(DatePicker lowerBoundDatePicker, DatePicker upperBoundDatePicker) {
        LocalDate lowerBound = lowerBoundDatePicker.getValue();
        LocalDate upperBound = upperBoundDatePicker.getValue();

        if (lowerBound.isAfter(upperBound)) {
            throw new IllegalStateException("Upper bound date picker has older date than lower bound date picker");
        }

        lowerBoundDatePicker.setEditable(true);
        upperBoundDatePicker.setEditable(true);

        lowerBoundDatePicker.setDayCellFactory(createDayCellFactory(null, upperBound));
        upperBoundDatePicker.setDayCellFactory(createDayCellFactory(lowerBound, null));

        lowerBoundDatePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
            upperBoundDatePicker.setDayCellFactory(createDayCellFactory(newValue, null));
        });

        upperBoundDatePicker.valueProperty().addListener(((observable, oldValue, newValue) -> {
            lowerBoundDatePicker.setDayCellFactory(createDayCellFactory(null, newValue));
        }));
    }

    private static Callback<DatePicker, DateCell> createDayCellFactory(LocalDate lowerBound, LocalDate upperBound) {
        return picker -> new DateCell() {
            @Override
            public void updateItem(LocalDate date, boolean empty) {
                super.updateItem(date, empty);
                boolean isBeforeLowerBound = lowerBound != null && date.isBefore(lowerBound);
                boolean isAfterUpperBound = upperBound != null && date.isAfter(upperBound);
                Platform.runLater(() -> setDisable(empty || isBeforeLowerBound || isAfterUpperBound));
            }
        };
    }
}

What I want to achieve is some sort of binding like in WPF/UWP where you can bind the minimum value of the end date DatePicker to the current value of the start date DatePicker, and the maximum value of the start date DatePicker to the current value of the end date DatePicker. How can I achieve this behaviour in JavaFX?

Body:
you can pass the first DatePicker's value to the second one and after it changes it updates the second one.

Here is a simple example:

public class MinMaxDate {

    private void test() {
        DatePicker firstDP = new DatePicker();
        DatePicker secondDP = new DatePicker();

        // set the min date
        secondDP.setDayCellFactory(cf -> new MinDateCell(firstDP.valueProperty()));
        // set the max date
        secondDP.setDayCellFactory(cf -> new MaxDateCell(firstDP.valueProperty()));
    }

    private class MinDateCell extends DateCell {

        private ObjectProperty<LocalDate> date;

        private MinDateCell(ObjectProperty<LocalDate> date) {
            this.date = date;
        }

        @Override
        public void updateItem(LocalDate item, boolean empty) {
            super.updateItem(item, empty);
            if (item.isBefore(date.get())) {
                this.setDisable(true);
                setStyle("-fx-background-color: #7e7e7e;"); // I used a different coloring to see which are disabled.
            }
        }

    }

    private class MaxDateCell extends DateCell {

        private ObjectProperty<LocalDate> date;

        private MaxDateCell(ObjectProperty<LocalDate> date) {
            this.date = date;
        }

        @Override
        public void updateItem(LocalDate item, boolean empty) {
            super.updateItem(item, empty);
            if (item.isAfter(date.get())) {
                this.setDisable(true);
                setStyle("-fx-background-color: #7e7e7e;"); // Same here
            }
        }

    }

}

I have created two different classes, but I am sure it can be solved using some fancy java8 function to make it much more general then you could use in that if any condition to disable a date.

Update

Here is the generic solution:

private class FilterDateCell extends DateCell {

        private ObjectProperty<LocalDate> date;
        private BiPredicate<LocalDate, LocalDate> filterPredicate;

        private FilterDateCell(
                ObjectProperty<LocalDate> date,
                BiPredicate<LocalDate, LocalDate> filterPredicate) {
            this.date = date;
            this.filterFunction = filterFunction;
        }

        @Override
        public void updateItem(LocalDate item, boolean empty) {
            super.updateItem(item, empty);
            if (filterPredicate.test(item, date.get())) {
                this.setDisable(true);
                setStyle("-fx-background-color: #7e7e7e;"); // I used a different coloring to see which are disabled.
            }
        }

    }

It can be used like:

// set the min date
secondDP.setDayCellFactory(cf -> new FilterDateCell(firstDP.valueProperty(),LocalDate::isBefore));
// set the max date
secondDP.setDayCellFactory(cf -> new FilterDateCell(firstDP.valueProperty(),LocalDate::isAfter));


问:
Creating UILabel programmatically with constraints?
What I want to do is create a new UILabel programmatically every time a certain action occurs in my code. I know the x, y, and height that I want to give the label, but I don't want to give it a set width. I want to constrain the sides so that the UILabel width is equal to the width of the screen, and so that the label width will change if the orientation is flipped.

I have considered using:

```<code>CGRect(x:, y:, width:, height:)
</code>```

However, I would have to give it a set width if I use this, so I don't think it will work.

I also tried using:

```<code>CGPoint(x:, y:)
</code>```

Then setting leading, trailing and height anchors, however, this doesn't seem to work either as even though it does compile, I get an error when I try creating a new UILabel.

I'm kind of new to programming in Swift so I'm not sure if there is an obvious fix to this.

答:
Like you said, we already have x, y and height available for the label, i.e.

```<code>let x: CGFloat = 0
let y: CGFloat = 0
let height: CGFloat = 50
</code>```

Let's create a label using the above details. Also set the width of the label as UIScreen.main.bounds.width as per your requirement.

```<code>let label = UILabel(frame: CGRect(x: x, y: y, width: UIScreen.main.bounds.width, height: height))
label.text = "This is a sample text"
</code>```

Don't forget to set label's translatesAutoresizingMaskIntoConstraints as false and add it to whatever subview you want.

```<code>label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
</code>```

Add the relevant constraints of label with its superview - top, bottom, leading, height. You can definitely add bottom constraint if required. That totally depends upon your UI.

I'm adding the label to the top of the viewController's view.

```<code>NSLayoutConstraint.activate([
    label.heightAnchor.constraint(equalToConstant: height),
    view.topAnchor.constraint(equalTo: label.topAnchor),
    view.leadingAnchor.constraint(equalTo: label.leadingAnchor),
    view.trailingAnchor.constraint(equalTo: label.trailingAnchor)
    ])
</code>```

Body:
What I want to do is create a new UILabel programmatically every time a certain action occurs in my code. I know the x, y, and height that I want to give the label, but I don't want to give it a set width. I want to constrain the sides so that the UILabel width is equal to the width of the screen, and so that the label width will change if the orientation is flipped.

I have considered using:

CGRect(x:, y:, width:, height:)

However, I would have to give it a set width if I use this, so I don't think it will work.

I also tried using:

CGPoint(x:, y:)

Then setting leading, trailing and height anchors, however, this doesn't seem to work either as even though it does compile, I get an error when I try creating a new UILabel.

I'm kind of new to programming in Swift so I'm not sure if there is an obvious fix to this.

Body:
Like you said, we already have x, y and height available for the label, i.e.

let x: CGFloat = 0
let y: CGFloat = 0
let height: CGFloat = 50

Let's create a label using the above details. Also set the width of the label as UIScreen.main.bounds.width as per your requirement.

let label = UILabel(frame: CGRect(x: x, y: y, width: UIScreen.main.bounds.width, height: height))
label.text = "This is a sample text"

Don't forget to set label's translatesAutoresizingMaskIntoConstraints as false and add it to whatever subview you want.

label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)

Add the relevant constraints of label with its superview - top, bottom, leading, height. You can definitely add bottom constraint if required. That totally depends upon your UI.

I'm adding the label to the top of the viewController's view.

NSLayoutConstraint.activate([
    label.heightAnchor.constraint(equalToConstant: height),
    view.topAnchor.constraint(equalTo: label.topAnchor),
    view.leadingAnchor.constraint(equalTo: label.leadingAnchor),
    view.trailingAnchor.constraint(equalTo: label.trailingAnchor)
    ])


问:
Open a image file then display it in new window
I have a button in my GUI then after selecting a image file I want it to display in new window.

Code:

```<code>import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
a = Tk()

def openimgfile():
    currdir = os.getcwd()
    name = filedialog.askopenfile(initialdir = currdir, title = "Select a Image", filetype = ( ("PNG", "*.png"), ("JPEG", "*.jpg;.*jpeg"), ("All files", "*.*") ) )

a.title("Pattern Matching")
a.minsize(200,200)
button1 = Button(text="Open file",width = 10,height =10,command=openimgfile).pack()

a.mainloop()
</code>```

答:
Use this to display the image in tkinter:

Display image :)

```<code> from tkinter import *

 def makeLabel(parent, image):
     # Make label to display the image
     label = Label(parent, image=image)
     label.pack()

 def showImg():
     # Define root window!
     root = Tk()

     # Bring the image to the script!
     img = PhotoImage(file='YOUR_PIC.png')

     # Show image as label
     makeLabel(root, img)

     # Update root (GUI)
     root.mainloop()

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

Also you can using matplotlib :)

Use library

It's cool  ^_^

You can display an image very simply by using matplotlib:

```<code>import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('YOUR_PIC.png')
imgplot = plt.imshow(img)

plt.show()
</code>```

Install library

But install it before using it :)

python2:

```<code>    pip2 install matplotlib
</code>```

python3:

```<code>    pip3 install matplotlib
</code>```

Body:
I have a button in my GUI then after selecting a image file I want it to display in new window.

Code:

import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
a = Tk()

def openimgfile():
    currdir = os.getcwd()
    name = filedialog.askopenfile(initialdir = currdir, title = "Select a Image", filetype = ( ("PNG", "*.png"), ("JPEG", "*.jpg;.*jpeg"), ("All files", "*.*") ) )

a.title("Pattern Matching")
a.minsize(200,200)
button1 = Button(text="Open file",width = 10,height =10,command=openimgfile).pack()

a.mainloop()

Body:
Use this to display the image in tkinter:

Display image :)

 from tkinter import *

 def makeLabel(parent, image):
     # Make label to display the image
     label = Label(parent, image=image)
     label.pack()

 def showImg():
     # Define root window!
     root = Tk()

     # Bring the image to the script!
     img = PhotoImage(file='YOUR_PIC.png')

     # Show image as label
     makeLabel(root, img)

     # Update root (GUI)
     root.mainloop()

 if __name__ == '__main__':
     showImg()

Also you can using matplotlib :)

Use library

It's cool  ^_^

You can display an image very simply by using matplotlib:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img = mpimg.imread('YOUR_PIC.png')
imgplot = plt.imshow(img)

plt.show()

Install library

But install it before using it :)

python2:

    pip2 install matplotlib

python3:

    pip3 install matplotlib


问:
LDAP server sizelimit was exceeded ( MSAD ) with ldaps_search
using

```<code>call ldaps_search(handle,shandle,filter, attrs, num, rc);
</code>```

with Microsoft Active Directory i get WARNING: LDAP server sizelimit was exceeded.

is there a way to page through somehow in sas?

i have tried ldaps_setOptions with sizeLimit=2000 for example but still generates the warning, as i guess is set on Microsofts side

Thanks

sample:

```<code>more = 1;
do while (more eq 1);
call ldaps_search_page(handle, shandle, filter, attrs, num, rc, more, 1000);
  if rc ne 0 then do;
 more = 0;
 msg = sysmsg();
 put msg;
  end;
/* free search results page */
if shandle NE 0 then do;
call ldaps_free(shandle,rc);
end;
end;
</code>```

答:
It's not possible to control LDAP server sizelimit from the client side (see AD's MaxPageSize), but yes you can still work around this via paging controls.

The idea is to request a paged result set, with a number of entries per page less than server's MaxPageSize limit.

SAS provides the call ldaps_search_page routine that returns only a single page for a given search request and requires subsequent calls to retrieve the entirety of the results :

```<code>CALL LDAPS_SEARCH_PAGE(lHandle, sHandle, filter, attr, num, rc, more <, pageSize>);
</code>```

pageSize (optional) specifies a positive integer value, which is the number of
  results on a page of output. By default, this value is set to 50. If
  pageSize is 0, this function acts as if paging is turned off. This
  argument is case-insensitive.

For example if a query matches n results (exceeding server side limit) and the page size is set to 50, you need to make up to ceil(n/50) calls.

Here is an example taken from the doc, it uses the more argument in a loop to continue retrieving paged results until there is no more information to retrieve :

```<code>more = 1;
do while (more eq 1);
call ldaps_search_page(handle, shandle, filter, attrs, num, rc, more, 50);
...
/* free search results page */
  if shandle NE 0 then do;
  call ldaps_free(shandle,rc);
  end;
end;
</code>```

https://documentation.sas.com/api/docsets/itechdsref/9.4/content/itechdsref.pdf

For those having trouble with more stuck at 1 thus causing the code above to loop forever (I don't know why the reference wouldn't get updated but OP was in this situation), actually you don't need it, incrementing a counter until the number of fetched entries reaches num should do the trick.

Body:
using

call ldaps_search(handle,shandle,filter, attrs, num, rc);

with Microsoft Active Directory i get WARNING: LDAP server sizelimit was exceeded.

is there a way to page through somehow in sas?

i have tried ldaps_setOptions with sizeLimit=2000 for example but still generates the warning, as i guess is set on Microsofts side

Thanks

sample:

more = 1;
do while (more eq 1);
call ldaps_search_page(handle, shandle, filter, attrs, num, rc, more, 1000);
  if rc ne 0 then do;
 more = 0;
 msg = sysmsg();
 put msg;
  end;
/* free search results page */
if shandle NE 0 then do;
call ldaps_free(shandle,rc);
end;
end;

Body:
It's not possible to control LDAP server sizelimit from the client side (see AD's MaxPageSize), but yes you can still work around this via paging controls.

The idea is to request a paged result set, with a number of entries per page less than server's MaxPageSize limit.

SAS provides the call ldaps_search_page routine that returns only a single page for a given search request and requires subsequent calls to retrieve the entirety of the results :

CALL LDAPS_SEARCH_PAGE(lHandle, sHandle, filter, attr, num, rc, more <, pageSize>);

pageSize (optional) specifies a positive integer value, which is the number of
  results on a page of output. By default, this value is set to 50. If
  pageSize is 0, this function acts as if paging is turned off. This
  argument is case-insensitive.

For example if a query matches n results (exceeding server side limit) and the page size is set to 50, you need to make up to ceil(n/50) calls.

Here is an example taken from the doc, it uses the more argument in a loop to continue retrieving paged results until there is no more information to retrieve :

more = 1;
do while (more eq 1);
call ldaps_search_page(handle, shandle, filter, attrs, num, rc, more, 50);
...
/* free search results page */
  if shandle NE 0 then do;
  call ldaps_free(shandle,rc);
  end;
end;

https://documentation.sas.com/api/docsets/itechdsref/9.4/content/itechdsref.pdf

For those having trouble with more stuck at 1 thus causing the code above to loop forever (I don't know why the reference wouldn't get updated but OP was in this situation), actually you don't need it, incrementing a counter until the number of fetched entries reaches num should do the trick.