问:
Reference a function within a library
I created a script for Google Docs that adds a menu item called "Utilities" -> "Insert Date" that (obviously) inserts the current date at the cursor position. I want to reuse this script for other documents and eventually offer it to others in my organisation, so I imported it as a Library in another document. However, when I try to run it, one function within the library references another, so I get an error that the .insertAtCursor function doesn't exist.

Do I need to make have everything in the library within the same function? If not, is there a way to use the call so it assumes it is within the library? I suspect this is my misunderstanding of scopes in Google Apps Script, but am not sure.

Here is the library:

```<code>function onOpen() {
  // Add a menu with some items, some separators, and a sub-menu.
  DocumentApp.getUi().createMenu('Utilities')
      .addItem('Insert Date (dd MMMM yyyy)', 'insertAtCursor')
      .addToUi();
}

/**
 * Inserts the sentence "Hey there!" at the current cursor location in boldface.
 */
function insertAtCursor() {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  if (cursor) {
    // Attempt to insert text at the cursor position. If insertion returns null,
    // then the cursor's containing element doesn't allow text insertions.
    // Date format defined at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
    // Make sure if you change the date format you update the menu items in the onOpen() fuction above
    var date = Utilities.formatDate(new Date(), "GMT", "dd MMMM yyyy"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"
    var element = cursor.insertText(date);
    if (element) {
      element.setBold(false);
    } else {
      DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
    }
  } else {
    DocumentApp.getUi().alert('Cannot find a cursor in the document.');
  }
}
</code>```

And here is how I use it in the other document:

```<code>function onOpen() {
  InsertDate.onOpen()
}
</code>```

If I call InsertDate.insertAtCursor from the other document that works, but doesn't make sense because I only want to call that function from the menu item. I'm not sure how I can modify this library to "just work" in another doc.

答:
In the script that uses the library you'll need to create a menu and also create a function that just calls the library, as the insertAtCursor function is called in the context of the doc using the library:

```<code>function onOpen() {

  // Add a menu with some items, some separators, and a sub-menu.
  DocumentApp.getUi().createMenu('Utilities')
      .addItem('Insert Date (dd MMMM yyyy)', 'insertAtCursor')
      .addToUi();
}

function insertAtCursor() {
  InsertAtCursor.insertAtCursor()
}
</code>```

The following is a bit cleaner and would work it just isn't as obvious what's going on:

```<code>function onOpen() {
  InsertAtCursor.onOpen()
}

function insertAtCursor() {
  InsertAtCursor.insertAtCursor()
}
</code>```

Title: Reference a function within a library

Body:
I created a script for Google Docs that adds a menu item called "Utilities" -> "Insert Date" that (obviously) inserts the current date at the cursor position. I want to reuse this script for other documents and eventually offer it to others in my organisation, so I imported it as a Library in another document. However, when I try to run it, one function within the library references another, so I get an error that the .insertAtCursor function doesn't exist.

Do I need to make have everything in the library within the same function? If not, is there a way to use the call so it assumes it is within the library? I suspect this is my misunderstanding of scopes in Google Apps Script, but am not sure.

Here is the library:

function onOpen() {
  // Add a menu with some items, some separators, and a sub-menu.
  DocumentApp.getUi().createMenu('Utilities')
      .addItem('Insert Date (dd MMMM yyyy)', 'insertAtCursor')
      .addToUi();
}

/**
 * Inserts the sentence "Hey there!" at the current cursor location in boldface.
 */
function insertAtCursor() {
  var cursor = DocumentApp.getActiveDocument().getCursor();

  if (cursor) {
    // Attempt to insert text at the cursor position. If insertion returns null,
    // then the cursor's containing element doesn't allow text insertions.
    // Date format defined at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
    // Make sure if you change the date format you update the menu items in the onOpen() fuction above
    var date = Utilities.formatDate(new Date(), "GMT", "dd MMMM yyyy"); // "yyyy-MM-dd'T'HH:mm:ss'Z'"
    var element = cursor.insertText(date);
    if (element) {
      element.setBold(false);
    } else {
      DocumentApp.getUi().alert('Cannot insert text at this cursor location.');
    }
  } else {
    DocumentApp.getUi().alert('Cannot find a cursor in the document.');
  }
}

And here is how I use it in the other document:

function onOpen() {
  InsertDate.onOpen()
}

If I call InsertDate.insertAtCursor from the other document that works, but doesn't make sense because I only want to call that function from the menu item. I'm not sure how I can modify this library to "just work" in another doc.

Body:
In the script that uses the library you'll need to create a menu and also create a function that just calls the library, as the insertAtCursor function is called in the context of the doc using the library:

function onOpen() {

  // Add a menu with some items, some separators, and a sub-menu.
  DocumentApp.getUi().createMenu('Utilities')
      .addItem('Insert Date (dd MMMM yyyy)', 'insertAtCursor')
      .addToUi();
}

function insertAtCursor() {
  InsertAtCursor.insertAtCursor()
}

The following is a bit cleaner and would work it just isn't as obvious what's going on:

function onOpen() {
  InsertAtCursor.onOpen()
}

function insertAtCursor() {
  InsertAtCursor.insertAtCursor()
}


来源: stackexchange

问:
Why there is an error in setOnItemClickListener
I use fragment and I want to set listview in m fragment.I have error in this field.
I want to use ListView of Foldingcell, but I think I have an error in my adapter.
i can not find error.
any body can't help me?
what should I do?

this is my error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                           at com.a700daneh.a700daneh.loanFragment.onCreateView(loanFragment.java:49)

this is my element for using in listView

```<code>public class Item {

String family1;
String cost1;
String family2;
String cost2;
String explain;
String code;
int Icon;

private View.OnClickListener requestBtnClickListener;

public Item() {
}

public Item(String family1, String cost1, String family2, String cost2, String explain, String code, int Icon) {
    this.family1 = family1;
    this.cost1 = cost1;
    this.family2 = family2;
    this.cost2 = cost2;
    this.explain = explain;
    this.code = code;
    this.Icon = Icon;
    //this.time = time;
}

public String getFamily1() {
    return family1;
}

public void setFamily1(String family1) {
    this.family1 = family1;
}

public String getCost1() {
    return cost2;
}

public void setCost1(String cost2) {
    this.cost2 = cost2;
}

public String getFamily2() {
    return family2;
}

public void setFamily2() {
    this.family2 = family2;
}

public String getCost2() {
    return cost2;
}

public void setCost2() {
    this.cost2 = cost2;
}

public String getExplain() {
    return explain;
}

public void setExplain() {
    this.explain = explain;
}

public String getCode() {
    return code;
}

public void setCode() {
    this.code = code;
}

public int getIcon() {
    return Icon;
}

/**
 * @return List of elements prepared for tests
 */
public static ArrayList<Item> getTestingList() {
    ArrayList<Item> items = new ArrayList<>();
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    return items;

}
</code>```

}

this is my adapter called FoldingCellListAdapter

```<code>public class FoldingCellListAdapter extends ArrayAdapter<Item> {

private HashSet<Integer> unfoldedIndexes = new HashSet<>();
private View.OnClickListener defaultRequestBtnClickListener;

public FoldingCellListAdapter(Context context, List<Item> objects) {
    super(context, 0, objects);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // get item for selected view
    Item item = getItem(position);
    // if cell is exists - reuse it, if not - create the new one from resource
    FoldingCell cell = (FoldingCell) convertView;
    ViewHolder viewHolder;
    if (cell == null) {
        viewHolder = new ViewHolder();
        LayoutInflater vi = LayoutInflater.from(getContext());
        cell = (FoldingCell) vi.inflate(R.layout.cell, parent, false);
        // binding view parts to view holder
        viewHolder.family1 = (TextView) cell.findViewById(R.id.family1);
        viewHolder.code = (TextView) cell.findViewById(R.id.code);
        viewHolder.family2 = (TextView) cell.findViewById(R.id.family2);
        viewHolder.cost2 = (TextView) cell.findViewById(R.id.cost2);
        viewHolder.explain = (TextView) cell.findViewById(R.id.explain);
        viewHolder.cost1 = (TextView) cell.findViewById(R.id.cost1);
        viewHolder.payment = (TextView) cell.findViewById(R.id.pay);
        viewHolder.familyImage1 = (ImageView) cell.findViewById(R.id.familyImage1);
        viewHolder.pinkback = (ImageView) cell.findViewById(R.id.pinkback);
        viewHolder.familyImage2 = (ImageView) cell.findViewById(R.id.familyImage2);

        cell.setTag(viewHolder);
    } else {
        // for existing cell set valid valid state(without animation)
        if (unfoldedIndexes.contains(position)) {
            cell.unfold(true);
        } else {
            cell.fold(true);
        }
        viewHolder = (ViewHolder) cell.getTag();
    }

    // bind data from selected element to view through view holder
    viewHolder.family1.setText(item.getFamily1());
    //viewHolder.time.setText(item.getTime());
    viewHolder.code.setText(item.getCode());
    viewHolder.family2.setText(item.getFamily2());
    viewHolder.cost2.setText(item.getCost2());
    viewHolder.explain.setText(String.valueOf(item.getExplain()));
    viewHolder.cost1.setText(item.getCost1());
    viewHolder.familyImage1.setImageResource(item.getIcon());
    viewHolder.familyImage2.setImageResource(item.getIcon());
    viewHolder.pinkback.setImageResource(item.getIcon());

    return cell;
}

// simple methods for register cell state changes
public void registerToggle(int position) {
    if (unfoldedIndexes.contains(position))
        registerFold(position);
    else
        registerUnfold(position);
}

public void registerFold(int position) {
    unfoldedIndexes.remove(position);
}

public void registerUnfold(int position) {
    unfoldedIndexes.add(position);
}

// View lookup cache
private static class ViewHolder {
    TextView family1;
    TextView payment;
    TextView cost1;
    TextView family2;
    TextView cost2;
    TextView explain;
    TextView code;
    ImageView familyImage1;
    ImageView pinkback;
    ImageView familyImage2;
}
</code>```

}

this is my codes in loanFragment

```<code>public class loanFragment extends Fragment {

public loanFragment() {
    // Required empty public constructor
}

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

    ListView lvlist = (ListView) view.findViewById(R.id.lvlist);

    final ArrayList<Item> items = Item.getTestingList();

    // create custom adapter that holds elements and their state (we need hold a id's of unfolded elements for reusable elements)
    final FoldingCellListAdapter adapter = new FoldingCellListAdapter(getContext(), items);

    // set elements to adapter
    lvlist.setAdapter(adapter);

    // set on click event listener to list view
    lvlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
            // toggle clicked cell state
            ((FoldingCell) view).toggle(false);
            // register in adapter that state for selected cell is toggled
            adapter.registerToggle(pos);
        }
    });

    return view;

}
</code>```

}

I had a layout called cell_content_layout for foldingcell and another layout called cell_title_layout and include these layouts in one layout called cell.

cell_title_content

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:baselineAligned="false"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:id="@+id/cell_title_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/cell_content_view"
        android:layout_toRightOf="@+id/cell_content_view">

        <FrameLayout
            android:id="@+id/familyFrame"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="#dd0f70">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="100dp" />

            <ImageView
                android:id="@+id/familyImage1"
                app:srcCompat="@drawable/family"
                android:layout_width="100dp"
                android:layout_height="109dp"
                android:layout_alignParentBottom="true"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1"
                android:visibility="visible" />

        </FrameLayout>

        <FrameLayout
            android:id="@+id/textFrame1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#d3d8dd">

            <LinearLayout
                android:id="@+id/textLinear1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                android:id="@+id/family1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginRight="18dp"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:text="۱. خانواده x"
                android:textSize="18dp" />

                <TextView
                android:id="@+id/cost1"
                android:layout_width="match_parent"
                android:layout_height="51dp"
                android:layout_marginRight="18dp"
                android:gravity="center_vertical"
                android:text="۵۰۰,۰۰۰  تومان"
                android:textSize="18dp" />
            </LinearLayout>

            <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp" />

        </FrameLayout>

    </LinearLayout>
</LinearLayout>
</code>```

cell_content_layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:visibility="gone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:id="@+id/cell_content_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:background="#ffffff"
        android:orientation="vertical"
        >

        <FrameLayout
            android:id="@+id/textFrame2"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="#d3d8dd">

            <ImageView
                android:id="@+id/pinkback"
                android:layout_width="100dp"
                android:layout_height="109dp"
                android:layout_alignParentBottom="true"
                android:layout_gravity="left"
                android:layout_weight="1"
                android:background="#dd0f70"
                android:visibility="visible" />

            <ImageView
                android:id="@+id/familyImage2"
                android:layout_width="100dp"
                android:layout_height="109dp"
                android:layout_alignParentBottom="true"
                android:layout_gravity="left"
                android:layout_weight="1"
                android:visibility="visible"
                app:srcCompat="@drawable/family" />

            <LinearLayout
                android:id="@+id/textLinear2"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/family2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginRight="18dp"
                    android:layout_weight="1"
                    android:gravity="center_vertical"
                    android:text="۱. خانواده x"
                    android:textSize="18dp" />

                <TextView
                    android:id="@+id/cost2"
                    android:layout_width="match_parent"
                    android:layout_height="51dp"
                    android:layout_marginRight="18dp"
                    android:gravity="center_vertical"
                    android:text="۵۰۰,۰۰۰  تومان"
                    android:textSize="18dp" />
            </LinearLayout>

        </FrameLayout>

        <FrameLayout
            android:id="@+id/containFrame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

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

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </FrameLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

            </LinearLayout>
        </FrameLayout>

        <FrameLayout
        android:id="@+id/frameContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <TextView
                android:id="@+id/explain"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:layout_marginRight="18dp"
                android:layout_marginTop="15dp"
                android:layout_weight="1.00"
                android:gravity="right"
                android:text="توضیحات:" />

            <TextView
                android:id="@+id/code"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="18dp"
                android:layout_weight="0.99"
                android:gravity="right"
                android:text="کد: ۱۲۳۴۵۶۷۸۹" />

            <Button
                android:id="@+id/pay"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="5dp"
                android:background="@drawable/button_style2"
                android:text="پرداخت"
                android:textColor="@color/white"
                android:textSize="16dp" />

        </LinearLayout>
    </FrameLayout>

    <TextView
        android:id="@+id/textView6"
        android:layout_width="match_parent"
        android:layout_height="0dp" />

</LinearLayout>
</code>```

cell

```<code><?xml version="1.0" encoding="utf-8"?>

<com.ramotion.foldingcell.FoldingCell

    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/folding_cell_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:clipChildren="false"
    android:clipToPadding="false">

    <include
        android:id="@+id/include"
        layout="@layout/cell_content_layout"
        android:visibility="gone" />

    <include
        layout="@layout/cell_title_layout"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/include" />

</com.ramotion.foldingcell.FoldingCell>
</code>```

答:
It looks like your error is in the setAdapter not the onItemClickListener.
My guess is that ListView lvlist = (ListView) view.findViewById(R.id.lvlist); return null;
Check if "R.id.lvlist" is realy the id of your listView in the xml file.

Also, Check if "lvlist" is null after the findViewById line of code

ContentLicense: CC BY-SA 3.0

Body:
I use fragment and I want to set listview in m fragment.I have error in this field.
I want to use ListView of Foldingcell, but I think I have an error in my adapter.
i can not find error.
any body can't help me?
what should I do?

this is my error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                           at com.a700daneh.a700daneh.loanFragment.onCreateView(loanFragment.java:49)

this is my element for using in listView

public class Item {

String family1;
String cost1;
String family2;
String cost2;
String explain;
String code;
int Icon;

private View.OnClickListener requestBtnClickListener;

public Item() {
}

public Item(String family1, String cost1, String family2, String cost2, String explain, String code, int Icon) {
    this.family1 = family1;
    this.cost1 = cost1;
    this.family2 = family2;
    this.cost2 = cost2;
    this.explain = explain;
    this.code = code;
    this.Icon = Icon;
    //this.time = time;
}

public String getFamily1() {
    return family1;
}

public void setFamily1(String family1) {
    this.family1 = family1;
}

public String getCost1() {
    return cost2;
}

public void setCost1(String cost2) {
    this.cost2 = cost2;
}

public String getFamily2() {
    return family2;
}

public void setFamily2() {
    this.family2 = family2;
}

public String getCost2() {
    return cost2;
}

public void setCost2() {
    this.cost2 = cost2;
}

public String getExplain() {
    return explain;
}

public void setExplain() {
    this.explain = explain;
}

public String getCode() {
    return code;
}

public void setCode() {
    this.code = code;
}

public int getIcon() {
    return Icon;
}

/**
 * @return List of elements prepared for tests
 */
public static ArrayList<Item> getTestingList() {
    ArrayList<Item> items = new ArrayList<>();
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    items.add(new Item("خانواده x:", "500,000 تومان", "خانواده x:", "500,000 تومان", "توضیحات:", "کد: 12345678", R.drawable.family));
    return items;

}

}

this is my adapter called FoldingCellListAdapter

public class FoldingCellListAdapter extends ArrayAdapter<Item> {

private HashSet<Integer> unfoldedIndexes = new HashSet<>();
private View.OnClickListener defaultRequestBtnClickListener;

public FoldingCellListAdapter(Context context, List<Item> objects) {
    super(context, 0, objects);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // get item for selected view
    Item item = getItem(position);
    // if cell is exists - reuse it, if not - create the new one from resource
    FoldingCell cell = (FoldingCell) convertView;
    ViewHolder viewHolder;
    if (cell == null) {
        viewHolder = new ViewHolder();
        LayoutInflater vi = LayoutInflater.from(getContext());
        cell = (FoldingCell) vi.inflate(R.layout.cell, parent, false);
        // binding view parts to view holder
        viewHolder.family1 = (TextView) cell.findViewById(R.id.family1);
        viewHolder.code = (TextView) cell.findViewById(R.id.code);
        viewHolder.family2 = (TextView) cell.findViewById(R.id.family2);
        viewHolder.cost2 = (TextView) cell.findViewById(R.id.cost2);
        viewHolder.explain = (TextView) cell.findViewById(R.id.explain);
        viewHolder.cost1 = (TextView) cell.findViewById(R.id.cost1);
        viewHolder.payment = (TextView) cell.findViewById(R.id.pay);
        viewHolder.familyImage1 = (ImageView) cell.findViewById(R.id.familyImage1);
        viewHolder.pinkback = (ImageView) cell.findViewById(R.id.pinkback);
        viewHolder.familyImage2 = (ImageView) cell.findViewById(R.id.familyImage2);

        cell.setTag(viewHolder);
    } else {
        // for existing cell set valid valid state(without animation)
        if (unfoldedIndexes.contains(position)) {
            cell.unfold(true);
        } else {
            cell.fold(true);
        }
        viewHolder = (ViewHolder) cell.getTag();
    }

    // bind data from selected element to view through view holder
    viewHolder.family1.setText(item.getFamily1());
    //viewHolder.time.setText(item.getTime());
    viewHolder.code.setText(item.getCode());
    viewHolder.family2.setText(item.getFamily2());
    viewHolder.cost2.setText(item.getCost2());
    viewHolder.explain.setText(String.valueOf(item.getExplain()));
    viewHolder.cost1.setText(item.getCost1());
    viewHolder.familyImage1.setImageResource(item.getIcon());
    viewHolder.familyImage2.setImageResource(item.getIcon());
    viewHolder.pinkback.setImageResource(item.getIcon());

    return cell;
}

// simple methods for register cell state changes
public void registerToggle(int position) {
    if (unfoldedIndexes.contains(position))
        registerFold(position);
    else
        registerUnfold(position);
}

public void registerFold(int position) {
    unfoldedIndexes.remove(position);
}

public void registerUnfold(int position) {
    unfoldedIndexes.add(position);
}

// View lookup cache
private static class ViewHolder {
    TextView family1;
    TextView payment;
    TextView cost1;
    TextView family2;
    TextView cost2;
    TextView explain;
    TextView code;
    ImageView familyImage1;
    ImageView pinkback;
    ImageView familyImage2;
}

}

this is my codes in loanFragment

public class loanFragment extends Fragment {

public loanFragment() {
    // Required empty public constructor
}

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

    ListView lvlist = (ListView) view.findViewById(R.id.lvlist);

    final ArrayList<Item> items = Item.getTestingList();

    // create custom adapter that holds elements and their state (we need hold a id's of unfolded elements for reusable elements)
    final FoldingCellListAdapter adapter = new FoldingCellListAdapter(getContext(), items);

    // set elements to adapter
    lvlist.setAdapter(adapter);

    // set on click event listener to list view
    lvlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
            // toggle clicked cell state
            ((FoldingCell) view).toggle(false);
            // register in adapter that state for selected cell is toggled
            adapter.registerToggle(pos);
        }
    });

    return view;

}

}

I had a layout called cell_content_layout for foldingcell and another layout called cell_title_layout and include these layouts in one layout called cell.

cell_title_content

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:baselineAligned="false"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:id="@+id/cell_title_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/cell_content_view"
        android:layout_toRightOf="@+id/cell_content_view">

        <FrameLayout
            android:id="@+id/familyFrame"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="#dd0f70">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="100dp" />

            <ImageView
                android:id="@+id/familyImage1"
                app:srcCompat="@drawable/family"
                android:layout_width="100dp"
                android:layout_height="109dp"
                android:layout_alignParentBottom="true"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1"
                android:visibility="visible" />

        </FrameLayout>

        <FrameLayout
            android:id="@+id/textFrame1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#d3d8dd">

            <LinearLayout
                android:id="@+id/textLinear1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                android:id="@+id/family1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginRight="18dp"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:text="۱. خانواده x"
                android:textSize="18dp" />

                <TextView
                android:id="@+id/cost1"
                android:layout_width="match_parent"
                android:layout_height="51dp"
                android:layout_marginRight="18dp"
                android:gravity="center_vertical"
                android:text="۵۰۰,۰۰۰  تومان"
                android:textSize="18dp" />
            </LinearLayout>

            <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp" />

        </FrameLayout>

    </LinearLayout>
</LinearLayout>

cell_content_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:visibility="gone"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:id="@+id/cell_content_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:background="#ffffff"
        android:orientation="vertical"
        >

        <FrameLayout
            android:id="@+id/textFrame2"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:background="#d3d8dd">

            <ImageView
                android:id="@+id/pinkback"
                android:layout_width="100dp"
                android:layout_height="109dp"
                android:layout_alignParentBottom="true"
                android:layout_gravity="left"
                android:layout_weight="1"
                android:background="#dd0f70"
                android:visibility="visible" />

            <ImageView
                android:id="@+id/familyImage2"
                android:layout_width="100dp"
                android:layout_height="109dp"
                android:layout_alignParentBottom="true"
                android:layout_gravity="left"
                android:layout_weight="1"
                android:visibility="visible"
                app:srcCompat="@drawable/family" />

            <LinearLayout
                android:id="@+id/textLinear2"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/family2"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginRight="18dp"
                    android:layout_weight="1"
                    android:gravity="center_vertical"
                    android:text="۱. خانواده x"
                    android:textSize="18dp" />

                <TextView
                    android:id="@+id/cost2"
                    android:layout_width="match_parent"
                    android:layout_height="51dp"
                    android:layout_marginRight="18dp"
                    android:gravity="center_vertical"
                    android:text="۵۰۰,۰۰۰  تومان"
                    android:textSize="18dp" />
            </LinearLayout>

        </FrameLayout>

        <FrameLayout
            android:id="@+id/containFrame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

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

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </FrameLayout>

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </FrameLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

            </LinearLayout>
        </FrameLayout>

        <FrameLayout
        android:id="@+id/frameContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <TextView
                android:id="@+id/explain"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:layout_marginRight="18dp"
                android:layout_marginTop="15dp"
                android:layout_weight="1.00"
                android:gravity="right"
                android:text="توضیحات:" />

            <TextView
                android:id="@+id/code"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="18dp"
                android:layout_weight="0.99"
                android:gravity="right"
                android:text="کد: ۱۲۳۴۵۶۷۸۹" />

            <Button
                android:id="@+id/pay"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="5dp"
                android:background="@drawable/button_style2"
                android:text="پرداخت"
                android:textColor="@color/white"
                android:textSize="16dp" />

        </LinearLayout>
    </FrameLayout>

    <TextView
        android:id="@+id/textView6"
        android:layout_width="match_parent"
        android:layout_height="0dp" />

</LinearLayout>

cell

<?xml version="1.0" encoding="utf-8"?>

<com.ramotion.foldingcell.FoldingCell

    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/folding_cell_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="10dp"
    android:clipChildren="false"
    android:clipToPadding="false">

    <include
        android:id="@+id/include"
        layout="@layout/cell_content_layout"
        android:visibility="gone" />

    <include
        layout="@layout/cell_title_layout"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/include" />

</com.ramotion.foldingcell.FoldingCell>


问:
Random element from unordered_set in O(1)
I've seen people mention that a random element can be grabbed from an unordered_set in O(1) time.  I attempted to do so with this:

```<code>std::unordered_set<TestObject*> test_set;

//fill with data

size_t index = rand() % test_set.size();
const TestObject* test = *(test_set.begin() + index);
</code>```

However, unordered_set iterators don't support + with an integer.  begin can be given a size_t param, but it is the index of a bucket rather than an element.  Randomly picking a bucket then randomly picking an element within it would result in a very unbalanced random distribution.

What's the secret to proper O(1) random access?  If it matters, this is in VC++ 2010.

答:
I wrote a solution using buck_count() and cbegin(n) methods, to choose a bucket at random, and then choose an element at random in the bucket.

Two problems:
 - this is not constant time (worse case with a lot of empty buckets and many  elements in one bucket)
 - the probability distribution is skewed

I think that the only way to peek an element at random is to maintain a separate container providing a random access iterator.

```<code>#include <random>
#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <cassert>

using namespace std;

ranlux24_base randomEngine(5);

int rand_int(int from, int to)
{
    assert(from <= to);

    return uniform_int_distribution<int>(from, to)(randomEngine);
}

int random_peek(const unordered_set<int> & container)
{
    assert(container.size() > 0);

    auto b_count = container.bucket_count();
    auto b_idx = rand_int(0, b_count - 1);
    size_t b_size = 0;

    for (int i = 0; i < b_count; ++i)
    {
        b_size = container.bucket_size(b_idx);
        if (b_size > 0)
            break;

        b_idx = (b_idx + 1) % b_count;
    }

    auto idx = rand_int(0, b_size - 1);

    auto it = container.cbegin(b_idx);

    for (int i = 0; i < idx; ++i)
    {
        it++;
    }

    return *it;
}

int main()
{
    unordered_set<int> set;

    for (int i = 0; i < 1000; ++i)
    {
        set.insert(rand_int(0, 100000));
    }

    unordered_map<int,int> distribution;

    const int N = 1000000;
    for (int i = 0; i < N; ++i)
    {
        int n = random_peek(set);
        distribution[n]++;
    }

    int min = N;
    int max = 0;

    for (auto & [n,count]: distribution)
    {
        if (count > max)
            max = count;
        if (count < min)
            min = count;
    }

    cout << "Max=" << max << ", Min=" << min << "\n";
    return 0;
}
</code>```

Body:
I've seen people mention that a random element can be grabbed from an unordered_set in O(1) time.  I attempted to do so with this:

std::unordered_set<TestObject*> test_set;

//fill with data

size_t index = rand() % test_set.size();
const TestObject* test = *(test_set.begin() + index);

However, unordered_set iterators don't support + with an integer.  begin can be given a size_t param, but it is the index of a bucket rather than an element.  Randomly picking a bucket then randomly picking an element within it would result in a very unbalanced random distribution.

What's the secret to proper O(1) random access?  If it matters, this is in VC++ 2010.

Body:
I wrote a solution using buck_count() and cbegin(n) methods, to choose a bucket at random, and then choose an element at random in the bucket.

Two problems:
 - this is not constant time (worse case with a lot of empty buckets and many  elements in one bucket)
 - the probability distribution is skewed

I think that the only way to peek an element at random is to maintain a separate container providing a random access iterator.

#include <random>
#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <cassert>

using namespace std;

ranlux24_base randomEngine(5);

int rand_int(int from, int to)
{
    assert(from <= to);

    return uniform_int_distribution<int>(from, to)(randomEngine);
}

int random_peek(const unordered_set<int> & container)
{
    assert(container.size() > 0);

    auto b_count = container.bucket_count();
    auto b_idx = rand_int(0, b_count - 1);
    size_t b_size = 0;

    for (int i = 0; i < b_count; ++i)
    {
        b_size = container.bucket_size(b_idx);
        if (b_size > 0)
            break;

        b_idx = (b_idx + 1) % b_count;
    }

    auto idx = rand_int(0, b_size - 1);

    auto it = container.cbegin(b_idx);

    for (int i = 0; i < idx; ++i)
    {
        it++;
    }

    return *it;
}

int main()
{
    unordered_set<int> set;

    for (int i = 0; i < 1000; ++i)
    {
        set.insert(rand_int(0, 100000));
    }

    unordered_map<int,int> distribution;

    const int N = 1000000;
    for (int i = 0; i < N; ++i)
    {
        int n = random_peek(set);
        distribution[n]++;
    }

    int min = N;
    int max = 0;

    for (auto & [n,count]: distribution)
    {
        if (count > max)
            max = count;
        if (count < min)
            min = count;
    }

    cout << "Max=" << max << ", Min=" << min << "\n";
    return 0;
}


问:
How send data from fragment in TabLayout to MainActivity?
I have a TabLayout with two tabs and a MainActivity.
 How can I send data from fragment1 which placed in tab1 to MainActivity?

答:
If you are calling an activity from a fragment and you want to send data to Activity you can use intents like below:

```<code>  Intent intent = new Intent(getActivity(), YourActivity.class);
    String name = "Transporter";
    intent.putExtra("name", name);
    startActivity(intent);
</code>```

And in your activity you should get the data like this:

```<code> try {

         Intent intent = getIntent();
         String name = intent.getStringExtra("name");

        } catch(Exception e) {
         e.printStackTrace();
    }
</code>```

Body:
If you are calling an activity from a fragment and you want to send data to Activity you can use intents like below:

  Intent intent = new Intent(getActivity(), YourActivity.class);
    String name = "Transporter";
    intent.putExtra("name", name);
    startActivity(intent);

And in your activity you should get the data like this:

 try {

         Intent intent = getIntent();
         String name = intent.getStringExtra("name");

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


问:
How to use sparse arrays with C3 charts?
For graphing in C3, we can give it column data, which is an array of arrays with each array being a different line on the chart like in this C3 docs example. But is there a way to have that column data sparse? I'm getting an error when I try that, although I'm not sure if there's a workaround I don't know about.

If not, is there a better way to convert between sparse and dense arrays than a filter function like what I have?

https://jsfiddle.net/dbkidd/majx8byn/

```<code>var columnData = []

var entry1 = ['data1', 30, 200, 100, 400, 150, 250];
var entry2 = ['data2', 50, 20, 10, 40, 15, 25];

columnData[0] = entry1;
columnData[3] = entry2;
console.log('columnData - sparse format', JSON.stringify(columnData));

function checkIfUndefined(x) {
    return (x !== undefined);
}

function sparseToDense(data) {
  return data.filter(checkIfUndefined);
}

/* If you comment out this sparseToDense conversion, it breaks
 * with the following error:
 * c3.js:5403 Uncaught TypeError: Cannot read property '0' of undefined
*/
columnData = sparseToDense(columnData);
console.log('columnData - dense format', JSON.stringify(columnData));

var chart = c3.generate({
    data: {
        columns: columnData,
        axes: {
            data1: 'y',
            data2: 'y2'
        }
    },
    axis: {
        y2: {
            show: true
        }
    }
});
</code>```

答:
You can use empty array as entry value. This works ok:

```<code>[["data1",30,200,100,400,150,250],[],[],["data2",50,20,10,40,15,25]]
</code>```

And modify your filtering function to skip arrays without length:

```<code>function checkIfNull(x) {
    return (x.length);
}
</code>```

See updated fiddle

Body:
For graphing in C3, we can give it column data, which is an array of arrays with each array being a different line on the chart like in this C3 docs example. But is there a way to have that column data sparse? I'm getting an error when I try that, although I'm not sure if there's a workaround I don't know about.

If not, is there a better way to convert between sparse and dense arrays than a filter function like what I have?

https://jsfiddle.net/dbkidd/majx8byn/

var columnData = []

var entry1 = ['data1', 30, 200, 100, 400, 150, 250];
var entry2 = ['data2', 50, 20, 10, 40, 15, 25];

columnData[0] = entry1;
columnData[3] = entry2;
console.log('columnData - sparse format', JSON.stringify(columnData));

function checkIfUndefined(x) {
    return (x !== undefined);
}

function sparseToDense(data) {
  return data.filter(checkIfUndefined);
}

/* If you comment out this sparseToDense conversion, it breaks
 * with the following error:
 * c3.js:5403 Uncaught TypeError: Cannot read property '0' of undefined
*/
columnData = sparseToDense(columnData);
console.log('columnData - dense format', JSON.stringify(columnData));

var chart = c3.generate({
    data: {
        columns: columnData,
        axes: {
            data1: 'y',
            data2: 'y2'
        }
    },
    axis: {
        y2: {
            show: true
        }
    }
});

Body:
You can use empty array as entry value. This works ok:

[["data1",30,200,100,400,150,250],[],[],["data2",50,20,10,40,15,25]]

And modify your filtering function to skip arrays without length:

function checkIfNull(x) {
    return (x.length);
}

See updated fiddle


问:
Xtend syntax clarification
I'm trying to 100% understand that the following Xtend syntax means:

```<code>        myVar.addSelectionListener(
           [MultiSelectionEvent<String> event |
               println(event.toString)
           ]
        )
</code>```

myVar is a com.vaadin.ui.CheckBoxGroup class

the addSelectionListener assume to receive a
com.vaadin.event.selection.MultiSelectionListener interface

When implementing the MultiSelectionListenener, one has to implement a selectionChange method which itself takes a MultSelectionEvent object as parameter.

I understand that in my above code, I'm providing the implementation inline in my code. But could anyone provide more details about the syntax?

For example, when do we use [ ], or | in Xtend?

答:
That is Xtend's lambda syntax. So in Java you would write:

```<code>    myVar.addSelectionListener(
       (MultiSelectionEvent<String> event) -> {
           println(event.toString)
       }
    );
</code>```

Xtend simply replaces (params)=>{code} with [<params>|].

Title: Xtend syntax clarification

Body:
I'm trying to 100% understand that the following Xtend syntax means:

        myVar.addSelectionListener(
           [MultiSelectionEvent<String> event |
               println(event.toString)
           ]
        )

myVar is a com.vaadin.ui.CheckBoxGroup class

the addSelectionListener assume to receive a
com.vaadin.event.selection.MultiSelectionListener interface

When implementing the MultiSelectionListenener, one has to implement a selectionChange method which itself takes a MultSelectionEvent object as parameter.

I understand that in my above code, I'm providing the implementation inline in my code. But could anyone provide more details about the syntax?

For example, when do we use [ ], or | in Xtend?

Body:
That is Xtend's lambda syntax. So in Java you would write:

    myVar.addSelectionListener(
       (MultiSelectionEvent<String> event) -> {
           println(event.toString)
       }
    );

Xtend simply replaces (params)=>{code} with [<params>|<code>].


问:
cron job not running inside docker container on ubuntu
I have a simple Dockerfile as follows

```<code>FROM ubuntu:latest

ADD crontab /etc/cron.d/test-cron

RUN chmod a+x /etc/cron.d/test-cron
RUN touch /var/log/cron.log

CMD cron && tail -f /var/log/cron.log
</code>```

and the content of crontab file is as simple as

```<code>* * * * * root echo "Hello world" >> /var/log/cron.log 2>&1
# empty line
</code>```

When I run this on my local OS X machine (with docker-machine running), it works fine ("Hello world" is printed to log file every minute). However, when I try to run it on an Ubuntu machine, the cron job does not run (empty log file).

Here's the command I use to run the container

```<code>docker build -t crontest .
docker run --name cron crontest
</code>```

I am not sure why this would be the case. I wonder if something is wrong with the Ubuntu box that I have (wrong time setting?). I have tried to restart that machine to no effect. I currently do have other docker containers running on the Ubuntu box and they're running fine.

Any suggestion on what I could do to debug/ fix this would be hugely appreciated.

EDIT:

After going inside the container (docker exec -it cron /bin/bash), I can verify that cron is running there:

```<code>root@a2ad451af8d9:/# ps -ef | grep cron
root         1     0  0 20:15 ?        00:00:00 /bin/sh -c cron && tail -f /var/log/cron.log
root         6     1  0 20:15 ?        00:00:00 cron
root         7     1  0 20:15 ?        00:00:00 tail -f /var/log/cron.log
root        25    11  0 20:21 ?        00:00:00 grep --color=auto cron
</code>```

答:
I had a backup script called backup.sh that I copied to /etc/cron.daily.
The script was not called properly.

To make it to I had to rename to the to just backup without the .sh

So for me ls -l /etc/cron.daily had the following output:

```<code>root@0989a35b8f94:/# ls -l /etc/cron.daily
total 24
-rwxr-xr-x 1 root root 1474 Sep 13 16:47 apt-compat
-rwxrwxr-x 1 root root   45 Nov  9 11:18 dobackup
-rwxr-xr-x 1 root root 1597 Feb 22  2017 dpkg
-rwxr-xr-x 1 root root 4125 Mar  2  2016 exim4-base
-rwxr-xr-x 1 root root  249 May 17 11:59 passwd
</code>```

To test/analyse this I used the following approach:

I looked up the crontab file cat /etc/crontab showing the following line for the daily cronjobs:

```<code>25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
</code>```

I then isolated my backup script into a dedicated folder:

```<code>mkdir /etc/cron.test
mv /etc/cron.daily/dobackup /etc/cron.test
</code>```

Then by running

```<code>test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.test)
</code>```

and using ps auxf on a different terminal showed me that the jobs now is running. You can also verify that it breaks when renaming to the .sh version:

```<code>mv /etc/cron.test/dobackup /etc/cron.test/dobackup.sh
test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.test)
</code>```

It then exists immediately, so no job is run.

Body:
I have a simple Dockerfile as follows

FROM ubuntu:latest

ADD crontab /etc/cron.d/test-cron

RUN chmod a+x /etc/cron.d/test-cron
RUN touch /var/log/cron.log

CMD cron && tail -f /var/log/cron.log

and the content of crontab file is as simple as

* * * * * root echo "Hello world" >> /var/log/cron.log 2>&1
# empty line

When I run this on my local OS X machine (with docker-machine running), it works fine ("Hello world" is printed to log file every minute). However, when I try to run it on an Ubuntu machine, the cron job does not run (empty log file).

Here's the command I use to run the container

docker build -t crontest .
docker run --name cron crontest

I am not sure why this would be the case. I wonder if something is wrong with the Ubuntu box that I have (wrong time setting?). I have tried to restart that machine to no effect. I currently do have other docker containers running on the Ubuntu box and they're running fine.

Any suggestion on what I could do to debug/ fix this would be hugely appreciated.

EDIT:

After going inside the container (docker exec -it cron /bin/bash), I can verify that cron is running there:

root@a2ad451af8d9:/# ps -ef | grep cron
root         1     0  0 20:15 ?        00:00:00 /bin/sh -c cron && tail -f /var/log/cron.log
root         6     1  0 20:15 ?        00:00:00 cron
root         7     1  0 20:15 ?        00:00:00 tail -f /var/log/cron.log
root        25    11  0 20:21 ?        00:00:00 grep --color=auto cron

Body:
I had a backup script called backup.sh that I copied to /etc/cron.daily.
The script was not called properly.

To make it to I had to rename to the to just backup without the .sh

So for me ls -l /etc/cron.daily had the following output:

root@0989a35b8f94:/# ls -l /etc/cron.daily
total 24
-rwxr-xr-x 1 root root 1474 Sep 13 16:47 apt-compat
-rwxrwxr-x 1 root root   45 Nov  9 11:18 dobackup
-rwxr-xr-x 1 root root 1597 Feb 22  2017 dpkg
-rwxr-xr-x 1 root root 4125 Mar  2  2016 exim4-base
-rwxr-xr-x 1 root root  249 May 17 11:59 passwd

To test/analyse this I used the following approach:

I looked up the crontab file cat /etc/crontab showing the following line for the daily cronjobs:

25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )

I then isolated my backup script into a dedicated folder:

mkdir /etc/cron.test
mv /etc/cron.daily/dobackup /etc/cron.test

Then by running

test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.test)

and using ps auxf on a different terminal showed me that the jobs now is running. You can also verify that it breaks when renaming to the .sh version:

mv /etc/cron.test/dobackup /etc/cron.test/dobackup.sh
test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.test)

It then exists immediately, so no job is run.


问:
Visual Studio Code intellisense shows ng-model rather than ngModel
I am using Visual Studio Code for Angular, VS code intelisense shows ng-model rather than ngModel. Do I need to update something or something else?
Please tell the solution. Thanks

答: Right now, it doesn't look like there's an extension for it, yet - likely due to gaps in the extension API which are currently in development.</p>


问:
How to call an external function inside a view in laravel 5.2
I want to call an external function from my blade view.

I have tried in this way,

```<code>{{ controllername::function name()}}
</code>```

But i get a response like Class 'controllername' not found.

How i can solve this?Looking for a solution.

答:
If you are on Laravel 5.5, there is a way to do that using Service Injection. A verbatim copied example from the doc:

```<code>@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>
</code>```

If you are not Using L5.5, then you can /Use/The/Path/OfTheClass, so that the example above will be:

```<code><div>
    Monthly Revenue: {{ \App\Services\MetricsService::monthlyRevenue() }}.
</div>
</code>```

Beware that, in this case monthlyRevenue() has to be a static function, which is sensible.

Otherwise, its much advisable to ensure the function that returns your view already did the work you need in theFunction() and then pass it as value to the view directly.

Also Its hard to understand why you'll need your controller function in your view in the first place. Perhaps you need to check if your are not doing something wrong.

Body:
I want to call an external function from my blade view.

I have tried in this way,

{{ controllername::function name()}}

But i get a response like Class 'controllername' not found.

How i can solve this?Looking for a solution.

Body:
If you are on Laravel 5.5, there is a way to do that using Service Injection. A verbatim copied example from the doc:

@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

If you are not Using L5.5, then you can /Use/The/Path/OfTheClass, so that the example above will be:

<div>
    Monthly Revenue: {{ \App\Services\MetricsService::monthlyRevenue() }}.
</div>

Beware that, in this case monthlyRevenue() has to be a static function, which is sensible.

Otherwise, its much advisable to ensure the function that returns your view already did the work you need in theFunction() and then pass it as value to the view directly.

Also Its hard to understand why you'll need your controller function in your view in the first place. Perhaps you need to check if your are not doing something wrong.


问:
How to download different sizes of an image from Twitter?
I'm using the Twitter Streaming API to get images included in tweets, and show them in my Android app. The media object which represents the image contains a media_url field that is a direct link to the image, and a JSON objects named sizes which contains the different sizes available for that image. The question is, how can I get such resized images? I want to download the thumbnail directly from Twitter, and since the sizes object contains a thumb field it should be possible, but how? I already tried to concat ?size=thumb to the media_url but it didn't work.
Media object example:</p>

```<code>{"id":897839774635053000,"id_str":"897839774635053056","indices":
[75,98],"media_url":"http://pbs.twimg.com/media/DHXEhKBW0AAKhf3.jpg",
"media_url_https":"https://pbs.twimg.com/media/DHXEhKBW0AAKhf3.jpg",
"url":"https://REMOVED/4NcW6720Zj","display_url":"pic.twitter.com/4NcW6720Zj",
"expanded_url":
"https://twitter.com/darioolly/status/897840123924164608/photo/1",
"type":"photo",

"sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},
         "medium":{"w":720,"h":711,"resize":"fit"},
         "small":{"w":680,"h":672,"resize":"fit"},
         "large":{"w":720,"h":711,"resize":"fit"}}}
</code>```

答:
You can retrieve the media in different sizes by appending a colon + the size key, as specified here

We support different sizes: thumb, small, medium and large. The media_url defaults to medium but you can retrieve the media in different sizes by appending a colon + the size key (for example: http://pbs.twimg.com/media/A7EiDWcCYAAZT1D.jpg:thumb ). Each available size comes with three attributes that describe it: w : the width (in pixels) of the media in this particular size; h : the height (in pixels) of the media in this particular size; resize : how we resized the media to this particular size (can be crop or fit )

Body:
I'm using the Twitter Streaming API to get images included in tweets, and show them in my Android app. The media object which represents the image contains a media_url field that is a direct link to the image, and a JSON objects named sizes which contains the different sizes available for that image. The question is, how can I get such resized images? I want to download the thumbnail directly from Twitter, and since the sizes object contains a thumb field it should be possible, but how? I already tried to concat ?size=thumb to the media_url but it didn't work.
Media object example:

{"id":897839774635053000,"id_str":"897839774635053056","indices":
[75,98],"media_url":"http://pbs.twimg.com/media/DHXEhKBW0AAKhf3.jpg",
"media_url_https":"https://pbs.twimg.com/media/DHXEhKBW0AAKhf3.jpg",
"url":"https://REMOVED/4NcW6720Zj","display_url":"pic.twitter.com/4NcW6720Zj",
"expanded_url":
"https://twitter.com/darioolly/status/897840123924164608/photo/1",
"type":"photo",

"sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},
         "medium":{"w":720,"h":711,"resize":"fit"},
         "small":{"w":680,"h":672,"resize":"fit"},
         "large":{"w":720,"h":711,"resize":"fit"}}}


问:
How to get data from an array where length is not fixed
Having an array where length of the array is getting changes(may be increase/may be decrease) but minimum length is 1.
Key values are constant for each index of array like below

```<code>Myarr =  [
  {stdid:1, stddesc:"",coursedetails:"xyz"},
  {stdid:2, stddesc:"ccc",coursedetails:"abc"},.......
]
</code>```

I want to fetch stdid for all the available index.

Can anyone help me here.

答:
You can use ES6 map operator.

Myarr = [{
  stdid: 1,
  stddesc: "",
  coursedetails: "xyz"
}, {
  stdid: 2,
  stddesc: "ccc",
  coursedetails: "abc"
}]
let idArr = Myarr.map(x => x.stdid);
console.log(idArr);```

Body:
Having an array where length of the array is getting changes(may be increase/may be decrease) but minimum length is 1.
Key values are constant for each index of array like below

Myarr =  [
  {stdid:1, stddesc:"",coursedetails:"xyz"},
  {stdid:2, stddesc:"ccc",coursedetails:"abc"},.......
]

I want to fetch stdid for all the available index.

Can anyone help me here.


问:
Java Spring SQL how to combine/join 3 tables into one
I have 3 tables that I want to combine/join into one, I have tried different methods like join, left/right join but somehow i lose myself in the amount of statements i write so i cant get it to work properly.

I want to map the name in measurement to measurement_id in measurement_data_points and then map data_points_id in measurement_data_points to id in measurement_point

I have included a made-up result that i would like at the bottom to give a clear understanding.

My Tables:

```<code>+-------------------------+
| Tables_in_db_datapoints |
+-------------------------+
| measurement             |
| measurement_data_points |
| measurement_point       |
+-------------------------+
</code>```

measurement table

```<code>mysql> select * from measurement;
+----+----------------------+
| id | name                 |
+----+----------------------+
|  1 | identifiedNeed       |
|  2 | identifiedBackground |
|  3 | identifiedGoal       |
+----+----------------------+
</code>```

measurement_data_points table

```<code>mysql> select * from measurement_data_points;
+----------------+----------------+
| measurement_id | data_points_id |
+----------------+----------------+
|              1 |              1 |
|              1 |              2 |
|              1 |              3 |
|              1 |              4 |
|              2 |              5 |
|              2 |              6 |
|              2 |              7 |
|              2 |              8 |
|              3 |              9 |
|              3 |             10 |
|              3 |             11 |
|              3 |             12 |
+----------------+----------------+
</code>```

measurement_point table

```<code>+----+------------+-----+----------+--------+
| id | date       | f1  | precison | recall |
+----+------------+-----+----------+--------+
|  1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|  2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|  3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|  4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|  5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|  6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|  7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|  8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|  9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| 10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| 11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| 12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----+------------+-----+----------+--------+
</code>```

I want the result to mainly be like this:

```<code>+-----------------------+----------------+------------+-----+----------+
| measurement_id        | data_points_id |  date      | f1  | precison | recall |
+-----------------------+----------------+------------+-----+----------+
| identifiedNeed        |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
| identifiedNeed        |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
| identifiedNeed        |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1
| identifiedNeed        |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
| identifiedBackground  |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
| identifiedBackground  |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedBackground  |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
| identifiedBackground  |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
| identifiedGoal        |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| identifiedGoal        |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedGoal        |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| identifiedGoal        |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+-----------------------+----------------+------------+-----+----------+
</code>```

If that doesnt work then this works as well

```<code>+----------------+----------------+------------+-----+----------+--------+
| measurement_id | data_points_id | date       | f1  | precison | recall |
+----------------+----------------+------------+-----+----------+--------+
|              1 |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|              1 |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|              1 |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|              1 |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|              2 |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|              2 |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              2 |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|              2 |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|              3 |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
|              3 |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              3 |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
|              3 |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----------------+----------------+------------+-----+----------+--------+
</code>```

答:
SELECT a.name AS measurement_id,
       b.data_points_id,
       c.date,
       c.f1,
       c.precision,
       c.recall
FROM measurement a,
     measurement_data_points b,
     measurement_point c
WHERE a.id = b.measurement_id
  AND b.measurement_id = c.measurement_id;</p>

Body:
I have 3 tables that I want to combine/join into one, I have tried different methods like join, left/right join but somehow i lose myself in the amount of statements i write so i cant get it to work properly.

I want to map the name in measurement to measurement_id in measurement_data_points and then map data_points_id in measurement_data_points to id in measurement_point

I have included a made-up result that i would like at the bottom to give a clear understanding.

My Tables:

+-------------------------+
| Tables_in_db_datapoints |
+-------------------------+
| measurement             |
| measurement_data_points |
| measurement_point       |
+-------------------------+

measurement table

mysql> select * from measurement;
+----+----------------------+
| id | name                 |
+----+----------------------+
|  1 | identifiedNeed       |
|  2 | identifiedBackground |
|  3 | identifiedGoal       |
+----+----------------------+

measurement_data_points table

mysql> select * from measurement_data_points;
+----------------+----------------+
| measurement_id | data_points_id |
+----------------+----------------+
|              1 |              1 |
|              1 |              2 |
|              1 |              3 |
|              1 |              4 |
|              2 |              5 |
|              2 |              6 |
|              2 |              7 |
|              2 |              8 |
|              3 |              9 |
|              3 |             10 |
|              3 |             11 |
|              3 |             12 |
+----------------+----------------+

measurement_point table

+----+------------+-----+----------+--------+
| id | date       | f1  | precison | recall |
+----+------------+-----+----------+--------+
|  1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|  2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|  3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|  4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|  5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|  6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|  7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|  8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|  9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| 10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| 11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| 12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----+------------+-----+----------+--------+

I want the result to mainly be like this:

+-----------------------+----------------+------------+-----+----------+
| measurement_id        | data_points_id |  date      | f1  | precison | recall |
+-----------------------+----------------+------------+-----+----------+
| identifiedNeed        |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
| identifiedNeed        |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
| identifiedNeed        |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1
| identifiedNeed        |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
| identifiedBackground  |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
| identifiedBackground  |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedBackground  |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
| identifiedBackground  |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
| identifiedGoal        |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| identifiedGoal        |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedGoal        |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| identifiedGoal        |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+-----------------------+----------------+------------+-----+----------+

If that doesnt work then this works as well

+----------------+----------------+------------+-----+----------+--------+
| measurement_id | data_points_id | date       | f1  | precison | recall |
+----------------+----------------+------------+-----+----------+--------+
|              1 |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|              1 |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|              1 |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|              1 |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|              2 |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|              2 |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              2 |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|              2 |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|              3 |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
|              3 |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              3 |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
|              3 |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----------------+----------------+------------+-----+----------+--------+


问:
"None" included in program output... why?
i've searched the forum and found similar questions, but no luck in solving my problem.

My code is designed to swap every two letters of each word using recursion and print the result. For words with an even amount of letters, the word "None" is included in the output and i don't know how to fix...

here's the code:

```<code>def encryptLine(line, count):
    headline = line[count:]

    if length(headline) > 0:
        if count == length(line) - 1:
            new = headline
            return new
        elif count <= length(line):
            new = head(tail(headline)) + head(headline)
        new = new + str(encryptLine(line, count+2))
        return new

print(encryptLine('abcd', 0))
</code>```

the output for 'abcd' is badcNone, which is correct except for the word None. the output for 'abcde' is 'badce', which is correct...

thanks in advance for your help!

答:
Add return "" to the function definition, that is

```<code>def encryptLine(line, count):
    headline = line[count:]

    if length(headline) > 0:
        if count == length(line) - 1:
            new = headline
            return new
        elif count <= length(line):
            new = head(tail(headline)) + head(headline)
        new = new + str(encryptLine(line, count+2))
        return new
    return ""
</code>```

Otherwise, the function will return None if length(headline) > 0 does not hold.

ContentLicense: CC BY-SA 2.5

Body:
i've searched the forum and found similar questions, but no luck in solving my problem.

My code is designed to swap every two letters of each word using recursion and print the result. For words with an even amount of letters, the word "None" is included in the output and i don't know how to fix...

here's the code:

def encryptLine(line, count):
    headline = line[count:]

    if length(headline) > 0:
        if count == length(line) - 1:
            new = headline
            return new
        elif count <= length(line):
            new = head(tail(headline)) + head(headline)
        new = new + str(encryptLine(line, count+2))
        return new

print(encryptLine('abcd', 0))

the output for 'abcd' is badcNone, which is correct except for the word None. the output for 'abcde' is 'badce', which is correct...

thanks in advance for your help!

Body:
Add return "" to the function definition, that is

def encryptLine(line, count):
    headline = line[count:]

    if length(headline) > 0:
        if count == length(line) - 1:
            new = headline
            return new
        elif count <= length(line):
            new = head(tail(headline)) + head(headline)
        new = new + str(encryptLine(line, count+2))
        return new
    return ""

Otherwise, the function will return None if length(headline) > 0 does not hold.


问:
Angularjs failed to load template after build
After i my build my angular app its showing me this error [$compile:tpload] Failed to load template: app/app.html (HTTP status: 404 Not Found). Please guys help me out!!!!!

app.html

```<code><div class="root">
    <div ui-view></div>
</div>
</code>```

app.component.js

```<code>    (function(angular) {
    'use strict'
    var app = {
        templateUrl:"app/app.html"
    }
    angular.module('mainApp')
           .component('app',app);
})(window.angular);
</code>```

index.html

```<code><!doctype html>
<html class="no-js" lang="" ng-app="mainApp">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <title>IES</title>
      <!-- Place favicon.ico in the root directory -->
    <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->

    <!-- build:css({.tmp/serve,src}) styles/vendor.css -->
    <!-- bower:css -->
    <!-- run `gulp inject` to automatically populate bower styles dependencies -->
    <!-- endbower -->
    <!-- endbuild -->

    <!-- build:css({.tmp/serve,src}) styles/app.css -->
    <!-- inject:css -->
    <!-- css files will be automatically insert here -->
    <!-- endinject -->
    <!-- endbuild -->
    <!--<script src="bower_components/angular/angular.js"></script>-->
</head>
<body>
    <app></app>
</body>
<!-- build:js(src) scripts/vendor.js -->
<!-- bower:js -->
<!-- run `gulp inject` to automatically populate bower script dependencies -->
<!-- endbower -->
<!-- endbuild -->

<!-- build:js({.tmp/serve,.tmp/partials,src}) scripts/app.js -->
<!-- inject:js -->
<!-- js files will be automatically insert here -->
<!-- endinject -->

<!-- inject:partials -->
<!-- angular templates will be automatically converted in js and inserted here -->
<!-- endinject -->
<!-- endbuild -->
</html>
</code>```

app.module.js

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

      angular.module('mainApp',[
        'components',
        'common',
               ])
      .config(['$httpProvider', function ($httpProvider) {
          $httpProvider.interceptors.push('HeaderInterceptor');
          console.log("Configuration Hook");
        }])

      .run(['$http', '$rootScope', function ($http, $rootScope) {
        if (typeof $rootScope.global === "undefined") {
            if (localStorage.getItem('user')) {
              $rootScope.global = {
                user: JSON.parse(localStorage.getItem('user')),
              }
            }
         }
      }])

    })(window.angular, window.localStorage);
</code>```

If you wanna see the whole code here it is
https://github.com/masresha/testfiles/tree/master/IES/src

答:
app.component.js

```<code>(function(angular) {
'use strict'
var app = {
    templateUrl:"./app.html"
}
angular.module('mainApp')
       .component('app',app);
})(window.angular);
</code>```

You don't need to indicate app folder, you're already in it.

Body:
After i my build my angular app its showing me this error [$compile:tpload] Failed to load template: app/app.html (HTTP status: 404 Not Found). Please guys help me out!!!!!

app.html

app.component.js

    (function(angular) {
    'use strict'
    var app = {
        templateUrl:"app/app.html"
    }
    angular.module('mainApp')
           .component('app',app);
})(window.angular);

index.html

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <title>IES</title>

    <app></app>

app.module.js

 (function(angular) {
      'use strict';

      angular.module('mainApp',[
        'components',
        'common',
               ])
      .config(['$httpProvider', function ($httpProvider) {
          $httpProvider.interceptors.push('HeaderInterceptor');
          console.log("Configuration Hook");
        }])

      .run(['$http', '$rootScope', function ($http, $rootScope) {
        if (typeof $rootScope.global === "undefined") {
            if (localStorage.getItem('user')) {
              $rootScope.global = {
                user: JSON.parse(localStorage.getItem('user')),
              }
            }
         }
      }])

    })(window.angular, window.localStorage);

If you wanna see the whole code here it is
https://github.com/masresha/testfiles/tree/master/IES/src

Body:
app.component.js

(function(angular) {
'use strict'
var app = {
    templateUrl:"./app.html"
}
angular.module('mainApp')
       .component('app',app);
})(window.angular);

You don't need to indicate app folder, you're already in it.


问:
Application's Toolbar is not collapsing when Scrolling RecyclerView inside fragments
Application's Toolbar is not collapsing. Here is my activity_main xml file, how

to collapse the application toolbar. I tried implementing with the bellow code but my code doesn't even collapse and showing something else. If i remove the
android.support.design.widget.CollapsingToolbarLayout tag then I can see my original layout like

This is the view without implementation of CollapsingToolBar.

More about the design is, I have 9 tabs with 9 fragments implemented for each tab with RecyclerView in it. While scrolling the recyclerview upwards the toolbar is not collapsing after implementation of CollapsingToolBar in the activity_main.xml file.

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:theme="@style/ThemeOverlay.AppCompat.Dark">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabIndicatorHeight="2dp"
            app:tabMode="scrollable"
            app:tabMaxWidth="0dp"
            android:theme="@style/MyMaterialTheme"/>
 </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>
    <View
        android:id="@+id/view_line"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#f90404"
        android:layout_below="@+id/appbar"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/view_line">

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

        <FrameLayout
            android:id="@+id/main_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true"
            android:clickable="true"
            android:padding="5dp">

        </FrameLayout>
        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

            <FrameLayout
                android:id="@+id/mensaje_vp_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:clickable="true" />

        </RelativeLayout>
        <android.support.design.widget.NavigationView
            android:id="@+id/navigation"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:fitsSystemWindows="true"
            app:itemBackground="@android:color/transparent"
            app:itemTextColor="#780d0d"
            app:menu="@menu/navigation_drawer_items"
            />

    </android.support.v4.widget.DrawerLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/cartoon"
            android:scaleType="centerCrop"
            app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
            app:layout_collapseMode="parallax" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin" />

    </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="#ffe5e5"
       app:layout_behavior="@string/appbar_scrolling_view_behavior">

       <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical"
         android:paddingTop="10dp">
         <include layout="@layout/card_layout" />
         <include layout="@layout/card_layout" />
         <include layout="@layout/card_layout" />
      </LinearLayout>

  </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>
</code>```

Output

More Reference

Body:
Application's Toolbar is not collapsing. Here is my activity_main xml file, how

to collapse the application toolbar. I tried implementing with the bellow code but my code doesn't even collapse and showing something else. If i remove the
android.support.design.widget.CollapsingToolbarLayout tag then I can see my original layout like

This is the view without implementation of CollapsingToolBar.

More about the design is, I have 9 tabs with 9 fragments implemented for each tab with RecyclerView in it. While scrolling the recyclerview upwards the toolbar is not collapsing after implementation of CollapsingToolBar in the activity_main.xml file.

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

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:theme="@style/ThemeOverlay.AppCompat.Dark">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabIndicatorHeight="2dp"
            app:tabMode="scrollable"
            app:tabMaxWidth="0dp"
            android:theme="@style/MyMaterialTheme"/>
 </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>
    <View
        android:id="@+id/view_line"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#f90404"
        android:layout_below="@+id/appbar"/>

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/view_line">

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

        <FrameLayout
            android:id="@+id/main_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true"
            android:clickable="true"
            android:padding="5dp">

        </FrameLayout>
        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

            <FrameLayout
                android:id="@+id/mensaje_vp_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:clickable="true" />

        </RelativeLayout>
        <android.support.design.widget.NavigationView
            android:id="@+id/navigation"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:fitsSystemWindows="true"
            app:itemBackground="@android:color/transparent"
            app:itemTextColor="#780d0d"
            app:menu="@menu/navigation_drawer_items"
            />

    </android.support.v4.widget.DrawerLayout>

</android.support.design.widget.CoordinatorLayout>

Body:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/cartoon"
            android:scaleType="centerCrop"
            app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
            app:layout_collapseMode="parallax" />

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin" />

    </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="#ffe5e5"
       app:layout_behavior="@string/appbar_scrolling_view_behavior">

       <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical"
         android:paddingTop="10dp">
         <include layout="@layout/card_layout" />
         <include layout="@layout/card_layout" />
         <include layout="@layout/card_layout" />
      </LinearLayout>

  </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

Output

More Reference


问:
How to make tkinter button raised before executing command
Am trying to make GUI app which compulsory you have to select one of predict button before the number entered will be printed to the terminal,if none of predictbutton is selected the should print outselect predict button to proceed.

In pseudecode something like:

```<code>def check:
    now = new.get()
    if no lotto_button is selected:
        print("select predict button to proceed")
    else:
        print(now)
</code>```

But having  challenges:

1:when i select one predict button both buttons raised.

2:How to make the predict compulsory to be selected before the content in the entry will  be printed.

```<code>import tkinter as tk

def terminal():
    now = new.get()
    print(now)

def start_func():
    lotto_button.configure(relief=tk.SUNKEN, state=tk.DISABLED)
    lotto_button1.configure(relief=tk.SUNKEN, state=tk.DISABLED)

def stop_func():
    lotto_button.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lotto_button1.configure(relief=tk.RAISED, state=tk.ACTIVE)

root = tk.Tk()
root.geometry("400x400")

new = tk.StringVar()
en = tk.Entry(root, textvariable=new).pack()

lotto_button = tk.Button(root, text="predict one", command=start_func)
lotto_button.pack(side="left")
lotto_button1 = tk.Button(root, text="predict two", command=start_func)
lotto_button1.pack()

tk.Button(root, text="print number", command=lambda :[stop_func(),
terminal()]).place(x=150, y=300)

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

Thank you and your advice to do is welcome.

答:
When you're clicking on one of the button prediction, both are raised because in your function start_func, you're configuring both.
Instead of configuring both of them you can bind an event click and getting the widget in start_func like this:

```<code>lotto_button = tk.Button(root, text="predict one")
lotto_button.bind('<1>', start_func)
lotto_button.pack(side="left")
</code>```

And then in your start_func :

```<code>def start_func(event):
    w = event.widget
    w.configure(relief=tk.SUNKEN, state=tk.DISABLED)
</code>```

About your second point, I'm not sure to understand what you mean.

Body:
Am trying to make GUI app which compulsory you have to select one of predict button before the number entered will be printed to the terminal,if none of predictbutton is selected the should print outselect predict button to proceed.

In pseudecode something like:

def check:
    now = new.get()
    if no lotto_button is selected:
        print("select predict button to proceed")
    else:
        print(now)

But having  challenges:

1:when i select one predict button both buttons raised.

2:How to make the predict compulsory to be selected before the content in the entry will  be printed.

import tkinter as tk

def terminal():
    now = new.get()
    print(now)

def start_func():
    lotto_button.configure(relief=tk.SUNKEN, state=tk.DISABLED)
    lotto_button1.configure(relief=tk.SUNKEN, state=tk.DISABLED)

def stop_func():
    lotto_button.configure(relief=tk.RAISED, state=tk.ACTIVE)
    lotto_button1.configure(relief=tk.RAISED, state=tk.ACTIVE)

root = tk.Tk()
root.geometry("400x400")

new = tk.StringVar()
en = tk.Entry(root, textvariable=new).pack()

lotto_button = tk.Button(root, text="predict one", command=start_func)
lotto_button.pack(side="left")
lotto_button1 = tk.Button(root, text="predict two", command=start_func)
lotto_button1.pack()

tk.Button(root, text="print number", command=lambda :[stop_func(),
terminal()]).place(x=150, y=300)

root.mainloop()

Thank you and your advice to do is welcome.

Body:
When you're clicking on one of the button prediction, both are raised because in your function start_func, you're configuring both.
Instead of configuring both of them you can bind an event click and getting the widget in start_func like this:

lotto_button = tk.Button(root, text="predict one")
lotto_button.bind('<1>', start_func)
lotto_button.pack(side="left")

And then in your start_func :

def start_func(event):
    w = event.widget
    w.configure(relief=tk.SUNKEN, state=tk.DISABLED)

About your second point, I'm not sure to understand what you mean.