问:
Networkx: Find all minimal cuts consisting of only nodes from one set in a bipartite graph
In the networkx python package, is there a way to find all node cuts of minimal size consisting of only nodes from one set in a bipartite graph? For example, if the two sides of a bipartite graph are A and B, how might I go about finding all minimal node cuts consisting of nodes entirely from set B? The following code I have works but it's extremely slow:

```<code>def get_one_sided_cuts(G, A, B):
    #get all cuts that consist of nodes exclusively from B which disconnect
    #nodes from A
    one_sided_cuts = []
    seen = []

    l = list(combinations(A, 2))

    for x in l:
        s = x[0]
        t = x[1]

        cut = connectivity.minimum_st_node_cut(G, s, t)
        if set(cut).issubset(B) and (cut not in seen):
            one_sided_cuts.append(cut)
        seen.append(cut)

    #find minimum cut size
    cur_min = float("inf")
    for i in one_sided_cuts:
        if len(i) < cur_min:
            cur_min = len(i)

    one_sided_cuts = [x for x in one_sided_cuts if len(x) == cur_min]

    return one_sided_cuts
</code>```

Note that this actually only checks if there is a minimal cut which, if removed, would disconnect two nodes in A only. If your solution does this (instead of finding a cut that will separate any two nodes) that's fine too. Any ideas on how to do this more efficiently?

答:
As stated in the comment, there are a couple of interpretations of “all node cuts of minimal size consisting of only nodes from one set in a bipartite graph”. It either means

All node cuts of minimum size when restricting cuts to be in one set of the bipartite graph, or

All node cuts in an unconstrained sense (consisting of nodes from A or B) that happen to completely lie in B.

From your code example you are interested in 2. According to the docs, there is a way to speed up this calculation, and from profile results it helps a bit. There are auxiliary structures built, per graph, to determine the minimum node cuts. Each node is replaced by 2 nodes, additional directed edges are added, etc. according to the Algorithm 9 in   http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
We can reuse these structures instead of reconstructing them inside a tight loop:

Improvement for Case 2:

```<code>from networkx.algorithms.connectivity import (
    build_auxiliary_node_connectivity)
from networkx.algorithms.flow import build_residual_network

from networkx.algorithms.flow import edmonds_karp

def getone_sided_cuts_Case2(G, A, B):
    # build auxiliary networks
    H = build_auxiliary_node_connectivity(G)
    R = build_residual_network(H, 'capacity')

    # get all cutes that consist of nodes exclusively from B which disconnet
    # nodes from A
    one_sided_cuts = []
    seen           = []

    l = list(combinations(A,2))

    for x in l:
        s = x[0]
        t = x[1]

    cut = minimum_st_node_cut(G, s, t, auxiliary=H, residual=R)
    if set(cut).issubset(B):
        if cut not in seen:
            one_sided_cuts.append(cut)
    seen.append(cut)

    # Find minimum cut size
    cur_min = float('inf')
    for i in one_sided_cuts:
        if len(i) < cur_min:
            curr_min = len(i)

    one_sided_cuts = [x for x in one_sided_cuts if len(x) == cur_min]

    return one_sided_cuts
</code>```

For profiling purposes, you might use the following, or one of the built-in bipartite graph generators in Networkx:

```<code>def create_bipartite_graph(size_m, size_n, num_edges):
    G = nx.Graph()

    edge_list_0 = list(range(size_m))
    edge_list_1 = list(range(size_m,size_m+size_n))
    all_edges = []

    G.add_nodes_from(edge_list_0, bipartite=0)
    G.add_nodes_from(edge_list_1, bipartite=1)

    all_edges = list(product(edge_list_0, edge_list_1))
    num_all_edges = len(all_edges)

    edges = [all_edges[i] for i in random.sample(range(num_all_edges), num_edges)]
    G.add_edges_from(edges)

    return G, edge_list_0, edge_list_1
</code>```

Using %timeit, the second version runs about 5-10% faster.

For Case 1, the logic is a little more involved. We need to consider minimal cuts from nodes only inside B. This requires a change to minimum_st_node_cut in the following way. Then replace all occurences of minimum_st_node_cut to rest_minimum_st_node_cut in your solution or the Case 2 solution I gave above, noting that the new function also requires specification of the sets A, B, necessarily:

```<code>def rest_build_auxiliary_node_connectivity(G,A,B):
    directed = G.is_directed()

    H = nx.DiGraph()

    for node in A:
        H.add_node('%sA' % node, id=node)
        H.add_node('%sB' % node, id=node)
        H.add_edge('%sA' % node, '%sB' % node, capacity=1)

    for node in B:
        H.add_node('%sA' % node, id=node)
        H.add_node('%sB' % node, id=node)
        H.add_edge('%sA' % node, '%sB' % node, capacity=1)

    edges = []
    for (source, target) in G.edges():
        edges.append(('%sB' % source, '%sA' % target))
        if not directed:
            edges.append(('%sB' % target, '%sA' % source))
    H.add_edges_from(edges, capacity=1)

    return H

def rest_minimum_st_node_cut(G, A, B, s, t, auxiliary=None, residual=None, flow_func=edmonds_karp):

    if auxiliary is None:
        H = rest_build_auxiliary_node_connectivity(G, A, B)
    else:
        H = auxiliary

    if G.has_edge(s,t) or G.has_edge(t,s):
        return []
    kwargs = dict(flow_func=flow_func, residual=residual, auxiliary=H)

    for node in [x for x in A if x not in [s,t]]:
        edge = ('%sA' % node, '%sB' % node)
        num_in_edges = len(H.in_edges(edge[0]))
        H[edge[0]][edge[1]]['capacity'] = num_in_edges

    edge_cut = minimum_st_edge_cut(H, '%sB' % s, '%sA' % t,**kwargs)

    node_cut = set([n for n in [H.nodes[node]['id'] for edge in edge_cut for node in edge] if n not in A])

    return node_cut - set([s,t])
</code>```

We then have, for example:

```<code>In [1]: G = nx.Graph()
        # A = [0,1,2,3], B = [4,5,6,7]
In [2]: G.add_edges_from([(0,4),(0,5),(1,6),(1,7),(4,1),(5,1),(6,3),(7,3)])
In [3]: minimum_st_node_cut(G, 0, 3)
           {1}
In [4]: rest_minimum_st_node_cut(G,A,B,0,3)
           {6, 7}
</code>```

Finally note that the minimum_st_edge_cut() function returns [] if two nodes are adjacent. Sometimes the convention is to return a set of n-1 nodes in this case, all nodes except the source or sink. Anyway, with the empty list convention, and since your original solution to Case 2 loops over node pairs in A, you will likely get [] as a return value for most configurations, unless no nodes in A are adjacent, say.

EDIT

The OP encountered a problem with bipartite graphs for which the sets A, B contained a mix of integers and str types. It looks to me like the build_auxiliary_node_connectivity converts those str nodes to integers causing collisions. I rewrote things above, I think that takes care of it. I don't see anything in the networkx docs about this, so either use all integer nodes or use the rest_build_auxiliary_node_connectivity() thing above.

Body:
In the networkx python package, is there a way to find all node cuts of minimal size consisting of only nodes from one set in a bipartite graph? For example, if the two sides of a bipartite graph are A and B, how might I go about finding all minimal node cuts consisting of nodes entirely from set B? The following code I have works but it's extremely slow:

def get_one_sided_cuts(G, A, B):
    #get all cuts that consist of nodes exclusively from B which disconnect
    #nodes from A
    one_sided_cuts = []
    seen = []

    l = list(combinations(A, 2))

    for x in l:
        s = x[0]
        t = x[1]

        cut = connectivity.minimum_st_node_cut(G, s, t)
        if set(cut).issubset(B) and (cut not in seen):
            one_sided_cuts.append(cut)
        seen.append(cut)

    #find minimum cut size
    cur_min = float("inf")
    for i in one_sided_cuts:
        if len(i) < cur_min:
            cur_min = len(i)

    one_sided_cuts = [x for x in one_sided_cuts if len(x) == cur_min]

    return one_sided_cuts

Note that this actually only checks if there is a minimal cut which, if removed, would disconnect two nodes in A only. If your solution does this (instead of finding a cut that will separate any two nodes) that's fine too. Any ideas on how to do this more efficiently?

Body:
As stated in the comment, there are a couple of interpretations of “all node cuts of minimal size consisting of only nodes from one set in a bipartite graph”. It either means

All node cuts of minimum size when restricting cuts to be in one set of the bipartite graph, or

All node cuts in an unconstrained sense (consisting of nodes from A or B) that happen to completely lie in B.

From your code example you are interested in 2. According to the docs, there is a way to speed up this calculation, and from profile results it helps a bit. There are auxiliary structures built, per graph, to determine the minimum node cuts. Each node is replaced by 2 nodes, additional directed edges are added, etc. according to the Algorithm 9 in   http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
We can reuse these structures instead of reconstructing them inside a tight loop:

Improvement for Case 2:

from networkx.algorithms.connectivity import (
    build_auxiliary_node_connectivity)
from networkx.algorithms.flow import build_residual_network

from networkx.algorithms.flow import edmonds_karp

def getone_sided_cuts_Case2(G, A, B):
    # build auxiliary networks
    H = build_auxiliary_node_connectivity(G)
    R = build_residual_network(H, 'capacity')

    # get all cutes that consist of nodes exclusively from B which disconnet
    # nodes from A
    one_sided_cuts = []
    seen           = []

    l = list(combinations(A,2))

    for x in l:
        s = x[0]
        t = x[1]

    cut = minimum_st_node_cut(G, s, t, auxiliary=H, residual=R)
    if set(cut).issubset(B):
        if cut not in seen:
            one_sided_cuts.append(cut)
    seen.append(cut)

    # Find minimum cut size
    cur_min = float('inf')
    for i in one_sided_cuts:
        if len(i) < cur_min:
            curr_min = len(i)

    one_sided_cuts = [x for x in one_sided_cuts if len(x) == cur_min]

    return one_sided_cuts

For profiling purposes, you might use the following, or one of the built-in bipartite graph generators in Networkx:

def create_bipartite_graph(size_m, size_n, num_edges):
    G = nx.Graph()

    edge_list_0 = list(range(size_m))
    edge_list_1 = list(range(size_m,size_m+size_n))
    all_edges = []

    G.add_nodes_from(edge_list_0, bipartite=0)
    G.add_nodes_from(edge_list_1, bipartite=1)

    all_edges = list(product(edge_list_0, edge_list_1))
    num_all_edges = len(all_edges)

    edges = [all_edges[i] for i in random.sample(range(num_all_edges), num_edges)]
    G.add_edges_from(edges)

    return G, edge_list_0, edge_list_1

Using %timeit, the second version runs about 5-10% faster.

For Case 1, the logic is a little more involved. We need to consider minimal cuts from nodes only inside B. This requires a change to minimum_st_node_cut in the following way. Then replace all occurences of minimum_st_node_cut to rest_minimum_st_node_cut in your solution or the Case 2 solution I gave above, noting that the new function also requires specification of the sets A, B, necessarily:

def rest_build_auxiliary_node_connectivity(G,A,B):
    directed = G.is_directed()

    H = nx.DiGraph()

    for node in A:
        H.add_node('%sA' % node, id=node)
        H.add_node('%sB' % node, id=node)
        H.add_edge('%sA' % node, '%sB' % node, capacity=1)

    for node in B:
        H.add_node('%sA' % node, id=node)
        H.add_node('%sB' % node, id=node)
        H.add_edge('%sA' % node, '%sB' % node, capacity=1)

    edges = []
    for (source, target) in G.edges():
        edges.append(('%sB' % source, '%sA' % target))
        if not directed:
            edges.append(('%sB' % target, '%sA' % source))
    H.add_edges_from(edges, capacity=1)

    return H

def rest_minimum_st_node_cut(G, A, B, s, t, auxiliary=None, residual=None, flow_func=edmonds_karp):

    if auxiliary is None:
        H = rest_build_auxiliary_node_connectivity(G, A, B)
    else:
        H = auxiliary

    if G.has_edge(s,t) or G.has_edge(t,s):
        return []
    kwargs = dict(flow_func=flow_func, residual=residual, auxiliary=H)

    for node in [x for x in A if x not in [s,t]]:
        edge = ('%sA' % node, '%sB' % node)
        num_in_edges = len(H.in_edges(edge[0]))
        H[edge[0]][edge[1]]['capacity'] = num_in_edges

    edge_cut = minimum_st_edge_cut(H, '%sB' % s, '%sA' % t,**kwargs)

    node_cut = set([n for n in [H.nodes[node]['id'] for edge in edge_cut for node in edge] if n not in A])

    return node_cut - set([s,t])

We then have, for example:

In [1]: G = nx.Graph()
        # A = [0,1,2,3], B = [4,5,6,7]
In [2]: G.add_edges_from([(0,4),(0,5),(1,6),(1,7),(4,1),(5,1),(6,3),(7,3)])
In [3]: minimum_st_node_cut(G, 0, 3)
           {1}
In [4]: rest_minimum_st_node_cut(G,A,B,0,3)
           {6, 7}

Finally note that the minimum_st_edge_cut() function returns [] if two nodes are adjacent. Sometimes the convention is to return a set of n-1 nodes in this case, all nodes except the source or sink. Anyway, with the empty list convention, and since your original solution to Case 2 loops over node pairs in A, you will likely get [] as a return value for most configurations, unless no nodes in A are adjacent, say.

EDIT

The OP encountered a problem with bipartite graphs for which the sets A, B contained a mix of integers and str types. It looks to me like the build_auxiliary_node_connectivity converts those str nodes to integers causing collisions. I rewrote things above, I think that takes care of it. I don't see anything in the networkx docs about this, so either use all integer nodes or use the rest_build_auxiliary_node_connectivity() thing above.


来源: stackexchange

问:
RecyclerView CardLayout images getting smaller in size after each refresh
I'm using RecyclerView and CardLayout on a TabLayout with 5 tabs, each represented as a fragment. Whenever I click on a tab, i first check if the fragment is visible. If true, I execute my UI code which involves invoking a REST service to fetch data from a db which is then populated to the RecyclerView by a custom adapter. I temporarily cache the data in an ArrayList so that frequent attempts to the fragment wont need another REST request. My problem is whenever I navigate to a certain tab more than once, the layout gets smaller and smaller after each attempt. Below are my Fragment, Adapter and Adapter Layout.</p>

```<code>public class BeerFragment extends Fragment {
    private RecyclerView recyclerView;
    ProgressDialog pd;
    private View rootView;
    private static final String TAG = BeerFragment.class.getSimpleName();
    public static boolean isLoadedBeer = false;
    public boolean instantiated = false;
    public BeerFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        rootView  = inflater.inflate(R.layout.activity_main2, container, false);
        initViews();
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && MaintainState.isLoadedBeer) {
            initViews();
        } else if (isVisibleToUser && !MaintainState.isLoadedBeer) {
        } else if (!isVisibleToUser && MaintainState.isLoadedBeer){
        } else if (!isVisibleToUser && !MaintainState.isLoadedBeer){
            MaintainState.isLoadedBeer = true;
        }
    }

    private void initViews(){
        pd = new ProgressDialog(getActivity());
        pd.setMessage("Fetching Beer...");
        pd.setCancelable(false);
        pd.show();
        Log.d("snopww4","noppww");
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }

        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        ArrayList albumList = new ArrayList<>();
        GalleryAdapter  adapter = new GalleryAdapter(getActivity(), albumList,2);
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, GridSpacingItemDecoration.dpToPx(getActivity(), 10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        if (!isLoadedBeer) {
            Log.d("lklk","lklk");
        String drink = FilterFragment.sorted;
        if (drink.equals("empty")){
            loadBeer("beer");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("lager")){
            loadBeer("lager");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("stout")){
            loadBeer("stout");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("malt")){
            loadBeer("malt");
            FilterFragment.sorted = "empty";
        } else {
            pd.hide();
        }
    } else {
        recyclerView.setAdapter(new GalleryAdapter(getActivity(), MaintainState.getItemsBeer(), 1));
        recyclerView.smoothScrollToPosition(0);
        pd.hide();
    }
    }

    private void loadBeer(final String item){
        try{
            Client Client = new Client();
            Service apiService = Client.getClient().create(Service.class);
            Call<GalleryResponse> call = apiService.getBeer(item);
            call.enqueue(new Callback<GalleryResponse>() {
                @Override
                public void onResponse(Call<GalleryResponse> call, Response<GalleryResponse> response) {
                    List<Gallery> items = response.body().getBeer();
                    recyclerView.setAdapter(new GalleryAdapter(getActivity(), items, 2));
                    recyclerView.smoothScrollToPosition(0);
                    MaintainState.setItemsBeer(items);
                    isLoadedBeer = true;
                    pd.hide();
                }

                @Override
                public void onFailure(Call<GalleryResponse> call, Throwable t) {
                    pd.hide();

                }
            });
        }catch (Exception e){
        }
    }
}

public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {

    private Context mContext;
    private List<Gallery> albumList;
    private int tabPosition;
    private LocalStore localStore;
    private static final String TAG = GalleryAdapter.class.getSimpleName();

    public GalleryAdapter(Context mContext, List<Gallery> albumList, int tabPosition) {
        Log.i(TAG, "INIT GalleryAdapter");
        this.mContext = mContext;
        this.albumList = albumList;
        this.tabPosition = tabPosition;
        localStore = new LocalStore(mContext);
    }

    @Override
    public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.album_card2, viewGroup, false);
        CardView cardView = (CardView) view.findViewById(R.id.card_view);
        cardView.setMaxCardElevation(GridSpacingItemDecoration.dpToPx(mContext, 10));
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final GalleryAdapter.MyViewHolder viewHolder, int i) {
        viewHolder.title.setText(albumList.get(i).getName());
        viewHolder.title.setTypeface(Display.displayTypefaceCabin(mContext, 1), Typeface.BOLD);
        viewHolder.count.setText("Ksh "+albumList.get(i).getPrice());
        viewHolder.count.setTypeface(Display.displayTypefaceWalkWay(mContext, 1), Typeface.BOLD);
        viewHolder.tag.setTypeface(Display.displayTypefaceOpenSansCondensed(mContext, 1), Typeface.BOLD);

        Glide.with(mContext).
                load(albumList.get(i).getThumbnail()).
                placeholder(R.drawable.placeholder).
                error(R.drawable.placeholder).
                fitCenter().
                into(viewHolder.thumbnail);
    }

    @Override
    public int getItemCount() {
        return albumList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, count, tag;
        public ImageView thumbnail, favourite;

        public MyViewHolder(final View view) {
            super(view);
            tag = (TextView) view.findViewById(R.id.tag);
            title = (TextView) view.findViewById(R.id.title);
            count = (TextView) view.findViewById(R.id.count);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            favourite = (ImageView) view.findViewById(R.id.favourite);

            thumbnail.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                }
            });
        }
    }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="#f2f5f7"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_marginLeft="-10dp"
        card_view:cardCornerRadius="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:background="@drawable/image_view_drop_shadow"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="3dp"
                android:paddingBottom="3dp"
                android:text="hello"
                android:textColor="@color/white"
                android:textSize="12dp"/>

            <ImageView
                android:id="@+id/favourite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="5dp"
                android:layout_alignParentRight="true"/>

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="match_parent"
                android:layout_height="220dp"
                android:clickable="true"
                android:scaleType="fitXY" />

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/thumbnail"
                android:gravity="center"
                android:textColor="#000000"
                android:paddingBottom="5dp"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/count"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/title"
                android:gravity="center"
                android:paddingBottom="15dp"
                android:textSize="14sp" />

        </RelativeLayout>

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

</LinearLayout>
</code>```

答:
Here's a wild guess.

What I think is happening is that your fragment calls initViews() multiple times, and every time it is called, you are adding a decoration that adds some sort of spacing, which makes less space for your actual views.

Very quick test, removing the below line and see if the problem goes away.

```<code> recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, GridSpacingItemDecoration.dpToPx(getActivity(), 10), true));
</code>```

If it does, debug your initView() methods to see if it's called more than you need, or maybe split the initView() method into two parts, one for one time things Decorator, Animator... etc. and another one that updates data in view.

ContentLicense: CC BY-SA 3.0

Body:
I'm using RecyclerView and CardLayout on a TabLayout with 5 tabs, each represented as a fragment. Whenever I click on a tab, i first check if the fragment is visible. If true, I execute my UI code which involves invoking a REST service to fetch data from a db which is then populated to the RecyclerView by a custom adapter. I temporarily cache the data in an ArrayList so that frequent attempts to the fragment wont need another REST request. My problem is whenever I navigate to a certain tab more than once, the layout gets smaller and smaller after each attempt. Below are my Fragment, Adapter and Adapter Layout.

public class BeerFragment extends Fragment {
    private RecyclerView recyclerView;
    ProgressDialog pd;
    private View rootView;
    private static final String TAG = BeerFragment.class.getSimpleName();
    public static boolean isLoadedBeer = false;
    public boolean instantiated = false;
    public BeerFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        rootView  = inflater.inflate(R.layout.activity_main2, container, false);
        initViews();
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && MaintainState.isLoadedBeer) {
            initViews();
        } else if (isVisibleToUser && !MaintainState.isLoadedBeer) {
        } else if (!isVisibleToUser && MaintainState.isLoadedBeer){
        } else if (!isVisibleToUser && !MaintainState.isLoadedBeer){
            MaintainState.isLoadedBeer = true;
        }
    }

    private void initViews(){
        pd = new ProgressDialog(getActivity());
        pd.setMessage("Fetching Beer...");
        pd.setCancelable(false);
        pd.show();
        Log.d("snopww4","noppww");
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }

        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        ArrayList albumList = new ArrayList<>();
        GalleryAdapter  adapter = new GalleryAdapter(getActivity(), albumList,2);
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, GridSpacingItemDecoration.dpToPx(getActivity(), 10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        if (!isLoadedBeer) {
            Log.d("lklk","lklk");
        String drink = FilterFragment.sorted;
        if (drink.equals("empty")){
            loadBeer("beer");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("lager")){
            loadBeer("lager");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("stout")){
            loadBeer("stout");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("malt")){
            loadBeer("malt");
            FilterFragment.sorted = "empty";
        } else {
            pd.hide();
        }
    } else {
        recyclerView.setAdapter(new GalleryAdapter(getActivity(), MaintainState.getItemsBeer(), 1));
        recyclerView.smoothScrollToPosition(0);
        pd.hide();
    }
    }

    private void loadBeer(final String item){
        try{
            Client Client = new Client();
            Service apiService = Client.getClient().create(Service.class);
            Call<GalleryResponse> call = apiService.getBeer(item);
            call.enqueue(new Callback<GalleryResponse>() {
                @Override
                public void onResponse(Call<GalleryResponse> call, Response<GalleryResponse> response) {
                    List<Gallery> items = response.body().getBeer();
                    recyclerView.setAdapter(new GalleryAdapter(getActivity(), items, 2));
                    recyclerView.smoothScrollToPosition(0);
                    MaintainState.setItemsBeer(items);
                    isLoadedBeer = true;
                    pd.hide();
                }

                @Override
                public void onFailure(Call<GalleryResponse> call, Throwable t) {
                    pd.hide();

                }
            });
        }catch (Exception e){
        }
    }
}

public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {

    private Context mContext;
    private List<Gallery> albumList;
    private int tabPosition;
    private LocalStore localStore;
    private static final String TAG = GalleryAdapter.class.getSimpleName();

    public GalleryAdapter(Context mContext, List<Gallery> albumList, int tabPosition) {
        Log.i(TAG, "INIT GalleryAdapter");
        this.mContext = mContext;
        this.albumList = albumList;
        this.tabPosition = tabPosition;
        localStore = new LocalStore(mContext);
    }

    @Override
    public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.album_card2, viewGroup, false);
        CardView cardView = (CardView) view.findViewById(R.id.card_view);
        cardView.setMaxCardElevation(GridSpacingItemDecoration.dpToPx(mContext, 10));
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final GalleryAdapter.MyViewHolder viewHolder, int i) {
        viewHolder.title.setText(albumList.get(i).getName());
        viewHolder.title.setTypeface(Display.displayTypefaceCabin(mContext, 1), Typeface.BOLD);
        viewHolder.count.setText("Ksh "+albumList.get(i).getPrice());
        viewHolder.count.setTypeface(Display.displayTypefaceWalkWay(mContext, 1), Typeface.BOLD);
        viewHolder.tag.setTypeface(Display.displayTypefaceOpenSansCondensed(mContext, 1), Typeface.BOLD);

        Glide.with(mContext).
                load(albumList.get(i).getThumbnail()).
                placeholder(R.drawable.placeholder).
                error(R.drawable.placeholder).
                fitCenter().
                into(viewHolder.thumbnail);
    }

    @Override
    public int getItemCount() {
        return albumList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, count, tag;
        public ImageView thumbnail, favourite;

        public MyViewHolder(final View view) {
            super(view);
            tag = (TextView) view.findViewById(R.id.tag);
            title = (TextView) view.findViewById(R.id.title);
            count = (TextView) view.findViewById(R.id.count);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            favourite = (ImageView) view.findViewById(R.id.favourite);

            thumbnail.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                }
            });
        }
    }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="#f2f5f7"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_marginLeft="-10dp"
        card_view:cardCornerRadius="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:background="@drawable/image_view_drop_shadow"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="3dp"
                android:paddingBottom="3dp"
                android:text="hello"
                android:textColor="@color/white"
                android:textSize="12dp"/>

            <ImageView
                android:id="@+id/favourite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="5dp"
                android:layout_alignParentRight="true"/>

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="match_parent"
                android:layout_height="220dp"
                android:clickable="true"
                android:scaleType="fitXY" />

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/thumbnail"
                android:gravity="center"
                android:textColor="#000000"
                android:paddingBottom="5dp"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/count"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/title"
                android:gravity="center"
                android:paddingBottom="15dp"
                android:textSize="14sp" />

        </RelativeLayout>

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

</LinearLayout>

Body:
Here's a wild guess.

What I think is happening is that your fragment calls initViews() multiple times, and every time it is called, you are adding a decoration that adds some sort of spacing, which makes less space for your actual views.

Very quick test, removing the below line and see if the problem goes away.

 recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, GridSpacingItemDecoration.dpToPx(getActivity(), 10), true));

If it does, debug your initView() methods to see if it's called more than you need, or maybe split the initView() method into two parts, one for one time things Decorator, Animator... etc. and another one that updates data in view.


问:
changed my wordpress url from http to https and now admin panel is not working
i changed the URL from HTTP to HTTP'S and the moment i did it my admin panel stopped working add the line in WP-config site URL and all but still not working
now i don't what do please help me out</p>

答:
open your functions.php in your theme directory and put the following lines in

```<code>update_option( 'siteurl', 'https://yourdomain.com' );
update_option( 'home', 'https://yourdomain.com' );
</code>```

after that - try to reload a couple of times your site
(you should remove those lines - if it was successful)

Body:
open your functions.php in your theme directory and put the following lines in

update_option( 'siteurl', 'https://yourdomain.com' );
update_option( 'home', 'https://yourdomain.com' );

after that - try to reload a couple of times your site
(you should remove those lines - if it was successful)


问:
How to make an extension for nvarchar max? Fluent nHibernate + Nhibernate
I been looking around for how to do this but I can't get it to work. I seen many tutorials that using

PropertyMap or IProperty but I can't figure out what using statement to use and VS intellisense does not know either

http://serialseb.blogspot.com/2009/01/fluent-nhibernate-and-nvarcharmax.html

I am using fluent nhibernate and nihbernate 3.0. So did they remove these?

答: It seems if I used PropertyPart that works.</p>

ContentLicense: CC BY-SA 2.5


问:
Second to the LastIndexOf C#
*  I cannot delete this duplicate question because someone has answered it *

I have file names formatted  CustomerInfoDaily.12042014.080043 and  CustomerInfoDaily.A.12042014.080043    I'm trying to get the base name (CustomerInfoDaily) and the base suffix (.12042014.080043) using substrings.  There is no limit to the number of periods however the suffix is always .\d{8}.\d{8}

```<code>string fn = "CustomerInfoDaily.A.12042014.080043";
string baseFileName = fn.Substring(0, fn.LastIndexOf(".",fn.Length-1,fn.Length));
string baseSuffix = fn.Substring(fn.LastIndexOf(".", 0, 2));
</code>```

The problem is that you can say you want the first or last dot but there is no saying that you want the second to the last instance of the dot.

Any help or advice would be greatly appreciated.

答:
Consider using string.Split:

```<code>string fn = "CustomerInfoDaily.A.12042014.080043";

var split = fn.Split('.');
var last = split.LastOrDefault();
var secondLast = split.Skip(split.Length - 2).FirstOrDefault();
</code>```

Title: Second to the LastIndexOf C#

Body:
*  I cannot delete this duplicate question because someone has answered it *

I have file names formatted  CustomerInfoDaily.12042014.080043 and  CustomerInfoDaily.A.12042014.080043    I'm trying to get the base name (CustomerInfoDaily) and the base suffix (.12042014.080043) using substrings.  There is no limit to the number of periods however the suffix is always .\d{8}.\d{8}

string fn = "CustomerInfoDaily.A.12042014.080043";
string baseFileName = fn.Substring(0, fn.LastIndexOf(".",fn.Length-1,fn.Length));
string baseSuffix = fn.Substring(fn.LastIndexOf(".", 0, 2));

The problem is that you can say you want the first or last dot but there is no saying that you want the second to the last instance of the dot.

Any help or advice would be greatly appreciated.

Body:
Consider using string.Split:

string fn = "CustomerInfoDaily.A.12042014.080043";

var split = fn.Split('.');
var last = split.LastOrDefault();
var secondLast = split.Skip(split.Length - 2).FirstOrDefault();


问:
Symfony generate cdn friendly asset url
I have a symfony application that gets served by a cdn (eg. akamai) and I generate the asset url on the templates with:

```<code>{{ asset('myJs.js') }}
</code>```

When I do I want to generate a url like (supposing that the site is served by www.example.com) :

www.example.com/myJs.js?v=321321312312

Where the v parameter get a deployed version in order to force cdn (eg. akamai network) to cache me newer version. Is it a good way to dynamically generate the v parameter?

答: If you want to append a hash to the file that is kept unique per version, you could either use the file modification time of that file or a hash. The best way could be to create a new Twig function versionedAsset() that uses the output of asset() and appends this hash to the generated URL</p>

Title: Symfony generate cdn friendly asset url

Body:
I have a symfony application that gets served by a cdn (eg. akamai) and I generate the asset url on the templates with:

{{ asset('myJs.js') }}

When I do I want to generate a url like (supposing that the site is served by www.example.com) :

www.example.com/myJs.js?v=321321312312

Where the v parameter get a deployed version in order to force cdn (eg. akamai network) to cache me newer version. Is it a good way to dynamically generate the v parameter?


问:
Uncaught Error: [$injector:modulerr] while using external js file
Uncaught Error: [$injector:modulerr] this is the error I'm getting only when I'm using an external js file for my code otherwise if I just copy the angular code in the html/php file it just works.

index.php

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">

    <script src="angular.min.js"></script>
    <script src="app.js"></script>
    <title>Learn</title>
</head>
<body ng-app="myApp">
    <div class="container" ng-controller="myCtrl" >

    </div>
</body>
</html>
</code>```

app.js

```<code>(function(){
    var app = angular.module('myApp', ["ngRoute"]);

    app.controller('myCtrl', function($scope){

    });

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

Error :

```<code>angular.min.js:sourcemap:7 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.6/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.6%2F%24injector%2Fmodulerr%3Fp0%3DngRoute%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.6.6%252F%2524injector%252Fnomod%253Fp0%253DngRoute%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A7%253A76%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A26%253A408%250A%2520%2520%2520%2520at%2520b%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A25%253A439)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A26%253A182%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A290%250A%2520%2520%2520%2520at%2520p%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A138)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A322%250A%2520%2520%2520%2520at%2520p%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A138)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A43%3A70%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A322%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20hb%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A46%3A250)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A22%3A332)
    at angular.min.js:sourcemap:7
    at angular.min.js:sourcemap:43
    at p (angular.min.js:sourcemap:8)
    at g (angular.min.js:sourcemap:42)
    at hb (angular.min.js:sourcemap:46)
    at c (angular.min.js:sourcemap:22)
    at Uc (angular.min.js:sourcemap:22)
    at we (angular.min.js:sourcemap:21)
    at angular.min.js:sourcemap:334
    at HTMLDocument.b (angular.min.js:sourcemap:38)
</code>```

答:
you must add script for "ng-route".and is better to move script tag end of body tag .

```<code>   <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">

        <link rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-
      beta.2/css/bootstrap.min.css" integrity="sha384-
      PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"
       crossorigin="anonymous">
        <link rel="stylesheet" href="style.css">

        <title>Learn</title>
    </head>
    <body ng-app="myApp">
        <div class="container" ng-controller="myCtrl" >

        </div>

        <script src="angular.min.js"></script>
       <script
       src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
       route.js"></script>
        <script src="app.js"></script>
     </body>
     </html>
</code>```

and no need to fonction({}) in app.js

var app = angular.module('myApp', ["ngRoute"]);

```<code>app.controller('myCtrl', function($scope){

});
</code>```

Body:
Uncaught Error: [$injector:modulerr] this is the error I'm getting only when I'm using an external js file for my code otherwise if I just copy the angular code in the html/php file it just works.

index.php

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">

    <title>Learn</title>

app.js

(function(){
    var app = angular.module('myApp', ["ngRoute"]);

    app.controller('myCtrl', function($scope){

    });

})();

Error :

angular.min.js:sourcemap:7 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.6/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.6%2F%24injector%2Fmodulerr%3Fp0%3DngRoute%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.6.6%252F%2524injector%252Fnomod%253Fp0%253DngRoute%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A7%253A76%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A26%253A408%250A%2520%2520%2520%2520at%2520b%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A25%253A439)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A26%253A182%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A290%250A%2520%2520%2520%2520at%2520p%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A138)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A322%250A%2520%2520%2520%2520at%2520p%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A138)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A43%3A70%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A322%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20hb%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A46%3A250)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A22%3A332)
    at angular.min.js:sourcemap:7
    at angular.min.js:sourcemap:43
    at p (angular.min.js:sourcemap:8)
    at g (angular.min.js:sourcemap:42)
    at hb (angular.min.js:sourcemap:46)
    at c (angular.min.js:sourcemap:22)
    at Uc (angular.min.js:sourcemap:22)
    at we (angular.min.js:sourcemap:21)
    at angular.min.js:sourcemap:334
    at HTMLDocument.b (angular.min.js:sourcemap:38)

Body:
you must add script for "ng-route".and is better to move script tag end of body tag .

   <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">

        <link rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-
      beta.2/css/bootstrap.min.css" integrity="sha384-
      PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"
       crossorigin="anonymous">
        <link rel="stylesheet" href="style.css">

        <title>Learn</title>
    </head>
    <body ng-app="myApp">
        <div class="container" ng-controller="myCtrl" >

        </div>

        <script src="angular.min.js"></script>
       <script
       src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
       route.js"></script>
        <script src="app.js"></script>
     </body>
     </html>

and no need to fonction({}) in app.js

var app = angular.module('myApp', ["ngRoute"]);

app.controller('myCtrl', function($scope){

});


问:
Execute task on specific time in Django
I have to execute a task at a specific time, which is specified by the user.
This will not be fix time...
It will be according to user...

On that time I have to execute my task...

To achieve this I tried to use django-cron also tried to use django-crontab...

But in both case either we have to specify cron details in settings.py or we've to execute runcron commands.

I also checked django-celery (I don't have any idea about celery much. I  may be wrong).

In celery we have to specify time while defining task...

Can any one help me how can I do this...

I am using django as a backend...

答:
To execute a task at specified date and time you can use eta attribute of apply_async while calling task as mentioned in docs(http://docs.celeryproject.org/en/latest/userguide/calling.html#eta-and-countdown)

your_task.apply_async(kwargs={}, eta="your_send_time")

```<code>## Note: your_send_time should be of type `datetime`.
</code>```

Title: Execute task on specific time in Django

Body:
To execute a task at specified date and time you can use eta attribute of apply_async while calling task as mentioned in docs(http://docs.celeryproject.org/en/latest/userguide/calling.html#eta-and-countdown)

your_task.apply_async(kwargs={}, eta="your_send_time")

## Note: your_send_time should be of type `datetime`.


问:
Find resource by slug in nested resource in rails
I have following routes

```<code> resources :shops do
    resources :categories
  end
</code>```

And when I visit this url:

```<code>http://localhost:3000/shops/rabin-shop/categories
</code>```

I first want to find the shop by using slug 'rabin-shop', then I can filter the categories of products that belong to that shop. In my controller I have tried to implement

```<code>    def find_shop
       @shop = Shop.find(params[:slug])
    end
</code>```

But this is not working. I know this is not how to find in nested resource. I am using friendly_id gem . I cannot do something like current_user.shop because I want the page to be accessed even when the user is not logged in.

答:
If you are using the freindly_id gem, this is how you find a record by it's slug : </p>

```<code> def find_shop
   # params[:shop_id] if nested
   @shop = Shop.friendly.find(params[:id])
 end
</code>```

Body:
I have following routes

 resources :shops do
    resources :categories
  end

And when I visit this url:

http://localhost:3000/shops/rabin-shop/categories

I first want to find the shop by using slug 'rabin-shop', then I can filter the categories of products that belong to that shop. In my controller I have tried to implement

    def find_shop
       @shop = Shop.find(params[:slug])
    end

But this is not working. I know this is not how to find in nested resource. I am using friendly_id gem . I cannot do something like current_user.shop because I want the page to be accessed even when the user is not logged in.

Body:
If you are using the freindly_id gem, this is how you find a record by it's slug :

 def find_shop
   # params[:shop_id] if nested
   @shop = Shop.friendly.find(params[:id])
 end


问:
Select2 dropdown allow new values by user when user types
The select2 component can be configured to accept new values, as ask in Select2 dropdown but allow new values by user?

And you can see it at: http://jsfiddle.net/pHSdP/646/ the code is as below:

```<code>$("#tags").select2({
    createSearchChoice: function (term, data) {
        if ($(data).filter(function () {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            return {
                id: term,
                text: term
            };
        }
    },
    multiple: false,
    data: [{
        id: 0,
        text: 'story'
    }, {
        id: 1,
        text: 'bug'
    }, {
        id: 2,
        text: 'task'
    }]
});
</code>```

The problem is that the new value is only added to the list if you enter new value and press enter, or press tab.

Is it possible to set the select2 component to accept this new value when use types and leave the select2. (Just as normal html input tag which keeps the value which you are typing when you leave it by clicking some where on the screen)

I found that the select2 has select2-blur event but I don't find a way to get this new value and add it to list?!

答:
And to be able to submit multiple new choices together with the existing ones:</p>

```<code>select2({tags: true, selectOnBlur: true, multiple: true})
</code>```

Body:
The select2 component can be configured to accept new values, as ask in Select2 dropdown but allow new values by user?

And you can see it at: http://jsfiddle.net/pHSdP/646/ the code is as below:

$("#tags").select2({
    createSearchChoice: function (term, data) {
        if ($(data).filter(function () {
            return this.text.localeCompare(term) === 0;
        }).length === 0) {
            return {
                id: term,
                text: term
            };
        }
    },
    multiple: false,
    data: [{
        id: 0,
        text: 'story'
    }, {
        id: 1,
        text: 'bug'
    }, {
        id: 2,
        text: 'task'
    }]
});

The problem is that the new value is only added to the list if you enter new value and press enter, or press tab.

Is it possible to set the select2 component to accept this new value when use types and leave the select2. (Just as normal html input tag which keeps the value which you are typing when you leave it by clicking some where on the screen)

I found that the select2 has select2-blur event but I don't find a way to get this new value and add it to list?!

Body:
And to be able to submit multiple new choices together with the existing ones:

select2({tags: true, selectOnBlur: true, multiple: true})


问:
How to use ManagementEventWatcher in a windoes service?
I am trying to use ManagementEventWatcher inside a C# .NET4 windows service application. At some point in the "OnStart" method I have these lines:

```<code>string scope = "\\root\\cimv2";
string query =
  "SELECT * FROM __InstanceCreationEvent " +
  "WITHIN 1 " +
  "WHERE TargetInstance ISA 'Win32_NTLogEvent' " +
  " AND ( " +
  "      targetInstance.EventCode = '4768' " +
  "   OR targetInstance.EventCode = '4770' " +
  "   OR targetInstance.EventCode = '672'" +
  "   OR targetInstance.EventCode = '674'" +
  " )";
eventListener = new ManagementEventWatcher(scope, query);
eventListener.EventArrived += new EventArrivedEventHandler(HandleEvent);

eventListener.Start();
</code>```

The eventListener.Start(); line gives an exception with the message "Access Denied". I tried to set up my service as Administrator or LOCALSYSTEM but it does not help.

I also found this documentation: http://msdn.microsoft.com/en-us/library/aa392289(VS.85).aspx
But I can not figure out how to use it in C#.

The same code works as expected if put in a WindowsForms application.

Thanks.

答:
There is nothing inherent here that will prevent a service from providing this functionality.  I actually took your code and ran it fine on my machine as a service(famous developer last words) under the localsystem account.  If the account running lacks permissions to the event log, in your case, or anything else it needs it will bail.
A few general tips from my all-too-frequent experience with troubleshoooting similar problems:
1.  Remember that you can choose to "run as" for your windows form app to run under a different account than you happen to be logged in as.  I suspect running your windows form app with the Administrator account will fail exactly as your service did.
2. Selectively using security auditing can be very help in pinpointing access problems.
3. Using Sysinternals ProcMon can often pinpoint what exactly access is being denied to.
4. To make debugging as much of your service code as possible without it running as a service use the #DEBUG as suggested in this blog post (http://jclaes.blogspot.com/2010/03/cannot-start-service-from-command-line.html)</p>

Body:
I am trying to use ManagementEventWatcher inside a C# .NET4 windows service application. At some point in the "OnStart" method I have these lines:

string scope = "\\root\\cimv2";
string query =
  "SELECT * FROM __InstanceCreationEvent " +
  "WITHIN 1 " +
  "WHERE TargetInstance ISA 'Win32_NTLogEvent' " +
  " AND ( " +
  "      targetInstance.EventCode = '4768' " +
  "   OR targetInstance.EventCode = '4770' " +
  "   OR targetInstance.EventCode = '672'" +
  "   OR targetInstance.EventCode = '674'" +
  " )";
eventListener = new ManagementEventWatcher(scope, query);
eventListener.EventArrived += new EventArrivedEventHandler(HandleEvent);

eventListener.Start();

The eventListener.Start(); line gives an exception with the message "Access Denied". I tried to set up my service as Administrator or LOCALSYSTEM but it does not help.

I also found this documentation: http://msdn.microsoft.com/en-us/library/aa392289(VS.85).aspx
But I can not figure out how to use it in C#.

The same code works as expected if put in a WindowsForms application.

Thanks.


问:
php autocomplete with vim
i'm looking for an php autocomplete solution for vim. I already was at this thread:
Vim PHP omni completion
but it doesn't work for me.
I generate the tags file with this bash script:

```<code>#!/bin/bash
exec ctags -V -f tags \
-h \".php\" -R \
--exclude=\"\.git\" \
--totals=yes \
--language-force=PHP \
--tag-relative=yes \
--PHP-kinds=+cfiv \
--regex-PHP='/(abstract)?\s+class\s+([^ ]+)/\2/c/' \
--regex-PHP='/(static|abstract|public|protected|private)\s+(final\s+)?function\s+(\&\s+)?([^ (]+)/\4/f/' \
--regex-PHP='/interface\s+([^ ]+)/\1/i/' \
--regex-PHP='/\$([a-zA-Z_][a-zA-Z0-9_]*)/\1/v/' \
kernel/classes/
</code>```

but the autocomplete is not as desired. I don't even know if the plugin is loading.
so, how can i see if the plugin is loading? (the plugin is located under bundle, i use pathogen, and other plugins do work..)
it is necessary to activate something else?
i have VIM - Vi IMproved 7.3, Exuberant Ctags 5.8

thanks

答:
Padawan with Deoplete are great solutions for having a robust PHP autocompletion in Neovim. For Vim you can use Neocomplete instead of Deoplete.

I wrote an article how to make a Vim PHP IDE if somebody is interested :)

Title: php autocomplete with vim

Body:
i'm looking for an php autocomplete solution for vim. I already was at this thread:
Vim PHP omni completion
but it doesn't work for me.
I generate the tags file with this bash script:

#!/bin/bash
exec ctags -V -f tags \
-h \".php\" -R \
--exclude=\"\.git\" \
--totals=yes \
--language-force=PHP \
--tag-relative=yes \
--PHP-kinds=+cfiv \
--regex-PHP='/(abstract)?\s+class\s+([^ ]+)/\2/c/' \
--regex-PHP='/(static|abstract|public|protected|private)\s+(final\s+)?function\s+(\&\s+)?([^ (]+)/\4/f/' \
--regex-PHP='/interface\s+([^ ]+)/\1/i/' \
--regex-PHP='/\$([a-zA-Z_][a-zA-Z0-9_]*)/\1/v/' \
kernel/classes/

but the autocomplete is not as desired. I don't even know if the plugin is loading.
so, how can i see if the plugin is loading? (the plugin is located under bundle, i use pathogen, and other plugins do work..)
it is necessary to activate something else?
i have VIM - Vi IMproved 7.3, Exuberant Ctags 5.8

thanks


问:
determinate which css is loaded with jQuery
I have html page that loads different css, depending on screen width (targeting pc, tablets and phones):

```<code><meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 1200px)" href="css/desktop-style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 769px) and (max-width: 1199px)" href="css/tablet-style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 100px) and (max-width: 768px)" href="css/phone-style.css" >
</code>```

I heavily depend on jQuery, and functions should be chosen depending on active css. Is there a way in JavaScript of jQuery to determinate which css is active?
Or should I use jQuery to determinate browser width, and make further functions depending on width output?
Thank you.

答:
I recommend you to use media query but if you want a JavaScript solution, can do this with jQuery like this:

var window = $(window).width();
var css = $('#css');

if(window > 100 && window < 768){
  css.attr('href','css/desktop-style.css')
} else if(window > 769 && window < 1199){
  css.attr('href','css/tablet-style.css')
} else if(window > 1200){
  css.attr('href','css/phone-style.css')
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link id="css" rel="stylesheet" type="text/css" href="css/style.css" ></code>```

Note: You can change resolutions as you want, I'm not sure it's correct for detect mobile tablet or etc.

Warning: Be aware! this method a little bad for SEO things, google and etc not read your responsive styles.

Body:
I have html page that loads different css, depending on screen width (targeting pc, tablets and phones):

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="all" href="css/style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 1200px)" href="css/desktop-style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 769px) and (max-width: 1199px)" href="css/tablet-style.css" >
<link rel="stylesheet" type="text/css" media="screen and (min-width: 100px) and (max-width: 768px)" href="css/phone-style.css" >

I heavily depend on jQuery, and functions should be chosen depending on active css. Is there a way in JavaScript of jQuery to determinate which css is active?
Or should I use jQuery to determinate browser width, and make further functions depending on width output?
Thank you.

Body:
I recommend you to use media query but if you want a JavaScript solution, can do this with jQuery like this:

var window = $(window).width();
var css = $('#css');

if(window > 100 && window < 768){
  css.attr('href','css/desktop-style.css')
} else if(window > 769 && window < 1199){
  css.attr('href','css/tablet-style.css')
} else if(window > 1200){
  css.attr('href','css/phone-style.css')
}

<link id="css" rel="stylesheet" type="text/css" href="css/style.css" >

Note: You can change resolutions as you want, I'm not sure it's correct for detect mobile tablet or etc.

Warning: Be aware! this method a little bad for SEO things, google and etc not read your responsive styles.


问:
How to find the last occurrence of an element in a Scala List?
I have a List of Students from which I want to find the last matching student whose age is 23.

I know that find() method gives us the first matching occurrence as shown below:

```<code>case class Student(id: Int, age: Int)

val students = List(Student(1, 23), Student(2, 24), Student(3, 23))

val firstStudentWithAge23 = students.find(student => student.age == 23)
// Some(Student(1, 23))
</code>```

This code gives me the first matching student. But I need the last matching student.

For now, I am using reverse method followed by find:

```<code>val lastStudentWithAge23 = students.reverse.find(student => student.age == 23)
// Some(Student(3,23))
</code>```

This gives me the last matching student.

But this doesn't not seem to be a good approach since the whole list has to be reversed first. How can I achieve this in a better yet functional way ?

答:
Yet another approach, using partition, for instance as follows,

```<code>val (l, _) = list.partition(_.age == 23)
l.lastOption
</code>```

which delivers the list bisected into a tuple of those aged 23 in order of occurrence in the original list, and the rest. From the first tuple take the last item.

ContentLicense: CC BY-SA 4.0

Body:
I have a List of Students from which I want to find the last matching student whose age is 23.

I know that find() method gives us the first matching occurrence as shown below:

case class Student(id: Int, age: Int)

val students = List(Student(1, 23), Student(2, 24), Student(3, 23))

val firstStudentWithAge23 = students.find(student => student.age == 23)
// Some(Student(1, 23))

This code gives me the first matching student. But I need the last matching student.

For now, I am using reverse method followed by find:

val lastStudentWithAge23 = students.reverse.find(student => student.age == 23)
// Some(Student(3,23))

This gives me the last matching student.

But this doesn't not seem to be a good approach since the whole list has to be reversed first. How can I achieve this in a better yet functional way ?

Body:
Yet another approach, using partition, for instance as follows,

val (l, _) = list.partition(_.age == 23)
l.lastOption

which delivers the list bisected into a tuple of those aged 23 in order of occurrence in the original list, and the rest. From the first tuple take the last item.


问:
How to add watermark when upload image using laravel using any library or custom development
I am trying to add watermark to images using http://image.intervention.io library but not working here's my code given below
I need to implement watermark dynamically when uploading or retrieving images

Controller Code

```<code>public function store(storeNewspaperJobFormValidation $request)
    {
        $values = $request->input();

        list($city, $catagory) = $this->_gettingValues($values);

        unset($values['city_id']);
        unset($values['catagory_id']);

        $values['slug'] = str_slug($values['organization_name'] . '-' . rand(1, 1000), '-');

        if ($request->hasFile('image_file')) {

            $request->file('image_file');
            $filename = $request->image_file->getClientOriginalName();

            $originalfile['image_file'] = $request->image_file->storeAs('public/newpaper_jobs', $filename);

            $data = array_merge($values, $originalfile);

            $newspaper = new newspaper_jobad($data);
            $newspaper->save();

            $insertedId = $newspaper->id;

            $this->_saveCatagoryNewspaperJobadbAssociations($catagory, $insertedId);

            $this->_saveNewspaperJobCities($city, $insertedId);

            //a flash message shold be shown that data successfully created
            flash('Data successfully added')->success();
            return back();

        } else

            flash('Data Not Inserted Image is Missing')->success();
        return back();

    }
</code>```

Model

```<code>use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;
use Laravel\Scout\Searchable;
use Intervention\Image\Facades\Image;

class newspaper_jobad extends Model
{
    use Searchable;

    protected $fillable = ['organization_name', 'job_apply_link', 'job_description', 'city_id', 'province_id', 'sector_id', 'image_file', 'test_id', 'newspaper_id', 'catagory_id', 'slug', 'meta_keywords', 'meta_description', 'job_title'];

    public function getFilePathAttribute($value)
    {
        $img = Image::make("public/newpaper_jobs/$value"); //your image I assume you have in public directory
        $img->insert('public/favico.png', 'bottom-right', 10, 10); //insert watermark in (also from public_directory)
        $img->save("public/Storage/newpaper_jobs/$value"); //save created image (will override old image)
        return ($value); //return value
    }
</code>```

Location of image is

```<code>public/Storage/newpaper_jobs/
</code>```

Location of watermark image

```<code>public/favico.png
</code>```

答:
I use spatie/laravel-medialibrary for managing my models media, it makes the process really easy. It's based on the concept of conversions, so you just set your model to have a media conversion with a watermark:

```<code>class ModelWithMedia extends Model implements HasMediaConversions
{

    /* Traits */

    use HasMediaTrait;

    /* Attributes */

    public function registerMediaConversions(Media $media = null)
    {
        // Watermark conversion
        $this->addMediaConversion($media->basename.'-watermark')
            ->watermark(public_path('/img/watermark.png'))
            ->nonQueued();
    }
}
</code>```

It uses spatie/image for image modifications, so you can use any method available in the package and chain them together until you get your desired modification.

Hope this helps you.

Body:
I am trying to add watermark to images using http://image.intervention.io library but not working here's my code given below
I need to implement watermark dynamically when uploading or retrieving images

Controller Code

public function store(storeNewspaperJobFormValidation $request)
    {
        $values = $request->input();

        list($city, $catagory) = $this->_gettingValues($values);

        unset($values['city_id']);
        unset($values['catagory_id']);

        $values['slug'] = str_slug($values['organization_name'] . '-' . rand(1, 1000), '-');

        if ($request->hasFile('image_file')) {

            $request->file('image_file');
            $filename = $request->image_file->getClientOriginalName();

            $originalfile['image_file'] = $request->image_file->storeAs('public/newpaper_jobs', $filename);

            $data = array_merge($values, $originalfile);

            $newspaper = new newspaper_jobad($data);
            $newspaper->save();

            $insertedId = $newspaper->id;

            $this->_saveCatagoryNewspaperJobadbAssociations($catagory, $insertedId);

            $this->_saveNewspaperJobCities($city, $insertedId);

            //a flash message shold be shown that data successfully created
            flash('Data successfully added')->success();
            return back();

        } else

            flash('Data Not Inserted Image is Missing')->success();
        return back();

    }

Model

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;
use Laravel\Scout\Searchable;
use Intervention\Image\Facades\Image;

class newspaper_jobad extends Model
{
    use Searchable;

    protected $fillable = ['organization_name', 'job_apply_link', 'job_description', 'city_id', 'province_id', 'sector_id', 'image_file', 'test_id', 'newspaper_id', 'catagory_id', 'slug', 'meta_keywords', 'meta_description', 'job_title'];

    public function getFilePathAttribute($value)
    {
        $img = Image::make("public/newpaper_jobs/$value"); //your image I assume you have in public directory
        $img->insert('public/favico.png', 'bottom-right', 10, 10); //insert watermark in (also from public_directory)
        $img->save("public/Storage/newpaper_jobs/$value"); //save created image (will override old image)
        return ($value); //return value
    }

Location of image is

public/Storage/newpaper_jobs/

Location of watermark image

public/favico.png

Body:
I use spatie/laravel-medialibrary for managing my models media, it makes the process really easy. It's based on the concept of conversions, so you just set your model to have a media conversion with a watermark:

class ModelWithMedia extends Model implements HasMediaConversions
{

    /* Traits */

    use HasMediaTrait;

    /* Attributes */

    public function registerMediaConversions(Media $media = null)
    {
        // Watermark conversion
        $this->addMediaConversion($media->basename.'-watermark')
            ->watermark(public_path('/img/watermark.png'))
            ->nonQueued();
    }
}

It uses spatie/image for image modifications, so you can use any method available in the package and chain them together until you get your desired modification.

Hope this helps you.


问:
Passing a vector or arguments to boost::process (boost::fusion)
I'm trying to create a boost::process from a vector of string arguments:

```<code>void runProcess( const std::string& exe, const std::vector<std::string>& args )
{
    bp::ipstream out;
    bp::child c(exe, args, std_out > out);
    ...
}
</code>```

This apparently works, but I'm getting the following warning:

warning C4503: 'boost::fusion::detail::for_each_linear': decorated name length exceeded, name was truncated

It diseappears if passing arguments one by one bp::child c(exe, "param1", "param2", std_out > out);.

What is the correct way to call childconstructor in this situation?

答:
You would use the as intended:

```<code>bp::child c(bp::search_path("ls"), bp::args({"-1", "-l"})/*, ...*/);
</code>```

In your case maybe like

```<code>void runProcess( const std::string& exe, const std::vector<std::string>& args )
{
    bp::ipstream out;
    bp::child c(exe, bp::args(args), std_out > out);
    ...
}
</code>```

Body:
I'm trying to create a boost::process from a vector of string arguments:

void runProcess( const std::string& exe, const std::vector<std::string>& args )
{
    bp::ipstream out;
    bp::child c(exe, args, std_out > out);
    ...
}

This apparently works, but I'm getting the following warning:

warning C4503: 'boost::fusion::detail::for_each_linear': decorated name length exceeded, name was truncated

It diseappears if passing arguments one by one bp::child c(exe, "param1", "param2", std_out > out);.

What is the correct way to call childconstructor in this situation?

Body:
You would use the as intended:

bp::child c(bp::search_path("ls"), bp::args({"-1", "-l"})/*, ...*/);

In your case maybe like

void runProcess( const std::string& exe, const std::vector<std::string>& args )
{
    bp::ipstream out;
    bp::child c(exe, bp::args(args), std_out > out);
    ...
}


答:
A solution using dplyr and tidyr. I filtered out the value with -99 through the process, assuming that this is what you want to do.

```<code>library(dplyr)
library(tidyr)

mydata2 <- mydata %>%
  mutate(date = as.character(date)) %>%                       # Convert to character
  filter(value != -99) %>%                                    # Remove -99
  extract(date, into = c("Year", "Month", "Day"),             # Split the date column
          regex = "([0-9]+)-([0-9]+)-([0-1]+)",
          convert = TRUE) %>%
  group_by(Year, Month) %>%                                   # Group by Year and Month
  mutate(Day = Day + row_number() - 1) %>%                    # Update Day to Day + row numbers - 1
  unite(col = date, Year, Month, Day, sep = "-") %>%          # Unite the Year, Month, Day columns
  mutate(date = as.Date(date))                                # Convert the date to date class
head(mydata2)
# # A tibble: 6 x 2
#         date  value
#       <date>  <dbl>
# 1 1993-01-01 32.000
# 2 1993-01-02 33.750
# 3 1993-01-03 23.000
# 4 1993-01-04 15.125
# 5 1993-01-05 25.125
# 6 1993-01-06 25.857
</code>```

Or we can use the dplyr and lubridate package with a similar strategy.

```<code>library(dplyr)
library(lubridate)

mydata2 <- mydata %>%
  filter(value != -99) %>%                            # Remove -99
  mutate(date = ymd(as.character(date))) %>%          # Convert the date column to date class
  mutate(Year = year(date), Month = month(date)) %>%  # Create Year and Month column
  group_by(Year, Month) %>%                           # Group by Year and Month
  mutate(date = date + days(row_number() - 1)) %>%    # Add day numbers based on row number - 1
  ungroup() %>%                                       # Ungroup
  select(date, value)                                 # Select the columns
head(mydata2)
# # A tibble: 6 x 2
#         date  value
#       <date>  <dbl>
# 1 1993-01-01 32.000
# 2 1993-01-02 33.750
# 3 1993-01-03 23.000
# 4 1993-01-04 15.125
# 5 1993-01-05 25.125
# 6 1993-01-06 25.857
</code>```

Title: convert factor into date with right days

Body:
I have a list of data.frames. Each data.frame has one column with dates and other with values. This is a sample of one of the data.frame (the data is quite large)

           dput(mydata)
structure(list(date = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("1993-01-01",
"1993-02-01", "1993-03-01", "1993-04-01", "1993-05-01", "1993-06-01",
"1993-07-01", "1993-08-01", "1993-09-01", "1993-10-01", "1993-11-01",
"1993-12-01", "1994-01-01", "1994-02-01", "1994-03-01", "1994-04-01",
"1994-05-01", "1994-06-01", "1994-07-01", "1994-08-01", "1994-09-01",
"1994-10-01", "1994-11-01", "1994-12-01", "1995-01-01", "1995-02-01",
"1995-03-01", "1995-04-01", "1995-05-01", "1995-06-01", "1995-07-01",
"1995-08-01", "1995-09-01", "1995-10-01", "1995-11-01", "1995-12-01",
"1996-01-01", "1996-02-01", "1996-03-01", "1996-04-01", "1996-05-01",
"1996-06-01", "1996-07-01", "1996-08-01", "1996-09-01", "1996-10-01",
"1996-11-01", "1996-12-01", "2000-01-01", "2000-02-01", "2000-03-01",
"2000-04-01", "2000-05-01", "2000-06-01", "2000-07-01", "2000-08-01",
"2000-09-01", "2000-10-01", "2000-11-01", "2000-12-01", "2001-01-01",
"2001-02-01", "2001-03-01", "2001-04-01", "2001-05-01", "2001-06-01",
"2001-07-01", "2001-08-01", "2001-09-01", "2001-10-01", "2001-11-01",
"2001-12-01", "2002-01-01", "2002-02-01", "2002-03-01", "2002-04-01",
"2002-05-01", "2002-06-01", "2002-07-01", "2002-08-01", "2002-09-01",
"2002-10-01", "2002-11-01", "2002-12-01", "2003-01-01", "2003-02-01",
"2003-03-01", "2003-04-01", "2003-05-01", "2003-06-01", "2003-07-01",
"2003-08-01", "2003-09-01", "2003-10-01", "2003-11-01", "2003-12-01"
), class = "factor"), value = c(32, 33.75, 23, 15.125, 25.125,
25.857, 25.25, 38.125, 35.5, 49.875, 55.25, 46.625, 52.625, 51.125,
45.75, 52.625, 54.125, 42.875, 36.375, 39.375, 52.625, 61.375,
61.375, 61.875, 61.5, 62.5, 50.625, 43.5, 38.167, 36.714, 41.875,
28.875, 20.333, 22.25, 24, 21.333, 3.167, 41.75, 19.375, 10.25,
16.625, 19.5, 48.333, 22.5, 26.25, 28.625, 31.5, 50.625, 50.375,
57, 63, 64.286, 65, 46.125, 59, 54.75, 25.375, 77, 74.125, -99,
-99, -99, 95.375, 86, 72.875, 85.25, 38.5, -99, 72.875, 80.375,
99.25, 94, 76.5, 32.875, 87.375, 114.875, 91.5, 96.25, 64.25,
55.75, 67.5, 79, 103, 66.25, 50.143, 79.5, 66.25, 75.75, 73.125,
77.25, 70.125, 65.5, 77.375, 103.375, 97.25, 66.875, 86.875,
71.375, 69.875, 62.75)), .Names = c("date", "value"), row.names = c(1L,
97L, 193L, 289L, 385L, 481L, 577L, 673L, 769L, 865L, 961L, 1057L,
1153L, 1249L, 1345L, 1441L, 1537L, 1633L, 1729L, 1825L, 1921L,
2017L, 2113L, 2209L, 2305L, 2401L, 2497L, 2593L, 2689L, 2785L,
2881L, 2L, 98L, 194L, 290L, 386L, 482L, 578L, 674L, 770L, 866L,
962L, 1058L, 1154L, 1250L, 1346L, 1442L, 1538L, 1634L, 1730L,
1826L, 1922L, 2018L, 2114L, 2210L, 2306L, 2402L, 2498L, 2594L,
2690L, 2786L, 2882L, 3L, 99L, 195L, 291L, 387L, 483L, 579L, 675L,
771L, 867L, 963L, 1059L, 1155L, 1251L, 1347L, 1443L, 1539L, 1635L,
1731L, 1827L, 1923L, 2019L, 2115L, 2211L, 2307L, 2403L, 2499L,
2595L, 2691L, 2787L, 2883L, 4L, 100L, 196L, 292L, 388L, 484L,
580L), class = "data.frame")

The problem is that the column date is a factor and all months contain 31 days (the corresponding value has -99 is the month is 30 or 28,29-days). I am trying to convert the date into a proper date format, with the correct days, but I'm struggling with that..I can convert the factor to a date, but I don't know how to convert into the right days like:

      head(mydata)
      date  value
      1993-01-01 32.000
      1993-01-02 33.750
      1993-01-03 23.000
      1993-01-04 15.125
      1993-01-05 25.125
      1993-01-06 25.857

....

I appreciate any suggestion,
Thanks!

Body:
A solution using dplyr and tidyr. I filtered out the value with -99 through the process, assuming that this is what you want to do.

library(dplyr)
library(tidyr)

mydata2 <- mydata %>%
  mutate(date = as.character(date)) %>%                       # Convert to character
  filter(value != -99) %>%                                    # Remove -99
  extract(date, into = c("Year", "Month", "Day"),             # Split the date column
          regex = "([0-9]+)-([0-9]+)-([0-1]+)",
          convert = TRUE) %>%
  group_by(Year, Month) %>%                                   # Group by Year and Month
  mutate(Day = Day + row_number() - 1) %>%                    # Update Day to Day + row numbers - 1
  unite(col = date, Year, Month, Day, sep = "-") %>%          # Unite the Year, Month, Day columns
  mutate(date = as.Date(date))                                # Convert the date to date class
head(mydata2)
# # A tibble: 6 x 2
#         date  value
#       <date>  <dbl>
# 1 1993-01-01 32.000
# 2 1993-01-02 33.750
# 3 1993-01-03 23.000
# 4 1993-01-04 15.125
# 5 1993-01-05 25.125
# 6 1993-01-06 25.857

Or we can use the dplyr and lubridate package with a similar strategy.

library(dplyr)
library(lubridate)

mydata2 <- mydata %>%
  filter(value != -99) %>%                            # Remove -99
  mutate(date = ymd(as.character(date))) %>%          # Convert the date column to date class
  mutate(Year = year(date), Month = month(date)) %>%  # Create Year and Month column
  group_by(Year, Month) %>%                           # Group by Year and Month
  mutate(date = date + days(row_number() - 1)) %>%    # Add day numbers based on row number - 1
  ungroup() %>%                                       # Ungroup
  select(date, value)                                 # Select the columns
head(mydata2)
# # A tibble: 6 x 2
#         date  value
#       <date>  <dbl>
# 1 1993-01-01 32.000
# 2 1993-01-02 33.750
# 3 1993-01-03 23.000
# 4 1993-01-04 15.125
# 5 1993-01-05 25.125
# 6 1993-01-06 25.857


问:
How to Do Growing Table / List

JS

```<code>var model = new JSONModel();
model.setData(data);
this.getView().byId("Table").setModel(model);
var table = this.getView().byId("Table");
table.bindItems({
    path: "/",
    template: new sap.m.ColumnListItem({
        cells: [
            new sap.m.Image({
                src: "{photo}"
            }),
            new sap.m.Text({
                text: "{name}"
            })
        ]
    })
});
</code>```

Here I have few data. Using above code I can list in table. Now I want to list only first 10 items in table and rest of the data will show after scroll down only. After scroll down mouse I need to call a function to get next 10 datas. How we can call a function after scroll down in sapUi5;

答:
OData

In order to enable growing on scroll, you need to take the following into account:

The sap.m.ListBase control (e.g. sap.m.Table) needs:

growing="true"

growingThreshold="<number of entries to load>"

growingScrollToLoad="true"

The list control needs to be inside a scrollable container.

(growingScrollToLoad) can only be used if the growing property is set to true and only if there is one instance of sap.m.List or sap.m.Table inside the scrollable scroll container (e.g sap.m.Page). (Source)

Run this example to see it in action:

globalThis.onUI5Init = () => sap.ui.require([
  "sap/ui/model/odata/v4/ODataModel",
  "sap/ui/core/mvc/XMLView",
], async function (ODataModel, XMLView) {
  "use strict";

  const model = new ODataModel({
    serviceUrl: "https://services.odata.org/TripPinRESTierService/(S(5pfdhufu5ymr2jh0az0vcwqe))/",
    autoExpandSelect: true,
  });

  const control = await XMLView.create({
    definition: `<mvc:View xmlns:mvc="sap.ui.core.mvc"
      xmlns="sap.m"
      displayBlock="true"
      height="100%"
    >
      <App>
        <Page showHeader="false">
          <List
            growing="true"
            growingThreshold="5"
            growingScrollToLoad="true"
            items="{/People}"
          >
            <StandardListItem title="{FirstName}" />
          </List>
        </Page>
      </App>
    </mvc:View>`,
    models: model,
  });
  control.placeAt("content");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script id="sap-ui-bootstrap"
  src="https://sdk.openui5.org/nightly/resources/sap-ui-core.js"
  data-sap-ui-oninit="onUI5Init"
  data-sap-ui-libs="sap.ui.core,sap.m,sap.ui.unified,sap.ui.layout"
  data-sap-ui-theme="sap_horizon_dark"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-excludejquerycompat="true"
  data-sap-ui-xx-waitForTheme="init"
></script>
<body id="content" class="sapUiBody"></body></code>```

Manual Hook

How we can call a function after scroll down in SAPUI5?

In case there is no OData service (no $top & $skip) but the app still needs to be notified when the user reached almost the end of the list (either by scrolling or by keyboard), you can make use of the sap.ui.core.delegate.ScrollEnablement. And since the list control is supposed to be already inside a scrollable container (such as Page), creating a new instance of ScrollEnablement is not necessary. Instead, there is a handy API to retrieve the corresponding ScrollEnablement delegate which is getScrollDelegate. Once you have the delegate object, call setGrowingList which awaits a hook function that gets invoked when the bottom is almost reached.

Example:

sap.ui.require([
  "sap/m/library",
], sapMLib => sapMLib.getScrollDelegate(myListControl).setGrowingList(() => {
  // Your code to load more data
}, sapMLib.ListGrowingDirection.Downwards));
```

Note

The API getScrollDelegate returns only the reference when the scrollable parent control has already created an instance of ScrollEnablement before rendering.

The API setGrowingList is protected, meaning it's not meant to be used by application developers. Please use the API only when extending the target control.

Title: How to Do Growing Table / List

Body:
JS

var model = new JSONModel();
model.setData(data);
this.getView().byId("Table").setModel(model);
var table = this.getView().byId("Table");
table.bindItems({
    path: "/",
    template: new sap.m.ColumnListItem({
        cells: [
            new sap.m.Image({
                src: "{photo}"
            }),
            new sap.m.Text({
                text: "{name}"
            })
        ]
    })
});

Here I have few data. Using above code I can list in table. Now I want to list only first 10 items in table and rest of the data will show after scroll down only. After scroll down mouse I need to call a function to get next 10 datas. How we can call a function after scroll down in sapUi5;

Body:
OData

In order to enable growing on scroll, you need to take the following into account:

The sap.m.ListBase control (e.g. sap.m.Table) needs:

growing="true"

growingThreshold="<number of entries to load>"

growingScrollToLoad="true"

The list control needs to be inside a scrollable container.

(growingScrollToLoad) can only be used if the growing property is set to true and only if there is one instance of sap.m.List or sap.m.Table inside the scrollable scroll container (e.g sap.m.Page). (Source)

Run this example to see it in action:

globalThis.onUI5Init = () => sap.ui.require([
  "sap/ui/model/odata/v4/ODataModel",
  "sap/ui/core/mvc/XMLView",
], async function (ODataModel, XMLView) {
  "use strict";

  const model = new ODataModel({
    serviceUrl: "https://services.odata.org/TripPinRESTierService/(S(5pfdhufu5ymr2jh0az0vcwqe))/",
    autoExpandSelect: true,
  });

  const control = await XMLView.create({
    definition: `<mvc:View xmlns:mvc="sap.ui.core.mvc"
      xmlns="sap.m"
      displayBlock="true"
      height="100%"
    >
      <App>
        <Page showHeader="false">
          <List
            growing="true"
            growingThreshold="5"
            growingScrollToLoad="true"
            items="{/People}"
          >
            <StandardListItem title="{FirstName}" />
          </List>
        </Page>
      </App>
    </mvc:View>`,
    models: model,
  });
  control.placeAt("content");
});

<script id="sap-ui-bootstrap"
  src="https://sdk.openui5.org/nightly/resources/sap-ui-core.js"
  data-sap-ui-oninit="onUI5Init"
  data-sap-ui-libs="sap.ui.core,sap.m,sap.ui.unified,sap.ui.layout"
  data-sap-ui-theme="sap_horizon_dark"
  data-sap-ui-async="true"
  data-sap-ui-compatversion="edge"
  data-sap-ui-excludejquerycompat="true"
  data-sap-ui-xx-waitForTheme="init"
></script>
<body id="content" class="sapUiBody"></body>

Manual Hook

How we can call a function after scroll down in SAPUI5?

In case there is no OData service (no $top & $skip) but the app still needs to be notified when the user reached almost the end of the list (either by scrolling or by keyboard), you can make use of the sap.ui.core.delegate.ScrollEnablement. And since the list control is supposed to be already inside a scrollable container (such as Page), creating a new instance of ScrollEnablement is not necessary. Instead, there is a handy API to retrieve the corresponding ScrollEnablement delegate which is getScrollDelegate. Once you have the delegate object, call setGrowingList which awaits a hook function that gets invoked when the bottom is almost reached.

Example:

sap.ui.require([
  "sap/m/library",
], sapMLib => sapMLib.getScrollDelegate(myListControl).setGrowingList(() => {
  // Your code to load more data
}, sapMLib.ListGrowingDirection.Downwards));

Note

The API getScrollDelegate returns only the reference when the scrollable parent control has already created an instance of ScrollEnablement before rendering.

The API setGrowingList is protected, meaning it's not meant to be used by application developers. Please use the API only when extending the target control.


问:
Math unexpectedly produces infinity '∞'
The goal is to have a progress bar monitoring an external process that writes the step it is on into a watch file.

If I do not have a Start-Sleep in the loop, it will produce messages about not being able to convert infinity. Why is this? I am willing to have some sleep time, but why is it needed and what is the minimum time needed to sleep?

```<code>PS C:\src\t\pb> .\Monitor-Progress2.ps1 -TotalCount 5 -WatchFile wf.txt -Verbose
New-TimeSpan : Cannot bind parameter 'Seconds'. Cannot convert value "∞" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
At C:\src\t\pb\Monitor-Progress2.ps1:46 char:37
+ ... an -Seconds (($ts.TotalSeconds / $currentCount) * ($TotalCount - $cur ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [New-TimeSpan], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewTimeSpanCommand
</code>```

Here is the code. The same problem occurs on PowerShell 5.1 and 6.0. All I do to run it is to ECHO>wf.txt 1, then ECHO>wf.txt 2, etc. Sometimes the error occurs on step two, but sometimes on step 3.

```<code>[CmdletBinding()]
Param (
    [Parameter(Mandatory=$true)]
    [int]$TotalCount

    ,[Parameter(Mandatory=$true)]
    [ValidateScript({Test-Path $_ -PathType 'Leaf'})]
    [string]$WatchFile
)

$currentcount = 0
$previouscount = $currentcount

$starttimestamp = Get-Date

while ($currentcount -lt $TotalCount) {
    $currentcount = [int32](Get-Content $WatchFile)

    ### Write-Verbose $currentcount

    if (($currentcount -lt $TotalCount) -and ($currentcount -ne $previouscount)) {
        $ts = $(Get-Date) - $starttimestamp

        ### Write-Verbose $ts.TotalSeconds
        ### Write-Verbose $currentcount
        ### Write-Verbose ($ts.TotalSeconds / $currentcount)
        ### Write-Verbose ($TotalCount - $currentcount)
        ### Write-Verbose (($ts.TotalSeconds / $currentcount) * ($TotalCount - $currentcount))

        $et = New-TimeSpan -Seconds (($ts.TotalSeconds / $currentCount) * ($TotalCount - $currentcount))
        $runningstatus = "Long process running for {0:%d} days {0:%h} hours {0:%m} minutes {0:%s} seconds" -f $ts
        $completionstatus = "Estimated completion in {0:%d} days {0:%h} hours {0:%m} minutes {0:%s} seconds" -f $et
        Write-Progress -Activity $runningstatus `
            -Status $completionstatus `
            -percentComplete ($currentcount / $TotalCount*100)
        $previouscount = $currentcount
    }

    #Start-Sleep -Seconds 1
}
</code>```

答:
While your code didn't process a single entity, your $currentcount is zero, therefore your naive ETA calculation returns infinity. You should check if you can calculate ETA first by comparing current count with zero.

EDIT: You have done an implicit conversion of Get-Content which returns an array of strings, so if your file has a newline in it, you get a conversion error and your $currentcount remains zero, thus you divide by zero to get that infinity. You should either use [IO.File]::ReadAllText() method, or use only the first line (with index 0) for parsing. Or you should write to the file with -NoNewLine flag to Out-File cmdlet.

Title: Math unexpectedly produces infinity '∞'

Body:
The goal is to have a progress bar monitoring an external process that writes the step it is on into a watch file.

If I do not have a Start-Sleep in the loop, it will produce messages about not being able to convert infinity. Why is this? I am willing to have some sleep time, but why is it needed and what is the minimum time needed to sleep?

PS C:\src\t\pb> .\Monitor-Progress2.ps1 -TotalCount 5 -WatchFile wf.txt -Verbose
New-TimeSpan : Cannot bind parameter 'Seconds'. Cannot convert value "∞" to type "System.Int32". Error: "Value was either too large or too small for an Int32."
At C:\src\t\pb\Monitor-Progress2.ps1:46 char:37
+ ... an -Seconds (($ts.TotalSeconds / $currentCount) * ($TotalCount - $cur ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (:) [New-TimeSpan], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewTimeSpanCommand

Here is the code. The same problem occurs on PowerShell 5.1 and 6.0. All I do to run it is to ECHO>wf.txt 1, then ECHO>wf.txt 2, etc. Sometimes the error occurs on step two, but sometimes on step 3.

[CmdletBinding()]
Param (
    [Parameter(Mandatory=$true)]
    [int]$TotalCount

    ,[Parameter(Mandatory=$true)]
    [ValidateScript({Test-Path $_ -PathType 'Leaf'})]
    [string]$WatchFile
)

$currentcount = 0
$previouscount = $currentcount

$starttimestamp = Get-Date

while ($currentcount -lt $TotalCount) {
    $currentcount = [int32](Get-Content $WatchFile)

    ### Write-Verbose $currentcount

    if (($currentcount -lt $TotalCount) -and ($currentcount -ne $previouscount)) {
        $ts = $(Get-Date) - $starttimestamp

        ### Write-Verbose $ts.TotalSeconds
        ### Write-Verbose $currentcount
        ### Write-Verbose ($ts.TotalSeconds / $currentcount)
        ### Write-Verbose ($TotalCount - $currentcount)
        ### Write-Verbose (($ts.TotalSeconds / $currentcount) * ($TotalCount - $currentcount))

        $et = New-TimeSpan -Seconds (($ts.TotalSeconds / $currentCount) * ($TotalCount - $currentcount))
        $runningstatus = "Long process running for {0:%d} days {0:%h} hours {0:%m} minutes {0:%s} seconds" -f $ts
        $completionstatus = "Estimated completion in {0:%d} days {0:%h} hours {0:%m} minutes {0:%s} seconds" -f $et
        Write-Progress -Activity $runningstatus `
            -Status $completionstatus `
            -percentComplete ($currentcount / $TotalCount*100)
        $previouscount = $currentcount
    }

    #Start-Sleep -Seconds 1
}