问:
Manual swiping in view pager using Trinea/android-auto-scroll-view-pager is not working?
I am using third party library for automatic scrolling and touch events in an image slider every thing is working fine except manual swiping of images in image slider. I am not able to swipe images manually.
Name of the library which I am using is
"Trinea/android-auto-scroll-view-pager"

Here is my code for fragment where Ii am using auto scroll view pager:

```<code>public class HomeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    TextView tv_slider, tv_button;
    AutoScrollViewPager mViewPager;

    private static int currentPage = 0;
    private static int NUM_PAGES = 0;
    private static final Integer[] IMAGES= {R.drawable.ecommerce, R.drawable.digital_marketing, R.drawable.explainer, R.drawable.it_services,
            R.drawable.mobile_app, R.drawable.seo, R.drawable.software, R.drawable.webdesign};
    private ArrayList<Integer> ImagesArray = new ArrayList<Integer>();

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public HomeFragment() {

    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_home, container, false);

        tv_slider=(TextView)v.findViewById(R.id.tv_slider);
        tv_slider.setTypeface(EasyFonts.robotoLight(this.getActivity()));
        tv_button=(TextView)v.findViewById(R.id.tv_button);
        tv_button.setTypeface(EasyFonts.robotoLight(this.getActivity()));

        for(int i=0;i<IMAGES.length;i++)
            ImagesArray.add(IMAGES[i]);

        mViewPager = (AutoScrollViewPager) v.findViewById(R.id.pager);
        mViewPager.setAdapter(new SlidingImage_Adapter(getActivity(),ImagesArray));
        mViewPager.setOffscreenPageLimit(1);

        CirclePageIndicator indicator = (CirclePageIndicator)
                v.findViewById(R.id.indicator);

        indicator.setViewPager(mViewPager);

        final float density = getResources().getDisplayMetrics().density;

//Set circle indicator radius
        indicator.setRadius(3 * density);

        NUM_PAGES =IMAGES.length;

        mViewPager.startAutoScroll();
        mViewPager.setInterval(3000);

        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch(motionEvent.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        Log.w("touched","down");
                        mViewPager.stopAutoScroll();
                        return true;
                    //break;

                    case MotionEvent.ACTION_UP:
                        Log.w("touched","up");
                        mViewPager.startAutoScroll();
                        return true;

                }

                return true;
            }
        });

        // Pager listener over indicator
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentPage = position;

            }

            @Override
            public void onPageScrolled(int pos, float arg1, int arg2) {

                switch (pos){

                    case 0:
                        tv_slider.setText(getString(R.string.es_content));
                        break;

                    case 1:
                        tv_slider.setText(getString(R.string.dm_content));
                        break;

                    case 2:
                        tv_slider.setText(getString(R.string.ev_content));
                        break;

                    case 3:
                        tv_slider.setText(getString(R.string.it_content));
                        break;

                    case 4:
                        tv_slider.setText(getString(R.string.md_content));
                        break;

                    case 5:
                        tv_slider.setText(getString(R.string.seo_content));
                        break;

                    case 6:
                        tv_slider.setText(getString(R.string.sd_content));
                        break;

                    case 7:
                        tv_slider.setText(getString(R.string.wd_content));
                        break;

                }

            }

            @Override
            public void onPageScrollStateChanged(int pos) {

            }
        });

        return v;

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onResume() {
        super.onResume();
        mViewPager.startAutoScroll();
    }

    @Override
    public void onStop() {
        super.onStop();
        mViewPager.stopAutoScroll();
    }
}
</code>```

This is my adapter class:

```<code>public  class SlidingImage_Adapter extends PagerAdapter {

    private ArrayList<Integer> IMAGES;
    private LayoutInflater inflater;
    private Context context;

    public SlidingImage_Adapter(Context context, ArrayList<Integer> IMAGES) {
        super();
        this.context = context;
        this.IMAGES=IMAGES;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return IMAGES.size();
    }

    @Override
    public Object instantiateItem(ViewGroup view, int position) {
        View imageLayout = inflater.inflate(R.layout.sliding_images, view, false);

        assert imageLayout != null;
        final ImageView imageView = (ImageView) imageLayout
                .findViewById(R.id.image);

        imageView.setImageResource(IMAGES.get(position));

        view.addView(imageLayout, 0);

        return imageLayout;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

}
</code>```

This is homefragment.xml file

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/background"
    tools:context="com.vamediabox.vamediaboxapp.activities.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@color/colorPrimary">

    </RelativeLayout>

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
       >

        <android.support.v7.widget.CardView

            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:id="@+id/rl_slider"
            android:gravity="center_horizontal"
            app:cardUseCompatPadding="true"
            app:cardElevation="4dp"
            app:cardCornerRadius="3dp"
            app:cardPreventCornerOverlap="false"
            android:layout_centerHorizontal="true">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_margin="2dp"
                android:id="@+id/rl1">

            <cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
                android:id="@+id/pager"
                android:layout_width="fill_parent"
                android:layout_height="200dp"
                android:layout_margin="2dp"
                android:layout_alignParentTop="true" />

                <com.viewpagerindicator.CirclePageIndicator
                    android:id="@+id/indicator"
                    android:layout_width="fill_parent"
                    android:layout_height="20dp"
                    android:layout_centerHorizontal="true"
                    android:layout_below="@+id/pager"
                    android:padding="5dip"
                    app:centered="true"
                    app:fillColor="@color/colorPrimary"
                    app:pageColor="@color/view_color"
                    app:snap="false" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:id="@+id/tv_slider"
                android:layout_marginTop="5dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="5dp"
                android:textSize="14sp"
                android:layout_below="@+id/indicator"
                android:textColor="@color/slider_text"

                />

            </RelativeLayout>

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

</ScrollView>
</RelativeLayout>
</code>```

and last this is sliding_images.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1dip" >

<ImageView
    android:id="@+id/image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:adjustViewBounds="true"
    android:layout_gravity="center"
    android:scaleType="fitXY" />
</FrameLayout>
</code>```

答:
not sure if you still looking for a way to fix this in case you do, check consumeTouch inside AutoScrollViewPager this is where your issue is.

You need to make sure that

```<code>getParent().requestDisallowInterceptTouchEvent(true)
</code>```

is getting called.

hope this helps.

Cheers

Body:
I am using third party library for automatic scrolling and touch events in an image slider every thing is working fine except manual swiping of images in image slider. I am not able to swipe images manually.
Name of the library which I am using is
"Trinea/android-auto-scroll-view-pager"

Here is my code for fragment where Ii am using auto scroll view pager:

public class HomeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    TextView tv_slider, tv_button;
    AutoScrollViewPager mViewPager;

    private static int currentPage = 0;
    private static int NUM_PAGES = 0;
    private static final Integer[] IMAGES= {R.drawable.ecommerce, R.drawable.digital_marketing, R.drawable.explainer, R.drawable.it_services,
            R.drawable.mobile_app, R.drawable.seo, R.drawable.software, R.drawable.webdesign};
    private ArrayList<Integer> ImagesArray = new ArrayList<Integer>();

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public HomeFragment() {

    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_home, container, false);

        tv_slider=(TextView)v.findViewById(R.id.tv_slider);
        tv_slider.setTypeface(EasyFonts.robotoLight(this.getActivity()));
        tv_button=(TextView)v.findViewById(R.id.tv_button);
        tv_button.setTypeface(EasyFonts.robotoLight(this.getActivity()));

        for(int i=0;i<IMAGES.length;i++)
            ImagesArray.add(IMAGES[i]);

        mViewPager = (AutoScrollViewPager) v.findViewById(R.id.pager);
        mViewPager.setAdapter(new SlidingImage_Adapter(getActivity(),ImagesArray));
        mViewPager.setOffscreenPageLimit(1);

        CirclePageIndicator indicator = (CirclePageIndicator)
                v.findViewById(R.id.indicator);

        indicator.setViewPager(mViewPager);

        final float density = getResources().getDisplayMetrics().density;

//Set circle indicator radius
        indicator.setRadius(3 * density);

        NUM_PAGES =IMAGES.length;

        mViewPager.startAutoScroll();
        mViewPager.setInterval(3000);

        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch(motionEvent.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        Log.w("touched","down");
                        mViewPager.stopAutoScroll();
                        return true;
                    //break;

                    case MotionEvent.ACTION_UP:
                        Log.w("touched","up");
                        mViewPager.startAutoScroll();
                        return true;

                }

                return true;
            }
        });

        // Pager listener over indicator
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentPage = position;

            }

            @Override
            public void onPageScrolled(int pos, float arg1, int arg2) {

                switch (pos){

                    case 0:
                        tv_slider.setText(getString(R.string.es_content));
                        break;

                    case 1:
                        tv_slider.setText(getString(R.string.dm_content));
                        break;

                    case 2:
                        tv_slider.setText(getString(R.string.ev_content));
                        break;

                    case 3:
                        tv_slider.setText(getString(R.string.it_content));
                        break;

                    case 4:
                        tv_slider.setText(getString(R.string.md_content));
                        break;

                    case 5:
                        tv_slider.setText(getString(R.string.seo_content));
                        break;

                    case 6:
                        tv_slider.setText(getString(R.string.sd_content));
                        break;

                    case 7:
                        tv_slider.setText(getString(R.string.wd_content));
                        break;

                }

            }

            @Override
            public void onPageScrollStateChanged(int pos) {

            }
        });

        return v;

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onResume() {
        super.onResume();
        mViewPager.startAutoScroll();
    }

    @Override
    public void onStop() {
        super.onStop();
        mViewPager.stopAutoScroll();
    }
}

This is my adapter class:

public  class SlidingImage_Adapter extends PagerAdapter {

    private ArrayList<Integer> IMAGES;
    private LayoutInflater inflater;
    private Context context;

    public SlidingImage_Adapter(Context context, ArrayList<Integer> IMAGES) {
        super();
        this.context = context;
        this.IMAGES=IMAGES;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return IMAGES.size();
    }

    @Override
    public Object instantiateItem(ViewGroup view, int position) {
        View imageLayout = inflater.inflate(R.layout.sliding_images, view, false);

        assert imageLayout != null;
        final ImageView imageView = (ImageView) imageLayout
                .findViewById(R.id.image);

        imageView.setImageResource(IMAGES.get(position));

        view.addView(imageLayout, 0);

        return imageLayout;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

}

This is homefragment.xml file

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/background"
    tools:context="com.vamediabox.vamediaboxapp.activities.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@color/colorPrimary">

    </RelativeLayout>

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
       >

        <android.support.v7.widget.CardView

            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:id="@+id/rl_slider"
            android:gravity="center_horizontal"
            app:cardUseCompatPadding="true"
            app:cardElevation="4dp"
            app:cardCornerRadius="3dp"
            app:cardPreventCornerOverlap="false"
            android:layout_centerHorizontal="true">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_margin="2dp"
                android:id="@+id/rl1">

            <cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
                android:id="@+id/pager"
                android:layout_width="fill_parent"
                android:layout_height="200dp"
                android:layout_margin="2dp"
                android:layout_alignParentTop="true" />

                <com.viewpagerindicator.CirclePageIndicator
                    android:id="@+id/indicator"
                    android:layout_width="fill_parent"
                    android:layout_height="20dp"
                    android:layout_centerHorizontal="true"
                    android:layout_below="@+id/pager"
                    android:padding="5dip"
                    app:centered="true"
                    app:fillColor="@color/colorPrimary"
                    app:pageColor="@color/view_color"
                    app:snap="false" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:id="@+id/tv_slider"
                android:layout_marginTop="5dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="5dp"
                android:textSize="14sp"
                android:layout_below="@+id/indicator"
                android:textColor="@color/slider_text"

                />

            </RelativeLayout>

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

</ScrollView>
</RelativeLayout>

and last this is sliding_images.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1dip" >

<ImageView
    android:id="@+id/image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:adjustViewBounds="true"
    android:layout_gravity="center"
    android:scaleType="fitXY" />
</FrameLayout>

Body:
not sure if you still looking for a way to fix this in case you do, check consumeTouch inside AutoScrollViewPager this is where your issue is.

You need to make sure that

getParent().requestDisallowInterceptTouchEvent(true)

is getting called.

hope this helps.

Cheers


来源: stackexchange

问:
Trying to make an automated table right-alligned - Python 3
So this is what I got so far...

```<code>r = int(input("How many rows?\n"))#Inputs amount of row
c = int(input("How many columns?\n"))#Input amount of columns
largest = (len(str(r**c)))#Multiplying r, c amount of times

for i in range(1,r+1):
    for y in range(1,c+1):
        numb = i**y
        space = " " * ((largest - len(str(numb))))
        print(numb, end=space)
    print ()
</code>```

And this prints like so

```<code>How many rows?
5
How many columns?
6
1    1    1    1    1    1
2    4    8    16   32   64
3    9    27   81   243  729
4    16   64   256  1024 4096
5    25   125  625  3125 15625
</code>```

Trying to make it right-aligned so it looks something like this

```<code>1      1     1     1     1     1
2      4     8    16    32    64
3      9    27    81   243   729
4     16    64   256  1024  4096
5     25   125   625  3125 15625
</code>```

答:
You can use str.format to right-align items in a string

```<code>def printer(rows, cols):
    for i in range(1, rows+1):
        print(('{:>10}'*cols).format(*[i**j for j in range(1, cols+1)]))
</code>```

printer(5, 6) will then print

```<code>         1         1         1         1         1         1
         2         4         8        16        32        64
         3         9        27        81       243       729
         4        16        64       256      1024      4096
         5        25       125       625      3125     15625
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So this is what I got so far...

r = int(input("How many rows?\n"))#Inputs amount of row
c = int(input("How many columns?\n"))#Input amount of columns
largest = (len(str(r**c)))#Multiplying r, c amount of times

for i in range(1,r+1):
    for y in range(1,c+1):
        numb = i**y
        space = " " * ((largest - len(str(numb))))
        print(numb, end=space)
    print ()

And this prints like so

How many rows?
5
How many columns?
6
1    1    1    1    1    1
2    4    8    16   32   64
3    9    27   81   243  729
4    16   64   256  1024 4096
5    25   125  625  3125 15625

Trying to make it right-aligned so it looks something like this

1      1     1     1     1     1
2      4     8    16    32    64
3      9    27    81   243   729
4     16    64   256  1024  4096
5     25   125   625  3125 15625

Body:
You can use str.format to right-align items in a string

def printer(rows, cols):
    for i in range(1, rows+1):
        print(('{:>10}'*cols).format(*[i**j for j in range(1, cols+1)]))

printer(5, 6) will then print

         1         1         1         1         1         1
         2         4         8        16        32        64
         3         9        27        81       243       729
         4        16        64       256      1024      4096
         5        25       125       625      3125     15625


问:
DB Design: Table Inheritance and Hierarchy
The example used does not represent the domain I am actually solving for; it's just for example.

Background

I am defining table inheritance. Planning to use Table API packages & views to handle the necessary logic & presentation.

I also need to define multiple multi-level named hierarchies with disparate attributes.

Combining table inheritance (Location > State, City) & named hierarchies (State <- City), however, is where I've come across a design snag.

The Problem

I want to define a Unique Key enforcing Name of City is Unique within State, but the abstraction of the Name field is preventing that. I can handle it in PL/SQL if needed, but I would like to enforce it at the SQL level (ideally without an additional table) if at all possible.

Constraints

Other tables need to be able to refer to any level of the hierarchy generically (location).

Other tables also need to be able to refer to a specific level of the hierarchy.

Thoughts

I cannot do single table inheritance due to the complexity of the graph of relations.

I have thought about duplicating the Name field for ease, though I'd rather not violate Normal Forms.

Example

```<code>CREATE TABLE location
( id      NUMBER  (  38) PRIMARY KEY
, name    VARCHAR2(1000) NOT NULL
, type_id NUMBER  (  38) NOT NULL
--, other common/super attributes
);

CREATE TABLE state
( id NUMBER(38) PRIMARY KEY
                REFERENCES location (id)
--, child attributes
);

CREATE TABLE city
( id       NUMBER(38) PRIMARY KEY
                      REFERENCES location (id)
, state_id NUMBER(38) NOT NULL
                      REFERENCES state    (id)
--, child attributes
);
</code>```

答:
Adding a "parent_location" to location table maybe works for you.

```<code>CREATE TABLE location
( id      NUMBER  (  38) PRIMARY KEY
, name    VARCHAR2(1000) NOT NULL
, type_id NUMBER  (  38) NOT NULL
, parent_location_id number( 38) NOT NULL
--, other common/super attributes
);

CREATE UNIQUE INDEX location_u2
   ON location (parent_location_id, name);

CREATE TABLE city
( id       NUMBER(38) PRIMARY KEY
                      REFERENCES location (id)
, --state_id gone away
--, child attributes
);
</code>```

It also would prevent having two states with the same name.

The disadvantage is you'll need to use a dummy "0" location_id for the top node.

Best regards.

Body:
The example used does not represent the domain I am actually solving for; it's just for example.

Background

I am defining table inheritance. Planning to use Table API packages & views to handle the necessary logic & presentation.

I also need to define multiple multi-level named hierarchies with disparate attributes.

Combining table inheritance (Location > State, City) & named hierarchies (State <- City), however, is where I've come across a design snag.

The Problem

I want to define a Unique Key enforcing Name of City is Unique within State, but the abstraction of the Name field is preventing that. I can handle it in PL/SQL if needed, but I would like to enforce it at the SQL level (ideally without an additional table) if at all possible.

Constraints

Other tables need to be able to refer to any level of the hierarchy generically (location).

Other tables also need to be able to refer to a specific level of the hierarchy.

Thoughts

I cannot do single table inheritance due to the complexity of the graph of relations.

I have thought about duplicating the Name field for ease, though I'd rather not violate Normal Forms.

Example

CREATE TABLE location
( id      NUMBER  (  38) PRIMARY KEY
, name    VARCHAR2(1000) NOT NULL
, type_id NUMBER  (  38) NOT NULL
--, other common/super attributes
);

CREATE TABLE state
( id NUMBER(38) PRIMARY KEY
                REFERENCES location (id)
--, child attributes
);

CREATE TABLE city
( id       NUMBER(38) PRIMARY KEY
                      REFERENCES location (id)
, state_id NUMBER(38) NOT NULL
                      REFERENCES state    (id)
--, child attributes
);

Body:
Adding a "parent_location" to location table maybe works for you.

CREATE TABLE location
( id      NUMBER  (  38) PRIMARY KEY
, name    VARCHAR2(1000) NOT NULL
, type_id NUMBER  (  38) NOT NULL
, parent_location_id number( 38) NOT NULL
--, other common/super attributes
);

CREATE UNIQUE INDEX location_u2
   ON location (parent_location_id, name);

CREATE TABLE city
( id       NUMBER(38) PRIMARY KEY
                      REFERENCES location (id)
, --state_id gone away
--, child attributes
);

It also would prevent having two states with the same name.

The disadvantage is you'll need to use a dummy "0" location_id for the top node.

Best regards.


问:
Spring CustomNumberEditor parses numbers that are not numbers
I'm using Spring CustomNumberEditor editor to bind my float values and I've experimented that if in the value is not a number sometimes it can parse the value and no error is returned.

number=10 ...... then the number is 10 and there's no errors

number=10a ......   then the number is 10 and there's no errors

number=10a25 ...... then the number is 10 and there's no errors

number=a ...... error because the number is not valid

So it seems that the editor parses the value until it can and omit the rest. Is there any way to configure this editor so the validation is strict (so numbers like 10a or 10a25 result in error) or do I have to build my custom implementation. I'm looking something like setting lenient to false in CustomDateEditor/DateFormat so dates cannot be parsed to the most probable one.

The way I register the editor is:

```<code>@InitBinder
public void initBinder(WebDataBinder binder){
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setGroupingUsed(false);
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}
</code>```

Thanks.

答:
I think the most elegant approach would be to use NumberFormat.parse(String,ParsePosition), something like this:

```<code>public class MyNumberEditor extends PropertyEditorSupport {
    private NumberFormat f;
    public MyNumberEditor(NumberFormat f) {
        this.f = f;
    }

    public void setAsText(String s) throws IllegalArgumentException {
        String t = s.trim();
        try {
            ParsePosition pp = new ParsePosition(0);
            Number n = f.parse(t, pp);
            if (pp.getIndex() != t.length()) throw new IllegalArgumentException();
            setValue((Float) n.floatValue());
        } catch (ParseException ex) {
            throw new IllegalArgumentException(ex);
        }
    }

    ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using Spring CustomNumberEditor editor to bind my float values and I've experimented that if in the value is not a number sometimes it can parse the value and no error is returned.

number=10 ...... then the number is 10 and there's no errors

number=10a ......   then the number is 10 and there's no errors

number=10a25 ...... then the number is 10 and there's no errors

number=a ...... error because the number is not valid

So it seems that the editor parses the value until it can and omit the rest. Is there any way to configure this editor so the validation is strict (so numbers like 10a or 10a25 result in error) or do I have to build my custom implementation. I'm looking something like setting lenient to false in CustomDateEditor/DateFormat so dates cannot be parsed to the most probable one.

The way I register the editor is:

@InitBinder
public void initBinder(WebDataBinder binder){
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setGroupingUsed(false);
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}

Thanks.

Body:
I think the most elegant approach would be to use NumberFormat.parse(String,ParsePosition), something like this:

public class MyNumberEditor extends PropertyEditorSupport {
    private NumberFormat f;
    public MyNumberEditor(NumberFormat f) {
        this.f = f;
    }

    public void setAsText(String s) throws IllegalArgumentException {
        String t = s.trim();
        try {
            ParsePosition pp = new ParsePosition(0);
            Number n = f.parse(t, pp);
            if (pp.getIndex() != t.length()) throw new IllegalArgumentException();
            setValue((Float) n.floatValue());
        } catch (ParseException ex) {
            throw new IllegalArgumentException(ex);
        }
    }

    ...
}


问:
Two-factor authentication with Google Authenticator - manually type key instead of scanning QR code
In Google Authenticator app you can either scan a QR code or manually type a key provided by the issuer.

In the following screenshot you can see the setup of 2FA among Google Security settings, displaying how to get the TOTP by following the 2nd method.

My question is: how is this key generated?

I'm trying to support 2FA with Google Authenticator for my website and I found many references and docs about how to generate the QR code, but none even mentioning the alternate method.

Edit:

To be a bit clearer, I'm supporting 2FA with Google Authenticator in a Grails 3 webapp. I already implemented the whole user flow by generating a secret key (Base32 string) for each user, providing a QR code for users to scan, and verifying the TOTP on login. I used as dependencies:

org.jboss.aerogear:aerogear-otp-java, aerogear OTP to conveniently verify user secret key against the TOTP from GA

org.grails.plugins:qrcode, qrcode Grails plugin to generate the QR code

My question is about the 2 ways to add a new entry in Google Authenticator app:
1. scan QR code (everything ok on my side)
2. manually type the account name along with an alphabetic code (in my 1st screenshot, the code is provided within Google Security Settings)

You can see an explicatory screenshot from GA for Android:

How can I generate and provide such code (starting with fzee in the 1st screenshot, and named "provided key" in the 2nd one) to the user? I'm sure it's an encoding of the same data string also encoded in the QR code, but I don't know which (not simply Base32).

答:
The Google Authenticator Setup QR code is generated based on a few things, one of these is the "secret key", so depending on the codebase you are using to build it into your site the "secret key" is normally generated first and that key is then used to generate the QR code.

If you look at this node.js module you can see what I am talking about

```<code>// generate base32 secret
var secret = GA.encode('base 32 encoded user secret') || GA.secret();

// get QRCode in SVG format
var qrCode = GA.qrCode('akanass', 'otp.js', secret);
</code>```

https://github.com/njl07/otp.js/#qrcode-generation

Here is another example site where you can manually generate the QR code,
You can provide a Label, User, Key and URL, and that will then generate the QR code.

https://dan.hersam.com/tools/gen-qr-code.html

Let me know what codebase you are trying to use to implement this into your site then I can help you track down where the secret key is generated

Body:
The Google Authenticator Setup QR code is generated based on a few things, one of these is the "secret key", so depending on the codebase you are using to build it into your site the "secret key" is normally generated first and that key is then used to generate the QR code.

If you look at this node.js module you can see what I am talking about

// generate base32 secret
var secret = GA.encode('base 32 encoded user secret') || GA.secret();

// get QRCode in SVG format
var qrCode = GA.qrCode('akanass', 'otp.js', secret);

https://github.com/njl07/otp.js/#qrcode-generation

Here is another example site where you can manually generate the QR code,
You can provide a Label, User, Key and URL, and that will then generate the QR code.

https://dan.hersam.com/tools/gen-qr-code.html

Let me know what codebase you are trying to use to implement this into your site then I can help you track down where the secret key is generated


问:
Java - Issue in a Recursive Backtracking Maze
After reading this blog post, I decided to use it to create a maze in Java to use the A* algorithm to solve. The maze generation works well. I've modified the code slightly to work with Java & my purposes.

Unfortunately, I didn't think about it when I started, but the example prints it as ASCII. I would like to have it be a two dimensional array with one's and zero's to use for the path finding.

Currently, it prints the characters, as an example if width & height = 10, it would look something like this:

```<code>___________________
| |  _  |_    |_  |
| | |  _|  _| |   |
|___| |_  | | | | |
|  ___|  _| |___| |
|_  |_  |  _|  ___|
| |_____|  ___|   |
|      _| |  ___| |
| | |_|  _| | |  _|
|_|_________|_____|
</code>```

I also have it draw the maze to a GUI. This one looks like this (it is rotated 90 degrees counter clockwise so that (1, 1) is in the bottom left):

I currently have the ASCII maze being added to a two dimensional String array. the possible values of the strings in the array are:

```<code>" ",
"_",
"  ",
" _",
" |",
"_ ",
"__",
"_|",
</code>```

would there be a way to loop through the array containing the maze, and assign a 1 or 0 based on what the next character is in the ASCII maze? if so, how would you account for the additional space above the horizontal lines, that are not going to be recognized as an open space?

答:
Just double the height internally, then you can convert

'_' to '▄' (0 above 1)

'|' to '█' (1 above 1)

' ' to ' ' (0 above 0)

Body:
After reading this blog post, I decided to use it to create a maze in Java to use the A* algorithm to solve. The maze generation works well. I've modified the code slightly to work with Java & my purposes.

Unfortunately, I didn't think about it when I started, but the example prints it as ASCII. I would like to have it be a two dimensional array with one's and zero's to use for the path finding.

Currently, it prints the characters, as an example if width & height = 10, it would look something like this:

___________________
| |  _  |_    |_  |
| | |  _|  _| |   |
|___| |_  | | | | |
|  ___|  _| |___| |
|_  |_  |  _|  ___|
| |_____|  ___|   |
|      _| |  ___| |
| | |_|  _| | |  _|
|_|_________|_____|

I also have it draw the maze to a GUI. This one looks like this (it is rotated 90 degrees counter clockwise so that (1, 1) is in the bottom left):

I currently have the ASCII maze being added to a two dimensional String array. the possible values of the strings in the array are:

" ",
"_",
"  ",
" _",
" |",
"_ ",
"__",
"_|",

would there be a way to loop through the array containing the maze, and assign a 1 or 0 based on what the next character is in the ASCII maze? if so, how would you account for the additional space above the horizontal lines, that are not going to be recognized as an open space?


问:
Target an element when another:checked
Here’s the HTML:

```<code><div>
  <label for="n-0">Label</label>
  <input id="n-0" type="checkbox"/>
</div>
</code>```

```<code><p class="special"></p>
</code>```

Is there a CSS-only selector that can target p.special when input:checked? Also notice that p.special is a lever higher than input.

答: No. You can target an element that is a sibling of input[type=checkbox]:checked but not it's parent's sibling.

Title: Target an element when another:checked

Body:
Here’s the HTML:

  Label
  <input id="n-0" type="checkbox"/>

Is there a CSS-only selector that can target p.special when input:checked? Also notice that p.special is a lever higher than input.


问:
How to assign vectors into multiple variables in dplyr mutate
I have the following data frame:

```<code>library(tidyverse)

dat <-structure(list(motif_name_binned = c("Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1",
"Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2",
"Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3"
), motif_score = c(6.816695, 6.816695, 6.816695)), row.names = c(NA,
-3L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("motif_name_binned",
"motif_score"))

dat
</code>```

Which gives this:

```<code>> dat
# A tibble: 3 x 2
                                                  motif_name_binned motif_score
                                                              <chr>       <dbl>
1 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1    6.816695
2 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2    6.816695
3 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3    6.816695
</code>```

I can get what I want by  extracting the value of motif_named_binned using this code:

```<code>dat %>%
  mutate(motif = str_match(motif_name_binned,"^(.*?)\\/.*?")[,2],
         inst =  str_match(motif_name_binned,"^.*?\\/.*?\\/.*?\\.instid_(.*?)\\.bin\\d+")[,2],
         binno = as.integer(str_match(motif_name_binned,"^.*?\\/.*?\\/.*?\\.bin(\\d+)")[,2]))
</code>```

Which gives

```<code># A tibble: 3 x 5
                                                  motif_name_binned motif_score        motif                     inst binno
                                                              <chr>       <dbl>        <chr>                    <chr> <int>
1 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1    6.816695 Ddit3::Cebpa chr1:183286845-183287245     1
2 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2    6.816695 Ddit3::Cebpa chr1:183286845-183287245     2
3 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3    6.816695 Ddit3::Cebpa chr1:183286845-183287245     3
</code>```

But notice that I have to execute the regex 3 times and assign it to a variable one by one. Where in fact I can use single regex such as this:

```<code>str_match(motif_name_binned,"^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)")[,c(2,3,4)]
</code>```

How I incorporate this later all-in-one regex in dplyr mutate()?

答:
You can use tidyr::extract to convert the capturing groups in the regular expression into new columns:

```<code>library(tidyr)
dat %>%
    extract(motif_name_binned, c('motif', 'inst', 'binno'), regex = "^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)", remove = FALSE)

# A tibble: 3 x 5
#                                                  motif_name_binned        motif                     inst binno motif_score
#*                                                             <chr>        <chr>                    <chr> <chr>       <dbl>
#1 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1 Ddit3::Cebpa chr1:183286845-183287245     1    6.816695
#2 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2 Ddit3::Cebpa chr1:183286845-183287245     2    6.816695
#3 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3 Ddit3::Cebpa chr1:183286845-183287245     3    6.816695
</code>```

Body:
I have the following data frame:

library(tidyverse)

dat <-structure(list(motif_name_binned = c("Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1",
"Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2",
"Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3"
), motif_score = c(6.816695, 6.816695, 6.816695)), row.names = c(NA,
-3L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("motif_name_binned",
"motif_score"))

dat

Which gives this:

> dat
# A tibble: 3 x 2
                                                  motif_name_binned motif_score
                                                              <chr>       <dbl>
1 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1    6.816695
2 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2    6.816695
3 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3    6.816695

I can get what I want by  extracting the value of motif_named_binned using this code:

dat %>%
  mutate(motif = str_match(motif_name_binned,"^(.*?)\\/.*?")[,2],
         inst =  str_match(motif_name_binned,"^.*?\\/.*?\\/.*?\\.instid_(.*?)\\.bin\\d+")[,2],
         binno = as.integer(str_match(motif_name_binned,"^.*?\\/.*?\\/.*?\\.bin(\\d+)")[,2]))

Which gives

# A tibble: 3 x 5
                                                  motif_name_binned motif_score        motif                     inst binno
                                                              <chr>       <dbl>        <chr>                    <chr> <int>
1 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1    6.816695 Ddit3::Cebpa chr1:183286845-183287245     1
2 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2    6.816695 Ddit3::Cebpa chr1:183286845-183287245     2
3 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3    6.816695 Ddit3::Cebpa chr1:183286845-183287245     3

But notice that I have to execute the regex 3 times and assign it to a variable one by one. Where in fact I can use single regex such as this:

str_match(motif_name_binned,"^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)")[,c(2,3,4)]

How I incorporate this later all-in-one regex in dplyr mutate()?

Body:
You can use tidyr::extract to convert the capturing groups in the regular expression into new columns:

library(tidyr)
dat %>%
    extract(motif_name_binned, c('motif', 'inst', 'binno'), regex = "^(.*?)\\/.*?\\/.*?\\.instid_(.*?)\\.bin(\\d+)", remove = FALSE)

# A tibble: 3 x 5
#                                                  motif_name_binned        motif                     inst binno motif_score
#*                                                             <chr>        <chr>                    <chr> <chr>       <dbl>
#1 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin1 Ddit3::Cebpa chr1:183286845-183287245     1    6.816695
#2 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin2 Ddit3::Cebpa chr1:183286845-183287245     2    6.816695
#3 Ddit3::Cebpa/MA0019.1/Jaspar.instid_chr1:183286845-183287245.bin3 Ddit3::Cebpa chr1:183286845-183287245     3    6.816695


问:
Why does changing a variable from a lambda not work?
I have been working on Tkinter and am finding trouble passing values between different frames, so I followed this tutorial here, using the "shared data" solution provided by Bryan Oakley and adding it to my own code.
Except I cannot set the value in the "shared data" dictionary as a command on a button.

A few comments in the code below outline the problem. If I just try to change the variable during the init of my choice page, it changes normally. But putting it in a lambda means that the dictionary variable won't change at all. And trying to use a def for the button command has its own complications.

```<code>import tkinter as tk
import tkinter.ttk as ttk

# from tkinter import messagebox

TITLE_FONT = ("Segoe UI Light", 22)
SUBTITLE_FONT = ("Segoe UI Light", 12)

window_size = [300, 200]

resistors = []
choice = "default"

class RegApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.iconbitmap(self, default="test.ico")
        tk.Tk.wm_title(self, "Test")

        self.shared_data = {
            "choice": tk.StringVar(),
        }

        container = tk.Frame(self, width=window_size[0], height=window_size[1])
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in panels:
            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="NSEW")

        self.show_frame(WelcomePage)

    def show_frame(self, container):
        frame = self.frames[container]
        frame.tkraise()

class WelcomePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        title_label = ttk.Label(self, text="Welcome", font=TITLE_FONT)
        subtitle_label = ttk.Label(self, text="Let's run some numbers.", font=SUBTITLE_FONT)
        start_button = ttk.Button(self, text="Begin", width=24, command=lambda: controller.show_frame(ChoicePage))
        title_label.pack(pady=(40, 5))
        subtitle_label.pack(pady=(0, 10))
        start_button.pack()

class ChoicePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.controller.shared_data["choice"].set("test2")  # Here, the variable is set fine

        title_label = ttk.Label(self, text="Is your resistor network \nin series or parallel?", font=SUBTITLE_FONT,
                                justify=tk.CENTER)
        series_button = ttk.Button(self, text="Series", width=24,
                                   command=lambda: [self.controller.shared_data["choice"].set("series"), controller.show_frame(ValuePage)])
        # But when I use it in a lambda, the variable doesn't even seem to set at all. It switches to the next page and has the value ""
        parallel_button = ttk.Button(self, text="Parallel", width=24,
                                     command=lambda: controller.show_frame(ValuePage))

        title_label.pack()
        series_button.pack()
        parallel_button.pack()

        # TODO Make the user select between 'series' and 'parallel'

class ValuePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        title_label = ttk.Label(self, text=self.controller.shared_data["choice"].get(), font=SUBTITLE_FONT,
                                justify=tk.CENTER)

        title_label.pack()

panels = [WelcomePage, ChoicePage, ValuePage]

app = RegApp()
app.resizable(False, False)
app.geometry('{}x{}'.format(window_size[0], window_size[1]))
app.mainloop()
</code>```

答: Why are you using 'controller' instead of 'self.controller'? It's kind of confusing that you assign 'self.controller' at the start of the constructor and then you use 'controller' instead. Maybe that variable shadowing is causing your problem.</p>

Body:
I have been working on Tkinter and am finding trouble passing values between different frames, so I followed this tutorial here, using the "shared data" solution provided by Bryan Oakley and adding it to my own code.
Except I cannot set the value in the "shared data" dictionary as a command on a button.

A few comments in the code below outline the problem. If I just try to change the variable during the init of my choice page, it changes normally. But putting it in a lambda means that the dictionary variable won't change at all. And trying to use a def for the button command has its own complications.

import tkinter as tk
import tkinter.ttk as ttk

# from tkinter import messagebox

TITLE_FONT = ("Segoe UI Light", 22)
SUBTITLE_FONT = ("Segoe UI Light", 12)

window_size = [300, 200]

resistors = []
choice = "default"

class RegApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.iconbitmap(self, default="test.ico")
        tk.Tk.wm_title(self, "Test")

        self.shared_data = {
            "choice": tk.StringVar(),
        }

        container = tk.Frame(self, width=window_size[0], height=window_size[1])
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in panels:
            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="NSEW")

        self.show_frame(WelcomePage)

    def show_frame(self, container):
        frame = self.frames[container]
        frame.tkraise()

class WelcomePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        title_label = ttk.Label(self, text="Welcome", font=TITLE_FONT)
        subtitle_label = ttk.Label(self, text="Let's run some numbers.", font=SUBTITLE_FONT)
        start_button = ttk.Button(self, text="Begin", width=24, command=lambda: controller.show_frame(ChoicePage))
        title_label.pack(pady=(40, 5))
        subtitle_label.pack(pady=(0, 10))
        start_button.pack()

class ChoicePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.controller.shared_data["choice"].set("test2")  # Here, the variable is set fine

        title_label = ttk.Label(self, text="Is your resistor network \nin series or parallel?", font=SUBTITLE_FONT,
                                justify=tk.CENTER)
        series_button = ttk.Button(self, text="Series", width=24,
                                   command=lambda: [self.controller.shared_data["choice"].set("series"), controller.show_frame(ValuePage)])
        # But when I use it in a lambda, the variable doesn't even seem to set at all. It switches to the next page and has the value ""
        parallel_button = ttk.Button(self, text="Parallel", width=24,
                                     command=lambda: controller.show_frame(ValuePage))

        title_label.pack()
        series_button.pack()
        parallel_button.pack()

        # TODO Make the user select between 'series' and 'parallel'

class ValuePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        title_label = ttk.Label(self, text=self.controller.shared_data["choice"].get(), font=SUBTITLE_FONT,
                                justify=tk.CENTER)

        title_label.pack()

panels = [WelcomePage, ChoicePage, ValuePage]

app = RegApp()
app.resizable(False, False)
app.geometry('{}x{}'.format(window_size[0], window_size[1]))
app.mainloop()


问:
Force an element to be 100% height when the parent is shimmed taller by another child
Here I have a parent div containing two children. Child 1 is set to 100% height, but it does not display at the actual height of parent, because child 2 is forcing the parent div taller.

```<code><div style="height: 50px; width:106px">
  <div style="border: 1px solid red; display: flex">

    <span style="border: 1px solid blue; height: 100%;">Child 1</span>

    <span style="border: 1px solid green; height: 100px;">Child 2</span>

  </div>
</div>
</code>```

How can I get child 1 to match the actual height of the parent div in this scenario? I want to do this with pure HTML/CSS.

答:
your issue is because your child1 is inherit from parent. if you set it 100%, means the size of your child 1 will be 50px. to make it auto remove your child 1 height: 100%;
below is a sample.

```<code><div style="height: 50px; width:106px">
  <div style="border: 1px solid red; display: flex">

    <span style="border: 1px solid blue;">Child 1</span>

    <span style="border: 1px solid green; height: 100px;">Child 2</span>

  </div>
</div>
</code>```

Body:
Here I have a parent div containing two children. Child 1 is set to 100% height, but it does not display at the actual height of parent, because child 2 is forcing the parent div taller.

    Child 1

    Child 2

How can I get child 1 to match the actual height of the parent div in this scenario? I want to do this with pure HTML/CSS.

Body:
your issue is because your child1 is inherit from parent. if you set it 100%, means the size of your child 1 will be 50px. to make it auto remove your child 1 height: 100%;
below is a sample.

<div style="height: 50px; width:106px">
  <div style="border: 1px solid red; display: flex">
    &nbsp;
    <span style="border: 1px solid blue;">Child 1</span>
    &nbsp;
    <span style="border: 1px solid green; height: 100px;">Child 2</span>
    &nbsp;
  </div>
</div>


Title: Trying to make an automated table right-alligned - Python 3

Body:
One way to do this would be with string alignment (assuming you do not need Python 2):

r = 6
c = 6

for i in range(1,r+1):
    numbs = [i**y for y in range(1,c+1)]
    print(
        '  '.join(['{:>12}'.format(y**i) for y in range(1,c+1)])
    )

Prints

   1             1             1             1             1             1
   2             4             8            16            32            64
   3             9            27            81           243           729
   4            16            64           256          1024          4096
   5            25           125           625          3125         15625
   6            36           216          1296          7776         46656


问:
Link VSTS issues to wiki
It's possible to link wiki page to issues in VSTS using the "#" sign in description or comments. Is there a way of navigatating this link in the opposite direction from issue to wiki?
I'm thinking of something like the "mentioned in" section in Jira issues that permitts to navigate related documentation from definition.
Thanks a lot!</p>

答:
VSTS has no issues but has work items correspondingly.

And yes, you can link work item in wiki page. The format is #work_item_ID.

Such as below example, the format #195 will link the work item PBI p8:

For the opposite (show the wiki page as the link in the work item), it's not available for Now. Since WIT link is mainly designed for linking relations which has effect for the work item. You can refer details about WIT link Types.

For your situation, it's necessary to show the wiki page in the work item links, you can post the idea in VSTS user voice.

Title: Link VSTS issues to wiki


问:
Pull data from Tableau Server into Pandas Dataframe
My goal is to join three datasources that are only available to me through Tableau Server (no direct database access). The data is too large to efficiently use Tableau's Data Blending.

One way forward is to pull the data from the three Tableau Server Datasources into a Pandas dataframe, do the necessary manipulations, and save down an Excel File to use as a datasource for a visualization in Tableau.

I have found lots of information on the TabPy module that allows one to convert a Pandas dataframe to a Tableau Data Extract but have not found much re: how to pull data from Tableau server in an automated fashion.

I have also read about tabcmd as a way of automating tasks, but do not have the necessary admin permissions.

Let me know if you need further information.

答:
Tabcmd does not require admin privileges. Anyone with permissions to Server can use it, but it will respect the privileges you do have. You can install tabcmd on computers other than your server without needing extra license keys.

That being said, it's very simple to automate data downloading. Take the URL to your workbook and add ".csv" to the end of it. The .csv goes at the end of the URL, not any query parameters you have.

For example: http://[Tableau Server Location]/views/[Workbook Name]/[View Name].csv

Using URL parameters, you can customize the data filters and how it looks. Just make sure you put the .csv before the ? for any query parameters.

More info for this plus a few others hacks at http://www.vizwiz.com/2014/03/the-greatest-tableau-tip-ever-exporting.html.


问:
PHP short-ternary ("Elvis") operator vs null coalescing operator
Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?

When do they behave differently and when in the same way (if that even happens)?

```<code>$a ?: $b
</code>```

VS.

```<code>$a ?? $b
</code>```

答:
Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:

```<code><?php
# case 1:
$greeting = 'Hola';
echo $greeting ?? 'Hi There'; # outputs: 'Hola'

# case 2:
$greeting = null;
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

# case 3:
unset($greeting);
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'
</code>```

The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.

Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:

```<code><?php /* example: checking for the $_POST field that goes by the name of 'fullname'*/
# in ternary operator
echo "Welcome ", (isset($_POST['fullname']) && !is_null($_POST['fullname']) ? $_POST['fullname'] : 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
# in null coalecing operator
echo "Welcome ", ($_POST['fullname'] ?? 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
</code>```

So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.

Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.

Credits: http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples

ContentLicense: CC BY-SA 4.0

Body:
Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?

When do they behave differently and when in the same way (if that even happens)?

$a ?: $b

VS.

$a ?? $b

Body:
Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:

<?php
# case 1:
$greeting = 'Hola';
echo $greeting ?? 'Hi There'; # outputs: 'Hola'

# case 2:
$greeting = null;
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

# case 3:
unset($greeting);
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'

The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.

Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:

<?php /* example: checking for the $_POST field that goes by the name of 'fullname'*/
# in ternary operator
echo "Welcome ", (isset($_POST['fullname']) && !is_null($_POST['fullname']) ? $_POST['fullname'] : 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
# in null coalecing operator
echo "Welcome ", ($_POST['fullname'] ?? 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.

So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.

Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.

Credits: http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples


问:
Deploy FeathersJS App on Heroku
I'm trying to deploy my feathersjs web app on heroku, and since feathers is simply an express wrapper I thought it was like deploy an ordinary node app. I got the "npm start" script on my package.json, I added heroku remote to my git repo and when I push heroku run "yarn install" and the "npm start" script. But just when the app start, an error occurs:
heroku logs

I can't figure out what happen, any suggestions?
Maybe I could dockerize my app, someone could help me to find the proper implementation?

Thanks everybody

答: It is the same as Express but the generated application will by default use feathers-configuration to pull in your application settings. From the error message it looks like you are not providing a proper NODE_ENV environment variable which has to be set to production when deploying to Heroku.

Title: Deploy FeathersJS App on Heroku


问:
Dates overwriting one another in php
Okay, so I'm trying to get two variables. One with yesterday's date, one with a date six days from today. This is so I can query google calendar for events happening this week.
I'm building a date time object, setting the date to today, then trying to store the values in two new variables. However, when I set the second variable, the first is getting modified as well. It appears to be assigning the variables by a reference to the object instead of the value I'm trying to stick into it.</p>

```<code>$todayData = explode("-", date("Y-m-d", Time()));
//Get DateTime for Yesterday
$today = new DateTime();
$today->setDate($todayData[0], $todayData[1], $todayData[2]);
echo $today->format("Y-m-d");
echo "<br />";
//Yesterday
$startDate = $today->modify("-1 day");
echo $startDate->format("Y-m-d");
echo "<br />";
//End of the week
$endDate = $today->modify("+6 day");
echo $endDate->format("Y-m-d");
echo "<br />";

//recheck yesterday
echo $startDate->format("Y-m-d");
</code>```

答:
When you modify $today, you're modifying a reference to a newly created object. In turn, since $startDate and $endDate both reference $today, they are viewing the same object.

One solution is to return a new DateTime object each time you call the modify() method I assume you've created. This would then allow you to have a brand new date every time modify() is used, but then this wouldn't really modify the original DateTime object.

Another option is to use cloning in your object. This makes a new object with the same value as the object you're duplicating. See here: http://php.net/manual/en/language.oop5.cloning.php

Title: Dates overwriting one another in php

Body:
Okay, so I'm trying to get two variables. One with yesterday's date, one with a date six days from today. This is so I can query google calendar for events happening this week.
I'm building a date time object, setting the date to today, then trying to store the values in two new variables. However, when I set the second variable, the first is getting modified as well. It appears to be assigning the variables by a reference to the object instead of the value I'm trying to stick into it.

$todayData = explode("-", date("Y-m-d", Time()));
//Get DateTime for Yesterday
$today = new DateTime();
$today->setDate($todayData[0], $todayData[1], $todayData[2]);
echo $today->format("Y-m-d");
echo "
";
//Yesterday
$startDate = $today->modify("-1 day");
echo $startDate->format("Y-m-d");
echo "
";
//End of the week
$endDate = $today->modify("+6 day");
echo $endDate->format("Y-m-d");
echo "
";

//recheck yesterday
echo $startDate->format("Y-m-d");


问:
Idris - lazy evaluation issue
Consider this program:

```<code>module test

import Effects
import Effect.StdIO

(>>==) : Maybe a -> Lazy (a -> Maybe b) -> Maybe b
(>>==) Nothing (Delay map) = Nothing
(>>==) (Just x) (Delay map) = map x

nothing : String -> Eff (Maybe String) [STDIO]
nothing s = do
    putStrLn s
    pure Nothing

func : Maybe String -> String -> Maybe String
func Nothing _ = Nothing
func (Just s) t = Just (s ++ t)

test : Eff () [STDIO]
test = do
    let m = !(nothing "a") >>== (func !(nothing "b"))
    putStrLn "end"

main : IO ()
main = run test
</code>```

since the right hand side of >>== is declared lazy and !(nothing "a") returns Nothing, I would expect that the right hand side of >>== would not be evaluated.

But actually it does get evaluated, and I can't understand why...

More broadly, I'm trying to concatenate Eff computations that return maybe and stop the execution when I get the first Nothing

答:
Desugar the ! notation.

```<code>test = do
    x <- nothing "a"
    y <- nothing "b"
    let m = x >>== (func y)
    putStrLn "end"
</code>```

Clearly "a", "b", and "end" will all be printed, but func may not be evaluated.

I think you'll need have to define >>== to act on (some) Eff values, rather than directly on Maybes.

HTH

Title: Idris - lazy evaluation issue

Body:
Consider this program:

module test

import Effects
import Effect.StdIO

(>>==) : Maybe a -> Lazy (a -> Maybe b) -> Maybe b
(>>==) Nothing (Delay map) = Nothing
(>>==) (Just x) (Delay map) = map x

nothing : String -> Eff (Maybe String) [STDIO]
nothing s = do
    putStrLn s
    pure Nothing

func : Maybe String -> String -> Maybe String
func Nothing _ = Nothing
func (Just s) t = Just (s ++ t)

test : Eff () [STDIO]
test = do
    let m = !(nothing "a") >>== (func !(nothing "b"))
    putStrLn "end"

main : IO ()
main = run test

since the right hand side of >>== is declared lazy and !(nothing "a") returns Nothing, I would expect that the right hand side of >>== would not be evaluated.

But actually it does get evaluated, and I can't understand why...

More broadly, I'm trying to concatenate Eff computations that return maybe and stop the execution when I get the first Nothing

Body:
Desugar the ! notation.

test = do
    x <- nothing "a"
    y <- nothing "b"
    let m = x >>== (func y)
    putStrLn "end"

Clearly "a", "b", and "end" will all be printed, but func may not be evaluated.

I think you'll need have to define >>== to act on (some) Eff values, rather than directly on Maybes.

HTH


问:
axes3d.plot_wireframe(X,Y,Z) Error
I'm trying to learn Python through a tutorial on youtube and I'm having some difficulies working with 3D graphs. Long stories short, I continuously get (if

```<code>Z.ndim != 2:
AttributeError: 'list' object has no attribute 'ndim')
</code>```

error while trying to launch this simple program:

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()

chart = fig.add_subplot(1,1,1,projection = '3d')

X,Y,Z = [1,2,3,4,5,6,7,8],[2,5,3,8,9,5,6,1],[3,6,2,7,5,4,5,6]

chart.plot_wireframe(X,Y,Z)

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

I know that it is related to the Axes3.plot_wireframe() method but Could anyone explain to me what's happening.

答: I had the exact problem (example from video not working though exactly copied). Without looking into the source code I'm assuming a reality check was added to matplotlib 2.1.0 that NOW stops 1D arrays from being used in plot_wireframe. Changing that method call to simply "plot" did indeed fix the problem.</p>

Title: axes3d.plot_wireframe(X,Y,Z) Error

Body:
I'm trying to learn Python through a tutorial on youtube and I'm having some difficulies working with 3D graphs. Long stories short, I continuously get (if

Z.ndim != 2:
AttributeError: 'list' object has no attribute 'ndim')

error while trying to launch this simple program:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()

chart = fig.add_subplot(1,1,1,projection = '3d')

X,Y,Z = [1,2,3,4,5,6,7,8],[2,5,3,8,9,5,6,1],[3,6,2,7,5,4,5,6]

chart.plot_wireframe(X,Y,Z)

plt.show()

I know that it is related to the Axes3.plot_wireframe() method but Could anyone explain to me what's happening.


问:
jQuery sort array based on number after last comma
Suppose I have an array:

```<code>["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"]
</code>```

How could I sort the array such that the last numbers in each array element are in descending order? That is:

```<code>["Team B, 7, 1, 14","Team A, 6, 2, 12","Team C, 4, 4, 8"]
</code>```

I have checked out various compare functions, but I cannot figure out how to tailor them to this specific situation.

答:
You have to define your own compare function

var arr = ["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"];
function compare(a,b){
  var vala = a.split(',').pop();
  var valb = b.split(',').pop();
  return valb-vala;
}
arr.sort(compare);
console.log(arr);```

Body:
Suppose I have an array:

["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"]

How could I sort the array such that the last numbers in each array element are in descending order? That is:

["Team B, 7, 1, 14","Team A, 6, 2, 12","Team C, 4, 4, 8"]

I have checked out various compare functions, but I cannot figure out how to tailor them to this specific situation.


答:
Basically, all you need to do is extract that last number, then use it in your comparason:

var myArray = ["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"];

function sorter(item1, item2) {
    const split1 = item1.split(",");
    const split2 = item2.split(",");

    const num1 = split1[split1.length - 1] || 0;
    const num2 = split2[split2.length - 1] || 0;

    return num2 - num1;
}

myArray.sort(sorter)
console.log(myArray)```

Title: jQuery sort array based on number after last comma


问:
Why am I getting exceptions running a function (stored procedure) through npgsql in .Net?
I have a .Net application which talks to a Postgresql DB using Npgsql for .Net.
I have a postgresql function which I am attempting to call through Npgsql.
The function runs fine when I run it through directly in pgadmin.
However, when I run it from my .Net (C#) application, it throws an exception.

Here is "cleansed" version of the function:

```<code>CREATE OR REPLACE FUNCTION Function1(id_param integer,
                                    date1_param date,
                                    date2_param date)
RETURNS TABLE (
            field1 character varying,
            field2 character varying,
            field3 bigint)
AS $$
BEGIN

    RETURN QUERY

        SELECT table1.field1,
            table2.field2,
            table3.field3
        FROM table1
            LEFT JOIN table2 on table1.empno = table2.empno
            LEFT JOIN public.table3 on table1.docnum = table3.number
        WHERE table1.entrydate >= date1_param
            AND table2.date1 >= date1_param
            AND table2.date2 <= date2_param;
    END;
$$ LANGUAGE plpgsql;
</code>```

Here is the exception I get at runtime:

{"42P01: invalid reference to FROM-clause entry for table \"table1\""}

What is wrong with the JOIN statements in my function to cause this exception?

Thanks,
JohnB

答:
I can't say for sure what's wrong, but I can tell you my recipe for successful function calls in NpgSql and apply it to your example.

First of all, your code, as I best understand it:

```<code>NpgsqlCommand command = null;
DataTable dtResults = new DataTable();
command = new NpgsqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = functionName;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
da.Fill(dtResults);
</code>```

In PostgreSQL, there is a blurred line (in my best assessment) between a function and a stored procedure.  In order to call a function, the simplest way to do this is with a select, even if it doesn't return anything (though yours does) and then use a normal DbDataReader or DbDataAdapter.

In addition, your example above warrants parameters, none of which appeared in the C# call.

Finally, the stored procedure does not show fully qualified tables.  Is it possible it's running as a different user ID in psql as it is in the .NET application?  Either way, there is no harm in adding the schema name.

Here is what I recommend for your .NET code:

```<code>NpgsqlCommand command = new NpgsqlCommand("select * from Function1(:ID, :DATE1, :DATE2)",
    connection);
command.Parameters.Add(new NpgsqlParameter("ID", NpgsqlDbType.Integer));
command.Parameters.Add(new NpgsqlParameter("DATE1", NpgsqlDbType.Date));
command.Parameters.Add(new NpgsqlParameter("DATE2", NpgsqlDbType.Date));

command.Parameters[0].Value = id;
command.Parameters[1].Value = dt1;
command.Parameters[2].Value = dt2;

DataTable dtResults = new DataTable();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
da.Fill(dtResults);
</code>```

Again, even if you don't need them, I'd add the schema name in front of the tables and functions.

Body:
I have a .Net application which talks to a Postgresql DB using Npgsql for .Net.
I have a postgresql function which I am attempting to call through Npgsql.
The function runs fine when I run it through directly in pgadmin.
However, when I run it from my .Net (C#) application, it throws an exception.

Here is "cleansed" version of the function:

CREATE OR REPLACE FUNCTION Function1(id_param integer,
                                    date1_param date,
                                    date2_param date)
RETURNS TABLE (
            field1 character varying,
            field2 character varying,
            field3 bigint)
AS $$
BEGIN

    RETURN QUERY

        SELECT table1.field1,
            table2.field2,
            table3.field3
        FROM table1
            LEFT JOIN table2 on table1.empno = table2.empno
            LEFT JOIN public.table3 on table1.docnum = table3.number
        WHERE table1.entrydate >= date1_param
            AND table2.date1 >= date1_param
            AND table2.date2 <= date2_param;
    END;
$$ LANGUAGE plpgsql;

Here is the exception I get at runtime:

{"42P01: invalid reference to FROM-clause entry for table \"table1\""}

What is wrong with the JOIN statements in my function to cause this exception?

Thanks,
JohnB

Body:
I can't say for sure what's wrong, but I can tell you my recipe for successful function calls in NpgSql and apply it to your example.

First of all, your code, as I best understand it:

NpgsqlCommand command = null;
DataTable dtResults = new DataTable();
command = new NpgsqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = functionName;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
da.Fill(dtResults);

In PostgreSQL, there is a blurred line (in my best assessment) between a function and a stored procedure.  In order to call a function, the simplest way to do this is with a select, even if it doesn't return anything (though yours does) and then use a normal DbDataReader or DbDataAdapter.

In addition, your example above warrants parameters, none of which appeared in the C# call.

Finally, the stored procedure does not show fully qualified tables.  Is it possible it's running as a different user ID in psql as it is in the .NET application?  Either way, there is no harm in adding the schema name.

Here is what I recommend for your .NET code:

NpgsqlCommand command = new NpgsqlCommand("select * from Function1(:ID, :DATE1, :DATE2)",
    connection);
command.Parameters.Add(new NpgsqlParameter("ID", NpgsqlDbType.Integer));
command.Parameters.Add(new NpgsqlParameter("DATE1", NpgsqlDbType.Date));
command.Parameters.Add(new NpgsqlParameter("DATE2", NpgsqlDbType.Date));

command.Parameters[0].Value = id;
command.Parameters[1].Value = dt1;
command.Parameters[2].Value = dt2;

DataTable dtResults = new DataTable();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
da.Fill(dtResults);

Again, even if you don't need them, I'd add the schema name in front of the tables and functions.


问:
Article within the image
I would like to have something along the lines of (the bordered thing is a a picture and text has inverse coloring so that it is easy to read)

Mind you the image is a simple div tag that is going to live in

```<code>    <div class = "row">
        <div class = "col-md-6">
            <h3>Title</h3>
            <p>
                Short and nice paragraph
            </p>
        </div>
    </div>
</code>```

However I do not know a first thing of where to start from. I tried reading bootstrap tutorials and they didn't provide much. I understand that I haven't provided any piece of code to show my work, but I honestly do not even know where to start, or what to search for or what to do. So I am not really asking  for a full solution or anything, but if you could point me in right direction I will be ever so grateful

答:
here you go

.col-md-6{
width:50%;
}

.image{
position:relative;
}

.image img{
width: 300px;
}

.text{
position:absolute;
top: 50%;
left: 0;
padding: 0 25px;
background: rgba(255,255,255,.6);
}

.text h3, .text p{
color:#f63;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
    <div class="col-md-6">
        <div class="image">
            <div class="text"><h3>Title</h3>
            <p>
                Short and nice paragraph
            </p>
            </div>
            <img src="https://i.pinimg.com/736x/51/d6/e3/51d6e3dcccd3bdac300202a5a3e99de0--pretty-cats-beautiful-cats.jpg">
            </div>
    </div>
</div></code>```

Title: Article within the image

Body:
I would like to have something along the lines of (the bordered thing is a a picture and text has inverse coloring so that it is easy to read)

Mind you the image is a simple div tag that is going to live in

Title

                Short and nice paragraph

However I do not know a first thing of where to start from. I tried reading bootstrap tutorials and they didn't provide much. I understand that I haven't provided any piece of code to show my work, but I honestly do not even know where to start, or what to search for or what to do. So I am not really asking  for a full solution or anything, but if you could point me in right direction I will be ever so grateful

Body:
here you go

.col-md-6{
width:50%;
}

.image{
position:relative;
}

.image img{
width: 300px;
}

.text{
position:absolute;
top: 50%;
left: 0;
padding: 0 25px;
background: rgba(255,255,255,.6);
}

.text h3, .text p{
color:#f63;
}

<div class="row">
    <div class="col-md-6">
        <div class="image">
            <div class="text"><h3>Title</h3>
            <p>
                Short and nice paragraph
            </p>
            </div>
            <img src="https://i.pinimg.com/736x/51/d6/e3/51d6e3dcccd3bdac300202a5a3e99de0--pretty-cats-beautiful-cats.jpg">
            </div>
    </div>
</div>


问:
How does pluck hook work in feathersjs
In the feathersjs docs the explanation provided is as follows:

pluck discards all fields except for the specified ones, either from
  the data submitted or from the result. If the data is an array or a
  paginated find result the hook will remove the field(s) for every
  item.

```<code>import _pluck from '../common/_pluck';
import checkContextIf from './check-context-if';
import getItems from './get-items';
import replaceItems from './replace-items';

export default function (...fieldNames) {
  return context => {
    checkContextIf(context, 'before', ['create', 'update', 'patch'], 'pluck');
    if(context.params.provider) {
      replaceItems(context, _pluck(getItems(context), fieldNames));
    }

    return context;
  };
}
</code>```

The getItems utility returns the items in either hook.data or
  hook.result depending on whether the hook is being used as a before or
  after hook. hook.result.data or hook.result is returned for a find
  method.

The returned items are always an array to simplify further processing.

The replaceItems utility is the reverse of getItems , returning the
  items where they came from.

My question relates to the checkContextIf function. This function prevents the pluck hook from being called except before the create,update and patch methods. How then does the pluck hook work on the results of the query. Are not the results produced after the service call and handled in an after hook?

答:
As the documentation states:

The getItems utility returns the items in either hook.data or hook.result depending on whether the hook is being used as a before or after hook.

hook.data is the data (body) sent with a create, patch or update request so it can be used to omit fields that you do not want to be saved to the database. This is also documented in the hooks API:

data - The request data (for create, update and patch)

Title: How does pluck hook work in feathersjs

Body:
In the feathersjs docs the explanation provided is as follows:

pluck discards all fields except for the specified ones, either from
  the data submitted or from the result. If the data is an array or a
  paginated find result the hook will remove the field(s) for every
  item.

import _pluck from '../common/_pluck';
import checkContextIf from './check-context-if';
import getItems from './get-items';
import replaceItems from './replace-items';

export default function (...fieldNames) {
  return context => {
    checkContextIf(context, 'before', ['create', 'update', 'patch'], 'pluck');
    if(context.params.provider) {
      replaceItems(context, _pluck(getItems(context), fieldNames));
    }

    return context;
  };
}

The getItems utility returns the items in either hook.data or
  hook.result depending on whether the hook is being used as a before or
  after hook. hook.result.data or hook.result is returned for a find
  method.

The returned items are always an array to simplify further processing.

The replaceItems utility is the reverse of getItems , returning the
  items where they came from.

My question relates to the checkContextIf function. This function prevents the pluck hook from being called except before the create,update and patch methods. How then does the pluck hook work on the results of the query. Are not the results produced after the service call and handled in an after hook?


问:
ORA-28001: The password has expired
I'm facing the problem about my database in Oracle, When I opened my database, it appear a message with: "ORA-28001: The password has expired"

I have updated my account with somes:

```<code>sqlplus /nolog
SQL> connect / as SYSDBA
Connected.

SQL> SELECT username, account_status FROM dba_users WHERE ACCOUNT_STATUS LIKE '%EXPIRED%';

SQL> ALTER USER system IDENTIFIED BY system;
User altered.

SQL> ALTER USER system ACCOUNT UNLOCK;
User altered.

SQL> ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
Profile altered.

SQL> exit
</code>```

I check and see that, my account: 'system' has OPEN, but I open it on Oracle SQL Developer, it still have alert:

```<code>ORA-28001: The password has expired
</code>```

I have refered very much links but it still same the problem, how to fix this?

答:
```<code>ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
alter user EPUSR100 identified by EPUSR100 account unlock;
commit;
</code>```

Title: ORA-28001: The password has expired

Body:
I'm facing the problem about my database in Oracle, When I opened my database, it appear a message with: "ORA-28001: The password has expired"

I have updated my account with somes:

sqlplus /nolog
SQL> connect / as SYSDBA
Connected.

SQL> SELECT username, account_status FROM dba_users WHERE ACCOUNT_STATUS LIKE '%EXPIRED%';

SQL> ALTER USER system IDENTIFIED BY system;
User altered.

SQL> ALTER USER system ACCOUNT UNLOCK;
User altered.

SQL> ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
Profile altered.

SQL> exit

I check and see that, my account: 'system' has OPEN, but I open it on Oracle SQL Developer, it still have alert:

ORA-28001: The password has expired

I have refered very much links but it still same the problem, how to fix this?


问:
How to extract one or several characters from a Chinese font?
I want to use @font-face to import a chinese font into my site. But as we all know chinese fonts are always large.
Since i will only use no more than ten chinese characters one time, i wonder how can i extract several characters from a chinese font?

Tks~

答:
Other than online uploading solutions, there are also offline editors like Fontforge that can do the same task.

For instance you can look at this guide for Fontforge which do the same task.

The main reason why this could be preferrable over online solutions are that, other than more customizable subsettings, there are also no file size restrictions in doing the extraction process locally. It is rather common for Chinese fonts especially for those with large collection of glyphs.


问:
CSV not importing to django models
I'm trying to create a django web app that uses data from CSV's. I've created a django model to house the data from these csv's, I've stored all the csv's in STATIC_ROOT. When I load the page, the called template (datalandingpage.html) loads with no problem. However, when I check django admin, none of the CSVs have been imported. If I were to guess, I think the shortcoming has something to do with django not being able to find the files (though I'm just guessing, I could very well be wrong since I'm a relatively new developer). Below is all the relevant code I've written as an attempt.

Edit: So it looks like my view function may be skipping straight to the render part, which may be why I don't see any errors when it runs. Any ideas as to why this may be the case?

settings.py:

```<code># Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/data')
</code>```

models.py:

```<code>from __future__ import unicode_literals
from django.db import models
from django.contrib import admin

class Data(models.Model):
     # A bunch of model objects (CharField/IntegerFields mainly)

    class Meta:
        verbose_name_plural = 'Data Sets'

    def __str__(self):
        return self.someobject
</code>```

views.py:

```<code>from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from .models import Data
import csv
import os

def landing(request):

# Opens all csv files in specified directory
directory = os.path.join(settings.STATIC_ROOT)
for files in os.walk(directory):
    for file in files:
        if file.endswith(".csv"):
            f = open(file, 'r')
            reader = csv.reader(f)

            #Checks the rows/columns and tries to find the specified string that marks the start of data
            for i, row in enumerate(reader):
                target_string = "Some string in the CSV"
                if target_string in row:
                    target_row = i
                    return target_row
                    break

            #Checks the rows/columns and tries to find the specified string that marks the end of data
            for j, row in enumerate(reader):
                end_target_string = "Another string in the CSV"
                if end_target_string in row:
                    end_target_row = j
                    return end_target_row
                    break

            #Begins parsing the csv, but skips until two rows past the target beginning string
            for k, row in enumerate(reader):

                #imports csv data when the row number is between target string and target end string
                if k >= (target_row + 2):
                    row = row.split(',')
                    DataSource = Data.objects.create()
                    DataSource.someobject1 = row[0]
                    DataSource.someobject2 = row[1]
                    DataSource.save()

                # When the parse gets to the row with the end string, it closes the file.
                elif k >= end_target_row:
                    reader.close()
                    break

        # Prints something if the file isn't a csv file
        else:
            print "This isn't a csv file"

return render(request, "Data/datalandingpage.html")
</code>```

答: If I understand correctly, you want to create a list of model from a CSV file. You might consider using an existing library for this: http://django-import-export.readthedocs.io/en/stable/index.html</p>

Title: CSV not importing to django models

Body:
I'm trying to create a django web app that uses data from CSV's. I've created a django model to house the data from these csv's, I've stored all the csv's in STATIC_ROOT. When I load the page, the called template (datalandingpage.html) loads with no problem. However, when I check django admin, none of the CSVs have been imported. If I were to guess, I think the shortcoming has something to do with django not being able to find the files (though I'm just guessing, I could very well be wrong since I'm a relatively new developer). Below is all the relevant code I've written as an attempt.

Edit: So it looks like my view function may be skipping straight to the render part, which may be why I don't see any errors when it runs. Any ideas as to why this may be the case?

settings.py:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/data')

models.py:

from __future__ import unicode_literals
from django.db import models
from django.contrib import admin

class Data(models.Model):
     # A bunch of model objects (CharField/IntegerFields mainly)

    class Meta:
        verbose_name_plural = 'Data Sets'

    def __str__(self):
        return self.someobject

views.py:

from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from .models import Data
import csv
import os

def landing(request):

# Opens all csv files in specified directory
directory = os.path.join(settings.STATIC_ROOT)
for files in os.walk(directory):
    for file in files:
        if file.endswith(".csv"):
            f = open(file, 'r')
            reader = csv.reader(f)

            #Checks the rows/columns and tries to find the specified string that marks the start of data
            for i, row in enumerate(reader):
                target_string = "Some string in the CSV"
                if target_string in row:
                    target_row = i
                    return target_row
                    break

            #Checks the rows/columns and tries to find the specified string that marks the end of data
            for j, row in enumerate(reader):
                end_target_string = "Another string in the CSV"
                if end_target_string in row:
                    end_target_row = j
                    return end_target_row
                    break

            #Begins parsing the csv, but skips until two rows past the target beginning string
            for k, row in enumerate(reader):

                #imports csv data when the row number is between target string and target end string
                if k >= (target_row + 2):
                    row = row.split(',')
                    DataSource = Data.objects.create()
                    DataSource.someobject1 = row[0]
                    DataSource.someobject2 = row[1]
                    DataSource.save()

                # When the parse gets to the row with the end string, it closes the file.
                elif k >= end_target_row:
                    reader.close()
                    break

        # Prints something if the file isn't a csv file
        else:
            print "This isn't a csv file"

return render(request, "Data/datalandingpage.html")


答:
Use a regex to get last digits in each string in Array#sort()

let reg = /\d+$/;

let arr = ["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"];
arr.sort((a, b) => reg.exec(b) - reg.exec(a));

console.log(arr)```