问:
How to map an array object with key from different array set in javascript
I'm building a small application in VueJS where I'm getting a response in following format:

```<code>"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        "client_name":"Test Company 5",
    }
]
</code>```

And I'm having a data set of nature as:

```<code>const nature = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"},
    {value: 3, label: "Demo 3"}
]
</code>```

I want to map my meeting_summaries with this data set were in meeting_summaries -> nature points to nature -> value so that my final output can look something like this:

```<code>"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        'nature_name": "Demo 1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        'nature_name": "Demo 2",
        "client_name":"Test Company 5",
    }
]
</code>```

答:
const baseObj = {
    "meeting_summaries": [
        {
            "interaction_id": 22,
            "nature": "1",
            "client_name": "Test Company 4",
        },
        {
            "interaction_id": 22,
            "nature": "2",
            "client_name": "Test Company 5",
        }
    ]
}

const natures = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"}
]

const meeting_summaries = baseObj.meeting_summaries

natures.forEach((nature, index) => {
    meeting_summaries[index]["nature_name"] = nature.label
})

console.log(baseObj)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I'm building a small application in VueJS where I'm getting a response in following format:

"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        "client_name":"Test Company 5",
    }
]

And I'm having a data set of nature as:

const nature = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"},
    {value: 3, label: "Demo 3"}
]

I want to map my meeting_summaries with this data set were in meeting_summaries -> nature points to nature -> value so that my final output can look something like this:

"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        'nature_name": "Demo 1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        'nature_name": "Demo 2",
        "client_name":"Test Company 5",
    }
]

Body:
const baseObj = {
    "meeting_summaries": [
        {
            "interaction_id": 22,
            "nature": "1",
            "client_name": "Test Company 4",
        },
        {
            "interaction_id": 22,
            "nature": "2",
            "client_name": "Test Company 5",
        }
    ]
}

const natures = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"}
]

const meeting_summaries = baseObj.meeting_summaries

natures.forEach((nature, index) => {
    meeting_summaries[index]["nature_name"] = nature.label
})

console.log(baseObj)

.as-console-wrapper { max-height: 100% !important; top: 0; }


来源: stackexchange

问:
Row won't move to the next line
I am working on my personal website and i'm trying to make a new row with Bootstrap 4. The row has an H1 above it. Whatever I'm trying, the row won't move to the next line. I tried different solutions, inline, br, different rows, nothing works. Can somebody help me out?
This is my current HTML code:

Projecten

col

col

col

I didn't change anything on the CSS code, just the default bootstrap code.

Click here for a screenshot

答:
With bootstrap is</p>

```<code>  <div class="row">
    <div class="col">
      <h1>Text</h1>
    </div>
  </div>
  <div class="row">
    <div class="col-md-4">
      <p>col</p>
    </div>
    <div class="col-md-4">
      <p>col</p>
    </div>
    <div class="col-md-4">
      <p>col</p>
    </div>
  </div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Row won't move to the next line

Body:
With bootstrap is

  <div class="row">
    <div class="col">
      <h1>Text</h1>
    </div>
  </div>
  <div class="row">
    <div class="col-md-4">
      <p>col</p>
    </div>
    <div class="col-md-4">
      <p>col</p>
    </div>
    <div class="col-md-4">
      <p>col</p>
    </div>
  </div>


问:
How to return different POJO using Java generics
I would like a method to return a different type of List.

I tried something like the following but not sure if this approach is correct or not. How can I do this?

```<code>public <T> List<T>  getPageDetails(Long adId,String source);
</code>```

Based on the source I will return a different List of objects in the implementation method.

Like in implementation if the source is 1, then will have to return List of objects type1, if the source is 2 then list of objects type2, etc.

答:
```<code>private Object objT;

public <T> List<T> magicalListGetter(Class<T> cls) {
    List<T> list = new ArrayList<>();
    list.add(cls.cast(actuallyT));
    try {
        list.add(cls.getConstructor().newInstance()); // If default constructor
    } ...
    return list;
}
</code>```

One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (cls.getConstructor().newInstance()).

Without class :

```<code>public <T> List<T> magicalListGetter() {
return new ArrayList<T>();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like a method to return a different type of List.

I tried something like the following but not sure if this approach is correct or not. How can I do this?

public <T> List<T>  getPageDetails(Long adId,String source);

Based on the source I will return a different List of objects in the implementation method.

Like in implementation if the source is 1, then will have to return List of objects type1, if the source is 2 then list of objects type2, etc.

Body:
private Object objT;

public <T> List<T> magicalListGetter(Class<T> cls) {
    List<T> list = new ArrayList<>();
    list.add(cls.cast(actuallyT));
    try {
        list.add(cls.getConstructor().newInstance()); // If default constructor
    } ...
    return list;
}

One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (cls.getConstructor().newInstance()).

Without class :

public <T> List<T> magicalListGetter() {
return new ArrayList<T>();
}


问:
Scrollview not scroll inside linearlayout android
Following is the code of layout xml that i have tried to implement, i don't know what is the issue behind it  Can anyone help me?

```<code> <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:id="@+id/activity_post"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/white"
 android:orientation="vertical"
 android:weightSum="1">
<ScrollView
    android:fillViewport="true"
    android:layout_weight="0.95"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        tools:ignore="NestedWeights"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_weight="0.05"
            tools:ignore="NestedWeights"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="0dp">
            <TextView
                tools:ignore="NestedWeights"
                android:id="@+id/etSearch"
                android:maxLines="1"
                android:layout_weight="0.9"
                android:gravity="center"
                android:padding="@dimen/value_3"
                android:textColor="@color/black"
                android:layout_width="0dp"
                android:textSize="@dimen/font_14"
                android:background="@drawable/bg"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="@string/search_text"/>
            <FrameLayout
                android:background="@drawable/tab_bg_selector"
                android:id="@+id/imgChat"
                tools:ignore="NestedWeights"
                android:layout_gravity="center"
                android:layout_weight="0.1"
                android:layout_margin="@dimen/value_5"
                android:layout_width="0dp"
                android:layout_height="@dimen/value_30">
                <TextView
                    android:gravity="center"
                    android:id="@+id/msgCount"
                    android:textSize="@dimen/font_14"
                    android:textColor="@android:color/white"
                    android:background="@drawable/round"
                    android:layout_gravity="center"
                    android:layout_width="wrap_content"
                    android:layout_height="@dimen/value_20" />
                <ImageView
                    android:visibility="gone"
                    android:id="@+id/imgMsg"
                    android:src="@drawable/chatt"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </FrameLayout>
        </LinearLayout>
        <!--<LinearLayout />-->
        <LinearLayout
            android:layout_weight="0.9"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="0dp">
            <android.support.v4.widget.SwipeRefreshLayout
                android:id="@+id/swiperefresh"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <LinearLayout
                    android:descendantFocusability="blocksDescendants"
                    tools:ignore="NestedWeights"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    >
                    <LinearLayout
                        android:orientation="vertical"
                        android:background="@color/rv_color"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">
                        <android.support.v7.widget.RecyclerView
                            tools:ignore="NestedWeights"
                            android:layout_centerInParent="true"
                            android:id="@+id/rvHairList"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:clipToPadding="false" />
                    </LinearLayout>
                    <ProgressBar
                        android:indeterminateTint="@color/user_name"
                        android:id="@+id/main_progress"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"/>
                    <include
                        layout="@layout/error_layout"/>
                </LinearLayout>
            </android.support.v4.widget.SwipeRefreshLayout>
        </LinearLayout>
    </LinearLayout>
</ScrollView>
<LinearLayout
    android:layout_weight="0.05"
    android:gravity="bottom"
    android:layout_gravity="bottom"
    android:background="@color/white"
    tools:ignore="NestedWeights"
    android:padding="@dimen/value_5"
    android:layout_alignParentBottom="true"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="horizontal">
    <LinearLayout
        android:id="@+id/llDrawer"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/drawer"
            android:layout_gravity="center"
            tools:ignore="NestedWeights"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/more"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/llHome"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/imgHome"
            android:layout_gravity="center"
            tools:ignore="NestedWeights"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/home"/>
    </LinearLayout>
    <FrameLayout
        android:id="@+id/imgFriendRequest"
        tools:ignore="NestedWeights"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:layout_marginRight="@dimen/value_5"
        android:layout_marginLeft="@dimen/value_5"
        android:layout_width="@dimen/value_30"
        android:layout_height="@dimen/value_20">
        <TextView
            android:gravity="center"
            android:id="@+id/friendCount"
            android:textSize="@dimen/font_14"
            android:textColor="@android:color/white"
            android:background="@drawable/round"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <ImageView
            android:visibility="gone"
            android:id="@+id/imgFnd"
            android:src="@drawable/add_friend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </FrameLayout>
    <LinearLayout
        android:visibility="gone"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/gestureImg"
            android:layout_gravity="center"
            tools:ignore="NestedWeights"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/img_thing"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/llNewPost"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/imgGallery"
            android:layout_gravity="center"
            tools:ignore="NestedWeights"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/gallery"/>
    </LinearLayout>
    <FrameLayout
        android:id="@+id/imgNotification"
        tools:ignore="NestedWeights"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:layout_marginRight="@dimen/value_5"
        android:layout_marginLeft="@dimen/value_5"
        android:layout_width="@dimen/value_30"
        android:layout_height="@dimen/value_20">
        <TextView
            android:gravity="center"
            android:id="@+id/notiCount"
            android:textSize="@dimen/font_14"
            android:textColor="@android:color/white"
            android:background="@drawable/round"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <ImageView
            android:visibility="gone"
            android:id="@+id/imgNoti"
            android:src="@drawable/notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </FrameLayout>
    <LinearLayout
        android:id="@+id/llProfile"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <de.hdodenhof.circleimageview.CircleImageView
            android:layout_gravity="center"
            android:layout_weight="1"
            tools:ignore="NestedWeights"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/imgTimeline"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/loader"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            app:civ_border_color="#FF000000"/>
    </LinearLayout>
</LinearLayout>
</code>```

scrollview not scrolling
i have tried to change height of scrollview and linearlayout of scrollview but not get any solution

答:
Set 0dp instead of wrap_content in android:layout_height="wrap_content" </p>

```<code><ScrollView
    android:fillViewport="true"
    android:layout_weight="0.95"
    android:layout_width="match_parent"
    android:layout_height="0dp">
</code>```

Body:
Following is the code of layout xml that i have tried to implement, i don't know what is the issue behind it  Can anyone help me?

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:id="@+id/activity_post"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/white"
 android:orientation="vertical"
 android:weightSum="1">
<ScrollView
    android:fillViewport="true"
    android:layout_weight="0.95"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        tools:ignore="NestedWeights"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_weight="0.05"
            tools:ignore="NestedWeights"
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="0dp">
            <TextView
                tools:ignore="NestedWeights"
                android:id="@+id/etSearch"
                android:maxLines="1"
                android:layout_weight="0.9"
                android:gravity="center"
                android:padding="@dimen/value_3"
                android:textColor="@color/black"
                android:layout_width="0dp"
                android:textSize="@dimen/font_14"
                android:background="@drawable/bg"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="@string/search_text"/>
            <FrameLayout
                android:background="@drawable/tab_bg_selector"
                android:id="@+id/imgChat"
                tools:ignore="NestedWeights"
                android:layout_gravity="center"
                android:layout_weight="0.1"
                android:layout_margin="@dimen/value_5"
                android:layout_width="0dp"
                android:layout_height="@dimen/value_30">
                <TextView
                    android:gravity="center"
                    android:id="@+id/msgCount"
                    android:textSize="@dimen/font_14"
                    android:textColor="@android:color/white"
                    android:background="@drawable/round"
                    android:layout_gravity="center"
                    android:layout_width="wrap_content"
                    android:layout_height="@dimen/value_20" />
                <ImageView
                    android:visibility="gone"
                    android:id="@+id/imgMsg"
                    android:src="@drawable/chatt"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </FrameLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_weight="0.9"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="0dp">
            <android.support.v4.widget.SwipeRefreshLayout
                android:id="@+id/swiperefresh"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <LinearLayout
                    android:descendantFocusability="blocksDescendants"
                    tools:ignore="NestedWeights"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    >
                    <LinearLayout
                        android:orientation="vertical"
                        android:background="@color/rv_color"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">
                        <android.support.v7.widget.RecyclerView
                            tools:ignore="NestedWeights"
                            android:layout_centerInParent="true"
                            android:id="@+id/rvHairList"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:clipToPadding="false" />
                    </LinearLayout>
                    <ProgressBar
                        android:indeterminateTint="@color/user_name"
                        android:id="@+id/main_progress"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"/>
                    <include
                        layout="@layout/error_layout"/>
                </LinearLayout>
            </android.support.v4.widget.SwipeRefreshLayout>
        </LinearLayout>
    </LinearLayout>
</ScrollView>
<LinearLayout
    android:layout_weight="0.05"
    android:gravity="bottom"
    android:layout_gravity="bottom"
    android:background="@color/white"
    tools:ignore="NestedWeights"
    android:padding="@dimen/value_5"
    android:layout_alignParentBottom="true"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="horizontal">
    <LinearLayout
        android:id="@+id/llDrawer"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/drawer"
            android:layout_gravity="center"
            tools:ignore="NestedWeights"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/more"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/llHome"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/imgHome"
            android:layout_gravity="center"
            tools:ignore="NestedWeights"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/home"/>
    </LinearLayout>
    <FrameLayout
        android:id="@+id/imgFriendRequest"
        tools:ignore="NestedWeights"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:layout_marginRight="@dimen/value_5"
        android:layout_marginLeft="@dimen/value_5"
        android:layout_width="@dimen/value_30"
        android:layout_height="@dimen/value_20">
        <TextView
            android:gravity="center"
            android:id="@+id/friendCount"
            android:textSize="@dimen/font_14"
            android:textColor="@android:color/white"
            android:background="@drawable/round"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <ImageView
            android:visibility="gone"
            android:id="@+id/imgFnd"
            android:src="@drawable/add_friend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </FrameLayout>
    <LinearLayout
        android:visibility="gone"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/gestureImg"
            android:layout_gravity="center"
            tools:ignore="NestedWeights"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/img_thing"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/llNewPost"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/imgGallery"
            android:layout_gravity="center"
            tools:ignore="NestedWeights"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/gallery"/>
    </LinearLayout>
    <FrameLayout
        android:id="@+id/imgNotification"
        tools:ignore="NestedWeights"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:layout_marginRight="@dimen/value_5"
        android:layout_marginLeft="@dimen/value_5"
        android:layout_width="@dimen/value_30"
        android:layout_height="@dimen/value_20">
        <TextView
            android:gravity="center"
            android:id="@+id/notiCount"
            android:textSize="@dimen/font_14"
            android:textColor="@android:color/white"
            android:background="@drawable/round"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <ImageView
            android:visibility="gone"
            android:id="@+id/imgNoti"
            android:src="@drawable/notification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </FrameLayout>
    <LinearLayout
        android:id="@+id/llProfile"
        android:gravity="center"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">
        <de.hdodenhof.circleimageview.CircleImageView
            android:layout_gravity="center"
            android:layout_weight="1"
            tools:ignore="NestedWeights"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/imgTimeline"
            android:layout_width="@dimen/value_30"
            android:layout_height="@dimen/value_20"
            android:src="@drawable/loader"
            android:layout_marginRight="@dimen/value_5"
            android:layout_marginLeft="@dimen/value_5"
            app:civ_border_color="#FF000000"/>
    </LinearLayout>
</LinearLayout>

scrollview not scrolling
i have tried to change height of scrollview and linearlayout of scrollview but not get any solution

Body:
Set 0dp instead of wrap_content in android:layout_height="wrap_content"

<ScrollView
    android:fillViewport="true"
    android:layout_weight="0.95"
    android:layout_width="match_parent"
    android:layout_height="0dp">


问:
Laravel 5.4 Eloquent not Saving certain fields
I have been working on logging all user activities in Model events... But for some reason, the records are stored in the user_action table but the action_model field. This is my code.
User Action Class
`

```<code>class UserAction extends Model
{

  use SoftDeletes;

  protected $table = 'user_actions';

  /**
  *
  */

  protected $fillable = [
      'user_id','action', ' action_model', 'action_id'
  ];

  public function user()
  {
      return $this->belongsTo(User::class, 'user_id');
  }

}
</code>```

`

UserActionObervable

```<code>    class UserActionObserver
{
    public function saved($model)
    {
        $type = $model->getTable();
        // dd($type); when dump the value exists
        if ($model->wasRecentlyCreated == true) {
            // Data was just created
            $action = 'created';
        } else {
            // Data was updated
            $action = 'updated';
        }
        if (Sentinel::check()) {
            UserAction::create([
                'user_id'      => Sentinel::getUser()->id,
                'action'       => $action,
                'action_model' => 'model', //I tried to pass in constant
                'action_id'    => $model->id
            ]);
        }
    }

    public function deleting($model)
    {
        if (Sentinel::check()) {
            UserAction::create([
                'user_id'      => Sentinel::getUser()->id,
                'action'       => 'deleted',
                'action_model' => $model->getTable(),
                'action_id'    => $model->id
            ]);
        }
    }
}
</code>```

This is the schema

```<code>Schema::create('user_actions', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('user_id')->unsigned()->nullable();
      $table->string('action');  // created / updated / deleted
      $table->string('action_model');
      $table->integer('action_id')->nullable();
      $table->timestamps();

      $table->engine = 'InnoDB';
      $table->foreign('user_id')->references('id')
            ->on('users')->onDelete('cascade');

    });
</code>```

答:
```<code>protected $fillable = [
    'user_id','action', ' action_model', 'action_id'
];
</code>```

Try to remove the space before action_model. The field in $fillable doesn't match the key you're passing into the create() method.

Body:
I have been working on logging all user activities in Model events... But for some reason, the records are stored in the user_action table but the action_model field. This is my code.
User Action Class
`

class UserAction extends Model
{

  use SoftDeletes;

  protected $table = 'user_actions';

  /**
  *
  */

  protected $fillable = [
      'user_id','action', ' action_model', 'action_id'
  ];

  public function user()
  {
      return $this->belongsTo(User::class, 'user_id');
  }

}

`

UserActionObervable

    class UserActionObserver
{
    public function saved($model)
    {
        $type = $model->getTable();
        // dd($type); when dump the value exists
        if ($model->wasRecentlyCreated == true) {
            // Data was just created
            $action = 'created';
        } else {
            // Data was updated
            $action = 'updated';
        }
        if (Sentinel::check()) {
            UserAction::create([
                'user_id'      => Sentinel::getUser()->id,
                'action'       => $action,
                'action_model' => 'model', //I tried to pass in constant
                'action_id'    => $model->id
            ]);
        }
    }

    public function deleting($model)
    {
        if (Sentinel::check()) {
            UserAction::create([
                'user_id'      => Sentinel::getUser()->id,
                'action'       => 'deleted',
                'action_model' => $model->getTable(),
                'action_id'    => $model->id
            ]);
        }
    }
}

This is the schema

Schema::create('user_actions', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('user_id')->unsigned()->nullable();
      $table->string('action');  // created / updated / deleted
      $table->string('action_model');
      $table->integer('action_id')->nullable();
      $table->timestamps();

      $table->engine = 'InnoDB';
      $table->foreign('user_id')->references('id')
            ->on('users')->onDelete('cascade');

    });

Body:
protected $fillable = [
    'user_id','action', ' action_model', 'action_id'
];

Try to remove the space before action_model. The field in $fillable doesn't match the key you're passing into the create() method.


问:
Angular 2 cli SCSS/CSS order
I'm trying to work out what order Angular 2 uses for its Css once its all compiled.

What I'm trying to work out is does it get all of the SCSS files from the individual components and then add them after the main styles.scss file? This would seem to be the obvious thing but does it do it the other way round and put the componet styles first then the main styles?

I know if I specify files in the styles array in the angular-cli.json file Angular will process them in that order but obviously component styles aren't specified there.

Apologies if this sounds a bit odd but I can't work it out and can't seem to find any info on it anywhwere.

答:
You may need to look at how ViewEncapsulation work and few other things. This might help:

https://scotch.io/tutorials/all-the-ways-to-add-css-to-angular-2-components

Title: Angular 2 cli SCSS/CSS order


问:
A Typical Issue with login using Zend_Form
Iam facing a typical issue with a form submit using Zend framework. Basically I have written a simple code to login a user, but this came out of the blue.

The code to show the form is pretty standard

$loginform = new Application_Form_Login();
        $loginform->setMethod('post');
        $loginform->setAction('login');
        $this->view->form = $loginform;

When I use my home page url as - http://localhost.ruin.com/public/

I get an exception

```<code>Page not found
Exception information:

Message: Invalid controller specified (login)
Stack trace:

#0 C:\domains\ruin\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#1 C:\domains\ruin\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#2 C:\domains\ruin\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#3 C:\domains\ruin\public\index.php(27): Zend_Application->run()
#4 {main}

Request Parameters:

array (
  'controller' => 'login',
  'action' => 'index',
  'module' => 'default',
  'username' => 'fsdf',
  'password' => 'fdsf',
  'submit' => 'submit',
)
</code>```

However if I use the base url as http://localhost.ruin.com/public/index/ , the same code works perfectly.

I also know that its due to the fact that in first url the zend router is messing up the index controller with login since its not able to append the login action to the default index controller.

Do you guys think this is by design of Zend Framework and I shall have to forcefully send my users to this url
http://localhost.ruin.com/public/index/ whenever they hit the home page or is there a way I can make my code work with
http://localhost.ruin.com/public/

Any suggestions?

答:
Short answer:

```<code>$form->setAction('/public/index/login');
</code>```

Ridiculously verbose answer follows: ;-)

One point of confusion is the use of the term "action".

With regard to a form, "action" refers to the action attribute:

```<code><form action="/url/at/which/the/form/will/be/processed" method="post">
</code>```

This is the action be referred to when you call $form->setAction() method. The key point is that this must be a URL, and the application has to have routing in place that maps this URL to a (controller, action) pair.

Which brings up the other way that the term "action" is used: as a shorthand name for a method on a controller. For example, the action named "smile" maps to the method smileAction() on the controller.

So, in your case, the issue is one of getting your form's setAction() call in-sync with the routing that's in place for the app.

By specifying the URL 'login' as the form's action, you are providing a relative URL, so the browser will interpret this as relative to the URL that appears in the browser's location bar. When you browse to the page but leave off the "index" portion of the URL, then the default routing in the framework views "login" as the controller. Since you have no LoginController, the request craps out.

So your IndexController could look like:

```<code><?php

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->form = $this->_getForm();
    }

    public function loginAction()
    {
        $form = $this->_getForm();
        if ($this->getRequest()->isPost()){
            if ($form->isValid($this->getRequest()->getPost())){
                // All cool. Process your form,
                // probably with a redirect afterwords to
                // clear the POST.
            }
        }

        // Still alive?
        // Then it was either not a post request or the form was invalid.
        // In either case, set the form in the view
        $this->view->form = $form;
    }

    /**
    * A helper method to keep the form creation DRY
    */
    protected function _getForm()
    {
        $loginform = new Application_Form_Login();
        $loginform->setMethod('post');

        // Points the form to the IndexController::loginAction();
        $loginform->setAction('/public/index/login');
        return $loginform;
    }
}
</code>```

The upshot is that the setAction() call needs a URL that the router can map to a controller/action pair knows how to process the post.

Hope this helps!

ContentLicense: CC BY-SA 2.5

Body:
Iam facing a typical issue with a form submit using Zend framework. Basically I have written a simple code to login a user, but this came out of the blue.

The code to show the form is pretty standard

$loginform = new Application_Form_Login();
        $loginform->setMethod('post');
        $loginform->setAction('login');
        $this->view->form = $loginform;

When I use my home page url as - http://localhost.ruin.com/public/

I get an exception

Page not found
Exception information:

Message: Invalid controller specified (login)
Stack trace:

#0 C:\domains\ruin\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#1 C:\domains\ruin\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#2 C:\domains\ruin\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#3 C:\domains\ruin\public\index.php(27): Zend_Application->run()
#4 {main}

Request Parameters:

array (
  'controller' => 'login',
  'action' => 'index',
  'module' => 'default',
  'username' => 'fsdf',
  'password' => 'fdsf',
  'submit' => 'submit',
)

However if I use the base url as http://localhost.ruin.com/public/index/ , the same code works perfectly.

I also know that its due to the fact that in first url the zend router is messing up the index controller with login since its not able to append the login action to the default index controller.

Do you guys think this is by design of Zend Framework and I shall have to forcefully send my users to this url
http://localhost.ruin.com/public/index/ whenever they hit the home page or is there a way I can make my code work with
http://localhost.ruin.com/public/

Any suggestions?

Body:
Short answer:

$form->setAction('/public/index/login');

Ridiculously verbose answer follows: ;-)

One point of confusion is the use of the term "action".

With regard to a form, "action" refers to the action attribute:

<form action="/url/at/which/the/form/will/be/processed" method="post">

This is the action be referred to when you call $form->setAction() method. The key point is that this must be a URL, and the application has to have routing in place that maps this URL to a (controller, action) pair.

Which brings up the other way that the term "action" is used: as a shorthand name for a method on a controller. For example, the action named "smile" maps to the method smileAction() on the controller.

So, in your case, the issue is one of getting your form's setAction() call in-sync with the routing that's in place for the app.

By specifying the URL 'login' as the form's action, you are providing a relative URL, so the browser will interpret this as relative to the URL that appears in the browser's location bar. When you browse to the page but leave off the "index" portion of the URL, then the default routing in the framework views "login" as the controller. Since you have no LoginController, the request craps out.

So your IndexController could look like:

<?php

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->form = $this->_getForm();
    }

    public function loginAction()
    {
        $form = $this->_getForm();
        if ($this->getRequest()->isPost()){
            if ($form->isValid($this->getRequest()->getPost())){
                // All cool. Process your form,
                // probably with a redirect afterwords to
                // clear the POST.
            }
        }

        // Still alive?
        // Then it was either not a post request or the form was invalid.
        // In either case, set the form in the view
        $this->view->form = $form;
    }

    /**
    * A helper method to keep the form creation DRY
    */
    protected function _getForm()
    {
        $loginform = new Application_Form_Login();
        $loginform->setMethod('post');

        // Points the form to the IndexController::loginAction();
        $loginform->setAction('/public/index/login');
        return $loginform;
    }
}

The upshot is that the setAction() call needs a URL that the router can map to a controller/action pair knows how to process the post.

Hope this helps!


问:
How to customize bulma variables in rails
I'm using the bulma rails gem and I Want to customize some of the variables it uses, specifically the font color.

According to the bulma docs http://bulma.io/documentation/overview/customize/ I should do something like this:

```<code>// 1. Import the initial variables
@import "../sass/utilities/initial-variables"

// 2. Set your own initial variables
// Update blue
$blue: #72d0eb
// Add pink and its invert
$pink: #ffb3b3
$pink-invert: #fff
// Add a serif family
$family-serif: "Merriweather", "Georgia", serif

// 3. Set the derived variables
// Use the new pink as the primary color
$primary: $pink
$primary-invert: $pink-invert
// Use the existing orange as the danger color
$danger: $orange
// Use the new serif family
$family-primary: $family-serif

// 4. Import the rest of Bulma
@import "../bulma"
</code>```

However I'm not sure how to make that work with the rails gem I'm using.

Currently my application.css file looks like this:

```<code>/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */

@import "bulma";
</code>```

which works fine. However if I change it to be like the example in the bulma docs it no longer works even when changing @import "../bulma" to @import "bulma" and @import "../sass/utilities/initial-variables"
 to @import "sass/utilities/initial-variables"

I guess the problem here is with that first import of the variables but I can't figure out how to import it. Here's the file in the gem: https://github.com/joshuajansen/bulma-rails/blob/master/app/assets/stylesheets/sass/utilities/variables.sass

Thanks!

答:
Ok managed to get this working.

I created a file called application.css.scss in the app/assets/stylesheets directory and added the following:

```<code>$blue: #72d0eb;
$pink: #ffb3b3;
$pink-invert: #fff;
$family-serif: "Merriweather", "Georgia", serif;
$primary: $pink;
$primary-invert: $pink-invert;
$family-primary: $family-serif;

@import "bulma";
</code>```

This works just fine. Adding the initial import statement causes to fail though, played around with it a bit trying to get the path correct but it always failed for me. Not sure if this has any significance I'm not seeing but works for me now anyways.

Body:
I'm using the bulma rails gem and I Want to customize some of the variables it uses, specifically the font color.

According to the bulma docs http://bulma.io/documentation/overview/customize/ I should do something like this:

// 1. Import the initial variables
@import "../sass/utilities/initial-variables"

// 2. Set your own initial variables
// Update blue
$blue: #72d0eb
// Add pink and its invert
$pink: #ffb3b3
$pink-invert: #fff
// Add a serif family
$family-serif: "Merriweather", "Georgia", serif

// 3. Set the derived variables
// Use the new pink as the primary color
$primary: $pink
$primary-invert: $pink-invert
// Use the existing orange as the danger color
$danger: $orange
// Use the new serif family
$family-primary: $family-serif

// 4. Import the rest of Bulma
@import "../bulma"

However I'm not sure how to make that work with the rails gem I'm using.

Currently my application.css file looks like this:

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .
 *= require_self
 */

@import "bulma";

which works fine. However if I change it to be like the example in the bulma docs it no longer works even when changing @import "../bulma" to @import "bulma" and @import "../sass/utilities/initial-variables"
 to @import "sass/utilities/initial-variables"

I guess the problem here is with that first import of the variables but I can't figure out how to import it. Here's the file in the gem: https://github.com/joshuajansen/bulma-rails/blob/master/app/assets/stylesheets/sass/utilities/variables.sass

Thanks!

Body:
Ok managed to get this working.

I created a file called application.css.scss in the app/assets/stylesheets directory and added the following:

$blue: #72d0eb;
$pink: #ffb3b3;
$pink-invert: #fff;
$family-serif: "Merriweather", "Georgia", serif;
$primary: $pink;
$primary-invert: $pink-invert;
$family-primary: $family-serif;

@import "bulma";

This works just fine. Adding the initial import statement causes to fail though, played around with it a bit trying to get the path correct but it always failed for me. Not sure if this has any significance I'm not seeing but works for me now anyways.


问:
django - model - what are the benefits?
I have customized my Django project to work with mariaDB (mySQL).
Works fine, however I have issues (or concerns) with models.

First of all - I am not sure why I should need them if for me (personally) its much easier to use SQL statements to get the data.
Using API for DB queries might be useful for people who do not know SQL, but for me its less flexible.
Can anybody explain me main benefits of using models?

Here is one of the issues I have. See the code below.

```<code>class Quotes(models.Model):
    updated = models.DateTimeField()
    tdate = models.DateField(default='1900-01-01')
    ticker = models.CharField(max_length=15)
    open = models.FloatField(default=0)
    vol = models.BigIntegerField(default=0)
</code>```

why program does not consider 'default' when DB table and fields are created?

why - what I define as FloatField on DB is 'double' and not 'float' (I checked this using phpMYAdmin)

How can I properly set default value?

My table will have at least 1 million of entries.
Do I need to concern about performance using API instead of direct SQL queries?  Usually one query will select 700-800 entries.
Is it good approach to use MySQLdb and direct SQL's instead of models?

sorry that some questions might sound too simple, but I just started with Django. Before this I worked with PHP. Main reason I want to use Python for web page development is library which I have developed.

答:
Question zero, i.e. why models: Django's models are a nice abstraction on top of relational database tables – most (if not all) web apps end up having (or being) some sort of CRUD where you manipulate objects or graphs of objects saved in the database, so an object-oriented approach is nice to work with there.

In addition, many features in Django (and libraries that work with Django) are built around models (such as the admin, ModelForms, serialization, etc.).

Question 1: That date should preferably be datetime.date(1900, 1, 1), not a string, but that aside, Django deals with defaults on model instantiation, not necessarily in the database.

Question 2: Because that's how it's mapped, presumably to avoid programmers accidentally losing floating-point precision (since MySQL is rather notorious about doing precision-losing conversions "behind your back").

Question 3: Django's ORM is, to be absolutely honest, not the fastest when it generates queries and instantiates model instances. Most of the time, in regular operations, that's not a problem. Depending on what you're doing with those 700 to 800 instances, you may be able to work around that anyway; for instance, using .values() or .values_list() on a queryset if you don't need the actual instances, just the data.

Regarding direct SQL, please don't hard-code any MySQLdb calls in a Django app though; Django has very nice "escape hatches" for doing raw SQL:

You can perform .raw() SQL queries that map into models, or if that's not enough,

you can just execute SQL against the database connection like you would with MySQLdb.

Oh, and one more thing: your model name should be singular (Quote) :)

Title: django - model - what are the benefits?

Body:
I have customized my Django project to work with mariaDB (mySQL).
Works fine, however I have issues (or concerns) with models.

First of all - I am not sure why I should need them if for me (personally) its much easier to use SQL statements to get the data.
Using API for DB queries might be useful for people who do not know SQL, but for me its less flexible.
Can anybody explain me main benefits of using models?

Here is one of the issues I have. See the code below.

class Quotes(models.Model):
    updated = models.DateTimeField()
    tdate = models.DateField(default='1900-01-01')
    ticker = models.CharField(max_length=15)
    open = models.FloatField(default=0)
    vol = models.BigIntegerField(default=0)

why program does not consider 'default' when DB table and fields are created?

why - what I define as FloatField on DB is 'double' and not 'float' (I checked this using phpMYAdmin)

How can I properly set default value?

My table will have at least 1 million of entries.
Do I need to concern about performance using API instead of direct SQL queries?  Usually one query will select 700-800 entries.
Is it good approach to use MySQLdb and direct SQL's instead of models?

sorry that some questions might sound too simple, but I just started with Django. Before this I worked with PHP. Main reason I want to use Python for web page development is library which I have developed.


答:
You can use genrics to return multiple list</p>

```<code>   public <T> List<T>  getPageDetails(Long adId,String source);

public static void main(String[] args) {
        Solution sol = new Solution();

        List<String> list = sol.getPageDetails(String.class, 0l, "source");
    }

    public <T> List<T> getPageDetails(Class<T> c, Long adId, String source) {
        List<T> list = new ArrayList<>();
        List<Object> objectList = getObjectList(adId, source);
        for (Object o : objectList) {
            T t = c.cast(o);
            list.add(t);
        }
        return list;

    }

    private List<Object> getObjectList(Long adId, String source) {
        // TODO Auto-generated method stub
        return null;
    }
</code>```

Title: How to return different POJO using Java generics

Body:
You can use genrics to return multiple list

   public <T> List<T>  getPageDetails(Long adId,String source);

public static void main(String[] args) {
        Solution sol = new Solution();

        List<String> list = sol.getPageDetails(String.class, 0l, "source");
    }

    public <T> List<T> getPageDetails(Class<T> c, Long adId, String source) {
        List<T> list = new ArrayList<>();
        List<Object> objectList = getObjectList(adId, source);
        for (Object o : objectList) {
            T t = c.cast(o);
            list.add(t);
        }
        return list;

    }

    private List<Object> getObjectList(Long adId, String source) {
        // TODO Auto-generated method stub
        return null;
    }


问:
No display custom Tag in asp.net
I am building custom asp.net server control. It is used in design time but no display run time. I write this.

```<code>   <cc1:TemplateMenu ID="TemplateMenu1" runat="server">
        <HeaderTemplate>
            <asp:Label ID="Title" Text="Hello World" runat="server"></asp:Label>
        </HeaderTemplate>
        <SperatorTemplate>|</SperatorTemplate>
        <FooterTemplate>
            <asp:TextBox ID="TextBox" Text="" runat="server"></asp:TextBox>
            <asp:Button ID="Button" Text="Click Me"  runat="server"/>
        </FooterTemplate>
    </cc1:TemplateMenu>
</code>```

This is design time.

This is server control code file.

```<code>Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports Yoma.Yoma.CustomControls.BasicTemplate

Namespace Yoma.CustomControls.TemplateMenu

    <DefaultProperty("Text"), ToolboxData("<{0}:TemplateMenu runat=server></{0}:TemplateMenu>")> _
    Public Class TemplateMenu
        Inherits CompositeControl

        Private MenuData As New ArrayList

        Public Sub New()

            MenuData = New ArrayList

            Dim MenuItem As New ListItem

            MenuItem.Text = "Apress"
            MenuItem.Value = "http://www.apress.com"
            MenuData.Add(MenuItem)

            MenuItem = New ListItem
            MenuItem.Text = "Microsoft"
            MenuItem.Value = "http://www.microsoft.com"
            MenuData.Add(MenuItem)

            MenuItem = New ListItem
            MenuItem.Text = "ASP.Net"
            MenuItem.Value = "http://asp.net"
            MenuData.Add(MenuItem)

        End Sub

#Region "HeaderTemplate"

        Private _HeaderTemplate As ITemplate = Nothing

        <Browsable(False), Description("The header template"), PersistenceMode(PersistenceMode.InnerProperty)> _
        Public Property HeaderTemplate() As ITemplate
            Get
                Return _HeaderTemplate
            End Get
            Set(ByVal value As ITemplate)
                _HeaderTemplate = value
            End Set
        End Property

#End Region

#Region "FooterTemplate"

        Private _FooterTemplate As ITemplate = Nothing

        <Browsable(False), Description("The footer template"), PersistenceMode(PersistenceMode.InnerProperty)> _
        Public Property FooterTemplate() As ITemplate
            Get
                Return _FooterTemplate
            End Get
            Set(ByVal value As ITemplate)
                _FooterTemplate = value
            End Set
        End Property

#End Region

#Region "SperatorTemplate"

        Private _SperatorTemplate As ITemplate = Nothing

        <Browsable(False), Description("The sperator template"), PersistenceMode(PersistenceMode.InnerProperty)> _
        Public Property SperatorTemplate() As ITemplate
            Get
                Return _SperatorTemplate
            End Get
            Set(ByVal value As ITemplate)
                _SperatorTemplate = value
            End Set
        End Property

#End Region

#Region "Create Control"

        Public Sub CreateControlHierarchy()

            If HeaderTemplate Is Nothing Then
                Dim Header As New BasicTemplateContainer

                HeaderTemplate.InstantiateIn(Header)
                Controls.Add(Header)
            End If

            Dim Count As Integer = MenuData.Count

            For Each Item As ListItem In MenuData
                Dim Link As New HyperLink

                Link.Text = Item.Text
                Link.NavigateUrl = Item.Value
                Controls.Add(Link)
                Controls.Add(New LiteralControl("|"))
            Next

            If FooterTemplate Is Nothing Then
                Dim Footer As New BasicTemplateContainer

                FooterTemplate.InstantiateIn(Footer)
                Controls.Add(Footer)
            End If

        End Sub

        Protected Overrides Sub CreateChildControls()
            Controls.Clear()
            CreateControlHierarchy()
        End Sub

        Public Overrides ReadOnly Property Controls() As ControlCollection
            Get
                EnsureChildControls()
                Return MyBase.Controls
            End Get
        End Property

        Public Overrides Sub DataBind()
            CreateChildControls()
            ChildControlsCreated = True
            MyBase.DataBind()
        End Sub

#End Region

    End Class

End Namespace

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Yoma.CustomControls.BasicTemplate

    <DefaultProperty("Text"), ToolboxData("<{0}:BasicTemplateContainer runat=server></{0}:BasicTemplateContainer>")> _
    Public Class BasicTemplateContainer
        Inherits WebControl
        Implements INamingContainer

        Public Sub New()
            Me.BorderWidth = 2
            Me.BorderStyle = WebControls.BorderStyle.Outset
        End Sub

    End Class

End Namespace
</code>```

Please help me... I got a really problem.

答: Have you invoked DataBind method for your control from your Page code? Unless you do that, your control tree may not be created.</p>

Title: No display custom Tag in asp.net

Body:
I am building custom asp.net server control. It is used in design time but no display run time. I write this.

   <cc1:TemplateMenu ID="TemplateMenu1" runat="server">
        <HeaderTemplate>
            <asp:Label ID="Title" Text="Hello World" runat="server"></asp:Label>
        </HeaderTemplate>
        <SperatorTemplate>|</SperatorTemplate>
        <FooterTemplate>
            <asp:TextBox ID="TextBox" Text="" runat="server"></asp:TextBox>
            <asp:Button ID="Button" Text="Click Me"  runat="server"/>
        </FooterTemplate>
    </cc1:TemplateMenu>

This is design time.

This is server control code file.

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports Yoma.Yoma.CustomControls.BasicTemplate

Namespace Yoma.CustomControls.TemplateMenu

    <DefaultProperty("Text"), ToolboxData("<{0}:TemplateMenu runat=server></{0}:TemplateMenu>")> _
    Public Class TemplateMenu
        Inherits CompositeControl

        Private MenuData As New ArrayList

        Public Sub New()

            MenuData = New ArrayList

            Dim MenuItem As New ListItem

            MenuItem.Text = "Apress"
            MenuItem.Value = "http://www.apress.com"
            MenuData.Add(MenuItem)

            MenuItem = New ListItem
            MenuItem.Text = "Microsoft"
            MenuItem.Value = "http://www.microsoft.com"
            MenuData.Add(MenuItem)

            MenuItem = New ListItem
            MenuItem.Text = "ASP.Net"
            MenuItem.Value = "http://asp.net"
            MenuData.Add(MenuItem)

        End Sub

#Region "HeaderTemplate"

        Private _HeaderTemplate As ITemplate = Nothing

        <Browsable(False), Description("The header template"), PersistenceMode(PersistenceMode.InnerProperty)> _
        Public Property HeaderTemplate() As ITemplate
            Get
                Return _HeaderTemplate
            End Get
            Set(ByVal value As ITemplate)
                _HeaderTemplate = value
            End Set
        End Property

#End Region

#Region "FooterTemplate"

        Private _FooterTemplate As ITemplate = Nothing

        <Browsable(False), Description("The footer template"), PersistenceMode(PersistenceMode.InnerProperty)> _
        Public Property FooterTemplate() As ITemplate
            Get
                Return _FooterTemplate
            End Get
            Set(ByVal value As ITemplate)
                _FooterTemplate = value
            End Set
        End Property

#End Region

#Region "SperatorTemplate"

        Private _SperatorTemplate As ITemplate = Nothing

        <Browsable(False), Description("The sperator template"), PersistenceMode(PersistenceMode.InnerProperty)> _
        Public Property SperatorTemplate() As ITemplate
            Get
                Return _SperatorTemplate
            End Get
            Set(ByVal value As ITemplate)
                _SperatorTemplate = value
            End Set
        End Property

#End Region

#Region "Create Control"

        Public Sub CreateControlHierarchy()

            If HeaderTemplate Is Nothing Then
                Dim Header As New BasicTemplateContainer

                HeaderTemplate.InstantiateIn(Header)
                Controls.Add(Header)
            End If

            Dim Count As Integer = MenuData.Count

            For Each Item As ListItem In MenuData
                Dim Link As New HyperLink

                Link.Text = Item.Text
                Link.NavigateUrl = Item.Value
                Controls.Add(Link)
                Controls.Add(New LiteralControl("|"))
            Next

            If FooterTemplate Is Nothing Then
                Dim Footer As New BasicTemplateContainer

                FooterTemplate.InstantiateIn(Footer)
                Controls.Add(Footer)
            End If

        End Sub

        Protected Overrides Sub CreateChildControls()
            Controls.Clear()
            CreateControlHierarchy()
        End Sub

        Public Overrides ReadOnly Property Controls() As ControlCollection
            Get
                EnsureChildControls()
                Return MyBase.Controls
            End Get
        End Property

        Public Overrides Sub DataBind()
            CreateChildControls()
            ChildControlsCreated = True
            MyBase.DataBind()
        End Sub

#End Region

    End Class

End Namespace

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Yoma.CustomControls.BasicTemplate

    <DefaultProperty("Text"), ToolboxData("<{0}:BasicTemplateContainer runat=server></{0}:BasicTemplateContainer>")> _
    Public Class BasicTemplateContainer
        Inherits WebControl
        Implements INamingContainer

        Public Sub New()
            Me.BorderWidth = 2
            Me.BorderStyle = WebControls.BorderStyle.Outset
        End Sub

    End Class

End Namespace

Please help me... I got a really problem.


问:
Switching from Gulp to Webpack
UPDATE 30.04.20

[ Moving to Webpack ]

My first question is about how recommended is this switch for simple projects, just to Pre-Process/Concat/Minify?

Understanding this future "standards", like Webpack in together with PostCss-NextCss-Autoprefixer, etc. is like obsessing me....

So this leads to my next question , is there any tutorial that will guide to simple tasks like the one I told in my first question?

Or is an easy way to change my gulpfile.js to a webpack-config.js

My normal tasks in gulp are not the best practices but work well :

```<code>//load plugins
var gulp    = require('gulp'),
runSequence = require('run-sequence'),
sass        = require('gulp-ruby-sass'),
compass     = require('gulp-compass'),
rev         = require('gulp-rev'),
revDel      = require('rev-del'),
del         = require('del'),
minifycss   = require('gulp-minify-css'),
uglify      = require('gulp-uglify'),
rename      = require('gulp-rename'),
concat      = require('gulp-concat'),
notify      = require('gulp-notify'),
plumber     = require('gulp-plumber'),
watch       = require('gulp-watch'),
path        = require('path');

  //the title and icon that will be used for the Grunt notifications
  var notifyInfo = {
    title: 'Gulp',
    icon: path.join(__dirname, 'gulp.png')
  };

  //error notification settings for plumber
  var plumberErrorHandler = { errorHandler: notify.onError({
    title: notifyInfo.title,
    icon: notifyInfo.icon,
    message: "Error: <%= error.message %>"
  })
};

//patches
var paths = {
  scriptsAbs : '_coffeescript/',
  stylesAbs: '_scss/',
  scriptsCom : '_coffeescript/' + '**/*.js',
  stylesCom :'_scss/' + '**/*.scss',
  cssCom : 'resources/css',
  jsCom : 'resources/js',
  imgCom : 'resources/img'
};

gulp.task('clean',
  function (cb) {
    del([
      paths.cssCom + '/*',
      paths.jsCom + '/*'
      ], cb);
  });

//styles
gulp.task('styles',
  function() {
    return gulp.src(paths.stylesCom)
    .pipe(plumber(plumberErrorHandler))
    .pipe(compass({
      sass: '_scss',
      css: paths.cssCom,
      image: paths.imgCom,
      style: 'expanded',
      relative: true,
      require: ['normalize-scss', 'susy']
    }))
    .pipe(gulp.dest(paths.cssCom))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(gulp.dest(paths.cssCom))
    .pipe(rev())
    .pipe(gulp.dest(paths.cssCom))
    .pipe(rev.manifest())
    .pipe(revDel({ dest: paths.cssCom }))
    .pipe(gulp.dest(paths.cssCom))
    .pipe(notify({ message: 'Styles task completed' }))
  });

//scripts
gulp.task('scripts',
  function() {
    return gulp.src(paths.scriptsCom)
    .pipe(plumber(plumberErrorHandler))
    .pipe(concat('main.js'))
    .pipe(gulp.dest(paths.jsCom))
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest(paths.jsCom))
    .pipe(rev())
    .pipe(gulp.dest(paths.jsCom))
    .pipe(rev.manifest())
    .pipe(revDel({ dest: paths.jsCom }))
    .pipe(gulp.dest(paths.jsCom))
    .pipe(notify({ message: 'Scripts Concatenated completed' }))
  // .pipe(reload({stream:true}));

});

gulp.task('default', ['clean','styles','scripts'], function(){
  gulp.watch(paths.stylesCom, ['styles'])
  gulp.watch(paths.scriptsCom, ['scripts'])

//watch .php files
// gulp.watch(['*.php'], ['bs-reload'])
});
</code>```

And  I'm starting to use postcss that is making my workflow, mm, better..easier sometimes.

What are your opinions on all this? Where is the right path to start?

EDIT // JUNE 28, 2017

At this date our progress with Webpack 1  were super satisfactory and successfully , our workflow is pretty much faster and our dependence in this tool is Unchangeable.

This is the webpack.config.js that we use every day:

```<code>"use strict";

var webpack = require('webpack');
var glob = require('glob-all');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');

let start = {

    entry: {
        scripts: glob.sync(
            [
            './_javascript/*.js',
            './_cssnext/*.pcss'
            ]
        )},

    output: {
        path: './resources/js',
        filename: 'bundle--[name].js'
    },
    watchOptions: {
        poll: true
    },

    postcss: function (webpack) {
        return [
            require("postcss-import")({addDependencyTo: webpack}),
            require("postcss-url")(),
            require("precss")(),
            require("postcss-cssnext")(),
            require('postcss-font-magician')(),
            require("postcss-reporter")(),
            require("postcss-browser-reporter")(),
            require('postcss-inline-svg')(),
            require('postcss-urlrev')(),
            require('postcss-fontpath')(),
            require('postcss-object-fit-images')()
        ]
    },

    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader'
            },
            {
                test: /\.p?css$/,
                loader: ExtractTextPlugin.extract(
                    'style-loader',
                    'css-loader!postcss-loader'
                )
            }
        ]
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({name: 'scripts', filename: 'bundle--[name].js'}),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new ExtractTextPlugin("../css/bundle--styles.css"),
        new BrowserSyncPlugin({
            host: 'localhost',
            port: 3000,
            proxy: 'localhost:8002',
            browser: 'google chrome',
            ghostMode: false
        })
    ]

};

module.exports = start;
</code>```

But times has change and is time to evolve to Webpack 3 , and now we are in the progress to change this webpack.config.jsto the version 3

答:
For simple projects, I would not recommend the switch at all. In the end it's a personal taste I think, and I prefer postprocessing through easily understandable javascript (gulp).

As you've said in your question, your current setup works well: so why fix something that's not broken? I'd focus on refactoring your gulp code to make it a bit more readable, split the long functions into smaller gulp tasks.

In the end, using webpack requires learning a lot of specific webpack related config options, while with gulp you're mostly just piping vanilla js commands.

Title: Switching from Gulp to Webpack

Body:
UPDATE 30.04.20

[ Moving to Webpack ]

My first question is about how recommended is this switch for simple projects, just to Pre-Process/Concat/Minify?

Understanding this future "standards", like Webpack in together with PostCss-NextCss-Autoprefixer, etc. is like obsessing me....

So this leads to my next question , is there any tutorial that will guide to simple tasks like the one I told in my first question?

Or is an easy way to change my gulpfile.js to a webpack-config.js

My normal tasks in gulp are not the best practices but work well :

//load plugins
var gulp    = require('gulp'),
runSequence = require('run-sequence'),
sass        = require('gulp-ruby-sass'),
compass     = require('gulp-compass'),
rev         = require('gulp-rev'),
revDel      = require('rev-del'),
del         = require('del'),
minifycss   = require('gulp-minify-css'),
uglify      = require('gulp-uglify'),
rename      = require('gulp-rename'),
concat      = require('gulp-concat'),
notify      = require('gulp-notify'),
plumber     = require('gulp-plumber'),
watch       = require('gulp-watch'),
path        = require('path');

  //the title and icon that will be used for the Grunt notifications
  var notifyInfo = {
    title: 'Gulp',
    icon: path.join(__dirname, 'gulp.png')
  };

  //error notification settings for plumber
  var plumberErrorHandler = { errorHandler: notify.onError({
    title: notifyInfo.title,
    icon: notifyInfo.icon,
    message: "Error: <%= error.message %>"
  })
};

//patches
var paths = {
  scriptsAbs : '_coffeescript/',
  stylesAbs: '_scss/',
  scriptsCom : '_coffeescript/' + '**/*.js',
  stylesCom :'_scss/' + '**/*.scss',
  cssCom : 'resources/css',
  jsCom : 'resources/js',
  imgCom : 'resources/img'
};

gulp.task('clean',
  function (cb) {
    del([
      paths.cssCom + '/*',
      paths.jsCom + '/*'
      ], cb);
  });

//styles
gulp.task('styles',
  function() {
    return gulp.src(paths.stylesCom)
    .pipe(plumber(plumberErrorHandler))
    .pipe(compass({
      sass: '_scss',
      css: paths.cssCom,
      image: paths.imgCom,
      style: 'expanded',
      relative: true,
      require: ['normalize-scss', 'susy']
    }))
    .pipe(gulp.dest(paths.cssCom))
    .pipe(rename({ suffix: '.min' }))
    .pipe(minifycss())
    .pipe(gulp.dest(paths.cssCom))
    .pipe(rev())
    .pipe(gulp.dest(paths.cssCom))
    .pipe(rev.manifest())
    .pipe(revDel({ dest: paths.cssCom }))
    .pipe(gulp.dest(paths.cssCom))
    .pipe(notify({ message: 'Styles task completed' }))
  });

//scripts
gulp.task('scripts',
  function() {
    return gulp.src(paths.scriptsCom)
    .pipe(plumber(plumberErrorHandler))
    .pipe(concat('main.js'))
    .pipe(gulp.dest(paths.jsCom))
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify())
    .pipe(gulp.dest(paths.jsCom))
    .pipe(rev())
    .pipe(gulp.dest(paths.jsCom))
    .pipe(rev.manifest())
    .pipe(revDel({ dest: paths.jsCom }))
    .pipe(gulp.dest(paths.jsCom))
    .pipe(notify({ message: 'Scripts Concatenated completed' }))
  // .pipe(reload({stream:true}));

});

gulp.task('default', ['clean','styles','scripts'], function(){
  gulp.watch(paths.stylesCom, ['styles'])
  gulp.watch(paths.scriptsCom, ['scripts'])

//watch .php files
// gulp.watch(['*.php'], ['bs-reload'])
});

And  I'm starting to use postcss that is making my workflow, mm, better..easier sometimes.

What are your opinions on all this? Where is the right path to start?

EDIT // JUNE 28, 2017

At this date our progress with Webpack 1  were super satisfactory and successfully , our workflow is pretty much faster and our dependence in this tool is Unchangeable.

This is the webpack.config.js that we use every day:

"use strict";

var webpack = require('webpack');
var glob = require('glob-all');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');

let start = {

    entry: {
        scripts: glob.sync(
            [
            './_javascript/*.js',
            './_cssnext/*.pcss'
            ]
        )},

    output: {
        path: './resources/js',
        filename: 'bundle--[name].js'
    },
    watchOptions: {
        poll: true
    },

    postcss: function (webpack) {
        return [
            require("postcss-import")({addDependencyTo: webpack}),
            require("postcss-url")(),
            require("precss")(),
            require("postcss-cssnext")(),
            require('postcss-font-magician')(),
            require("postcss-reporter")(),
            require("postcss-browser-reporter")(),
            require('postcss-inline-svg')(),
            require('postcss-urlrev')(),
            require('postcss-fontpath')(),
            require('postcss-object-fit-images')()
        ]
    },

    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader'
            },
            {
                test: /\.p?css$/,
                loader: ExtractTextPlugin.extract(
                    'style-loader',
                    'css-loader!postcss-loader'
                )
            }
        ]
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({name: 'scripts', filename: 'bundle--[name].js'}),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new ExtractTextPlugin("../css/bundle--styles.css"),
        new BrowserSyncPlugin({
            host: 'localhost',
            port: 3000,
            proxy: 'localhost:8002',
            browser: 'google chrome',
            ghostMode: false
        })
    ]

};

module.exports = start;

But times has change and is time to evolve to Webpack 3 , and now we are in the progress to change this webpack.config.jsto the version 3


问:
getting confusion on this explain this loop result in java
```<code>int a = 0, b = 0;

for (int i = 0; i < 5; i++) {
    if (++a > 2 || ++b > 2) {
        a++;
    }
}

System.out.println("a= " + a + " b=" + b);
</code>```

can you explain the logic please?

答:
I think your confusion may come from ++a vs a++. So basicly, both of them increment the value carried by a by 1, this mean a = a + 1.

The difference is ++a will do the increment first, then do the comparison, while a++ will do the comparison first then increment.

So look at your code:

1st line: just declaring variables a and b, and instantiating

3rd line: for loop will iterate 5 times

First iteration:
- 4th line: ++a ---> a == 1, then compare it to 2, so on for b, here the expression returns false, so skip line 5.

9th line: here it prints out a= 1 b=1

Second iteration:
- 4th line: ++a ---> a == 2, then compare it to 2, so on for b, here the expression returns false, so skip line 5.

9th line: here it prints out a= 2 b=2

Third iteration: (later iterations are similar)
- 4th line: ++a ---> a == 3, then compare it to 2, so on for b, here the expression returns true, so line 5 is reached now.

5th line: a++ ---> a == 4

9th line: here it prints out a= 4 b=3

Hope that helps.

Body:
int a = 0, b = 0;

for (int i = 0; i < 5; i++) {
    if (++a > 2 || ++b > 2) {
        a++;
    }
}

System.out.println("a= " + a + " b=" + b);

can you explain the logic please?


问:
NSDictionary seems to have multiple values for one key, how do I access the individual values?
I am using ADAL to authenticate to Azure AD, it returns an dictionary with claims, one of the keys is the groups that a user is a member of,

The full dictionary looks like this

```<code>2017-06-05 17:40:58.712 NWMobileTill[46676:3282242] userInfoStore Item all {
    alg = none;
    amr =     (
        pwd
    );
    aud = "042a00fc-b832-411f-xxxxxxxx";
    exp = xxxxxxx;
    groups =     (
        "xxx-9725-43f6-a502-xxxxx",
        "38c5b3af-xxx-4b38-b180-xxxx"
    );
    iat = xxx;
    ipaddr = "xx";
    iss = "https://xxxxxxx/xxx-d61d-xxx-a949-0cb72eff23be/";
    name = "POS Test";
    nbf = xxx;
    oid = "c44f91f2-xx-40bb-9624-xxx";
    platf = 2;
    sub = "xxxxx";
    tid = "b5154a9e-xxx-4d55-a949-xxx";
    typ = JWT;
    "unique_name" = "nwpos@xxxxxx";
    upn = "nwpos@xxxx";
    ver = "1.0";
}
</code>```

when I access they values in the NSDIctionary using the objectForKey as below

```<code>NSDictionary *jongel = [result.tokenCacheStoreItem.userInformation.allClaims objectForKey:@"groups"];
</code>```

I get multiple entries like this,

```<code>2017-06-05 17:40:58.712 NWMobileTill[46676:3282242] Groups are (
"xx-9725-43f6-a502-xx",
"xx-d0dc-4b38-xx-17555db6f626"
)
</code>```

I am confused that I can get multiple values, how do I access each individual value? I happen to assign this to an NSDictionary but I don't know if that is right. How can I get to those individual entries?

答:
The groups is an array, so when you do the [objectForKey...] call it returns the data as expected. I would assign the returned object to an NSArray as it should always be returned as from that data model as an array, even if it only contains one element.
If you're more curious you can add a breakpoint in and examine it in a debugger, the [objectForKey...] method does some interesting behaviour around type conversions and sometimes the results may surprise you.

Body:
I am using ADAL to authenticate to Azure AD, it returns an dictionary with claims, one of the keys is the groups that a user is a member of,

The full dictionary looks like this

2017-06-05 17:40:58.712 NWMobileTill[46676:3282242] userInfoStore Item all {
    alg = none;
    amr =     (
        pwd
    );
    aud = "042a00fc-b832-411f-xxxxxxxx";
    exp = xxxxxxx;
    groups =     (
        "xxx-9725-43f6-a502-xxxxx",
        "38c5b3af-xxx-4b38-b180-xxxx"
    );
    iat = xxx;
    ipaddr = "xx";
    iss = "https://xxxxxxx/xxx-d61d-xxx-a949-0cb72eff23be/";
    name = "POS Test";
    nbf = xxx;
    oid = "c44f91f2-xx-40bb-9624-xxx";
    platf = 2;
    sub = "xxxxx";
    tid = "b5154a9e-xxx-4d55-a949-xxx";
    typ = JWT;
    "unique_name" = "nwpos@xxxxxx";
    upn = "nwpos@xxxx";
    ver = "1.0";
}

when I access they values in the NSDIctionary using the objectForKey as below

NSDictionary *jongel = [result.tokenCacheStoreItem.userInformation.allClaims objectForKey:@"groups"];

I get multiple entries like this,

2017-06-05 17:40:58.712 NWMobileTill[46676:3282242] Groups are (
"xx-9725-43f6-a502-xx",
"xx-d0dc-4b38-xx-17555db6f626"
)

I am confused that I can get multiple values, how do I access each individual value? I happen to assign this to an NSDictionary but I don't know if that is right. How can I get to those individual entries?


问:
Google Analytics Behaviour Flow
I have an ionic app that is exported to both platforms [iOS and Android]
I was checking the behaviour flow in Google Analytics and got this view :

as we can see only signin /up pages are tracked, however the app has many other screens as shown in the below screenshot:

I am using GoogleAnalytics.trackView("Screen Name") viewDidEnter() function, which is similar to viewDidAppear in iOS.

Can someone help me pointing out why I am not getting the correct flows?

Thank you

答:
My best guess is that it's to do with the way you're reporting your views. I'm not hugely familiar with app reporting, but that Behavior Flows report requires your data to be structured into Sessions.

If, as I suspect is the case, you're accidentally telling Google Analytics that each page is the first page of a Session, then that report will not work at all.

The way to check if this is the case is to look at the Screens per Session value; if it's only fractionally over 1, then this is the issue.

The way to fix it is to look at your Screen View reporting, and make sure that you're not invoking a new Session each time.

Title: Google Analytics Behaviour Flow


问:
error occurs: class SubclassInSamePackage is public, should be declared in a file named SubclassInSamePackage.java
Please help me out with the code the error is

```<code>class SubclassInSamePackage is public, should be declared in a file named SubclassInSamePackage.java
</code>```

Program:

```<code>package pckage1;

class BaseClass {

    public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; //Implicit Default Access Modifier
public int getX() {
    return x;
}
public void setX(int x) {
    this.x = x;
}
private int getY() {
    return y;
}
private void setY(int y) {
    this.y = y;
}
protected int getZ() {
    return z;
}
protected void setZ(int z) {
    this.z = z;
}
int getA() {
    return a;
}
void setA(int a) {
    this.a = a;
}
}

public class SubclassInSamePackage extends BaseClass {

    public static void main(String args[]) {
    BaseClass rr = new BaseClass();
    rr.z = 0;
    SubclassInSamePackage subClassObj = new SubclassInSamePackage();
    //Access Modifiers - Public
    System.out.println("Value of x is : " + subClassObj.x);
    subClassObj.setX(20);
    System.out.println("Value of x is : " + subClassObj.x);
    //Access Modifiers - Public
    //      If we remove the comments it would result in a compilaton
    //      error as the fields and methods being accessed are private
    /*      System.out.println("Value of y is : "+subClassObj.y);

     subClassObj.setY(20);

     System.out.println("Value of y is : "+subClassObj.y);*/
    //Access Modifiers - Protected
    System.out.println("Value of z is : " + subClassObj.z);
    subClassObj.setZ(30);
    System.out.println("Value of z is : " + subClassObj.z);
    //Access Modifiers - Default
    System.out.println("Value of x is : " + subClassObj.a);
    subClassObj.setA(20);
    System.out.println("Value of x is : " + subClassObj.a);
    }
}
</code>```

答:
There can be only one public class in a file and the name of that class should match with that of the filename. </p>

<p>If you want to create multiple classes in the same file, you can mark them as private or "blank" but not public. </p>

Body:
Please help me out with the code the error is

class SubclassInSamePackage is public, should be declared in a file named SubclassInSamePackage.java

Program:

package pckage1;

class BaseClass {

    public int x = 10;
private int y = 10;
protected int z = 10;
int a = 10; //Implicit Default Access Modifier
public int getX() {
    return x;
}
public void setX(int x) {
    this.x = x;
}
private int getY() {
    return y;
}
private void setY(int y) {
    this.y = y;
}
protected int getZ() {
    return z;
}
protected void setZ(int z) {
    this.z = z;
}
int getA() {
    return a;
}
void setA(int a) {
    this.a = a;
}
}

public class SubclassInSamePackage extends BaseClass {

    public static void main(String args[]) {
    BaseClass rr = new BaseClass();
    rr.z = 0;
    SubclassInSamePackage subClassObj = new SubclassInSamePackage();
    //Access Modifiers - Public
    System.out.println("Value of x is : " + subClassObj.x);
    subClassObj.setX(20);
    System.out.println("Value of x is : " + subClassObj.x);
    //Access Modifiers - Public
    //      If we remove the comments it would result in a compilaton
    //      error as the fields and methods being accessed are private
    /*      System.out.println("Value of y is : "+subClassObj.y);

     subClassObj.setY(20);

     System.out.println("Value of y is : "+subClassObj.y);*/
    //Access Modifiers - Protected
    System.out.println("Value of z is : " + subClassObj.z);
    subClassObj.setZ(30);
    System.out.println("Value of z is : " + subClassObj.z);
    //Access Modifiers - Default
    System.out.println("Value of x is : " + subClassObj.a);
    subClassObj.setA(20);
    System.out.println("Value of x is : " + subClassObj.a);
    }
}

Body:
There can be only one public class in a file and the name of that class should match with that of the filename.

If you want to create multiple classes in the same file, you can mark them as private or "blank" but not public.


问:
C# Read Password from Console without showing it
If i use Console.ReadLine() to read a password then all the text entered is visible on the console. How can i read the password without making it visible? </p>

答: You can use Console.ReadKey(true),and concatenate internally chars into a string</p>


问:
How to convert Objective-C App Delegate to Swift?
I am working on old projects converting all classes to Swift.

How can I convert the AppDelegate class to Swift?

What changes must me made in the Project settings or main.m?

答:
None of previous answers worked for me, after some researches, this worked:</p>

```<code>import Foundation

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var bridge: RCTBridge!

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let jsCodeLocation: URL

    jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index.ios", fallbackResource:nil)
    let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "REPLACE_BY_YOUR_PROJECT_NAME", initialProperties: nil, launchOptions: launchOptions)
    let rootViewController = UIViewController()
    rootViewController.view = rootView

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = rootViewController
    self.window?.makeKeyAndVisible()

    return true
  }
}
</code>```

Body:
None of previous answers worked for me, after some researches, this worked:

import Foundation

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
  var bridge: RCTBridge!

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let jsCodeLocation: URL

    jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index.ios", fallbackResource:nil)
    let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "REPLACE_BY_YOUR_PROJECT_NAME", initialProperties: nil, launchOptions: launchOptions)
    let rootViewController = UIViewController()
    rootViewController.view = rootView

    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = rootViewController
    self.window?.makeKeyAndVisible()

    return true
  }
}


问:
Spark insert to HBase slow
I am inserting to HBase using Spark but it's slow. For 60,000 records it takes 2-3mins. I have about 10 million records to save.

```<code>object WriteToHbase extends Serializable {
    def main(args: Array[String]) {
        val csvRows: RDD[Array[String] = ...
        val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
        val usersRDD = csvRows.map(row => {
            new UserTable(row(0), row(1), row(2), row(9), row(10), row(11))
        })
        processUsers(sc: SparkContext, usersRDD, dateFormatter)
    })
}

def processUsers(sc: SparkContext, usersRDD: RDD[UserTable], dateFormatter: DateTimeFormatter): Unit = {

    usersRDD.foreachPartition(part => {
        val conf = HBaseConfiguration.create()
        val table = new HTable(conf, tablename)

        part.foreach(userRow => {
            val id = userRow.id
            val name = userRow.name
            val date1 = dateFormatter.parseDateTime(userRow.date1)
            val hRow = new Put(Bytes.toBytes(id))
            hRow.add(cf, q, Bytes.toBytes(date1))
            hRow.add(cf, q, Bytes.toBytes(name))
            ...
            table.put(hRow)
        })
        table.flushCommits()
        table.close()
    })
}
</code>```

I am using this in spark-submit:

```<code>--num-executors 2 --driver-memory 2G --executor-memory 2G --executor-cores 2
</code>```

答:
You have to look on the approach where you can distribute your incoming data in to the Spark Job. In your current approach of foreachPartition instead you have to look on Transformations like map, mapToPair as well. You need to evaluate your whole DAG lifecycle and where you can save more time.

After that based on the Parallelism achieved you can call saveAsNewAPIHadoopDataset Action of Spark to write inside HBase more fast and parallel. Like:

```<code>JavaPairRDD<ImmutableBytesWritable, Put> yourFinalRDD = yourRDD.<SparkTransformation>{()};
yourFinalRDD.saveAsNewAPIHadoopDataset(yourHBaseConfiguration);
</code>```

Note: Where yourHBaseConfiguration will be a singleton and will be single object on an Executor node to share between the Tasks

Kindly let me know if this Pseudo-code doesn't work for you or find any difficulty on the same.

Title: Spark insert to HBase slow

Body:
I am inserting to HBase using Spark but it's slow. For 60,000 records it takes 2-3mins. I have about 10 million records to save.

object WriteToHbase extends Serializable {
    def main(args: Array[String]) {
        val csvRows: RDD[Array[String] = ...
        val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
        val usersRDD = csvRows.map(row => {
            new UserTable(row(0), row(1), row(2), row(9), row(10), row(11))
        })
        processUsers(sc: SparkContext, usersRDD, dateFormatter)
    })
}

def processUsers(sc: SparkContext, usersRDD: RDD[UserTable], dateFormatter: DateTimeFormatter): Unit = {

    usersRDD.foreachPartition(part => {
        val conf = HBaseConfiguration.create()
        val table = new HTable(conf, tablename)

        part.foreach(userRow => {
            val id = userRow.id
            val name = userRow.name
            val date1 = dateFormatter.parseDateTime(userRow.date1)
            val hRow = new Put(Bytes.toBytes(id))
            hRow.add(cf, q, Bytes.toBytes(date1))
            hRow.add(cf, q, Bytes.toBytes(name))
            ...
            table.put(hRow)
        })
        table.flushCommits()
        table.close()
    })
}

I am using this in spark-submit:

--num-executors 2 --driver-memory 2G --executor-memory 2G --executor-cores 2

Body:
You have to look on the approach where you can distribute your incoming data in to the Spark Job. In your current approach of foreachPartition instead you have to look on Transformations like map, mapToPair as well. You need to evaluate your whole DAG lifecycle and where you can save more time.

After that based on the Parallelism achieved you can call saveAsNewAPIHadoopDataset Action of Spark to write inside HBase more fast and parallel. Like:

JavaPairRDD<ImmutableBytesWritable, Put> yourFinalRDD = yourRDD.<SparkTransformation>{()};
yourFinalRDD.saveAsNewAPIHadoopDataset(yourHBaseConfiguration);

Note: Where yourHBaseConfiguration will be a singleton and will be single object on an Executor node to share between the Tasks

Kindly let me know if this Pseudo-code doesn't work for you or find any difficulty on the same.


问:
Assign value to rows inside a for loop python
I can't figure out why my below code won't assign a new value to the nth row inside the for loop. As far as I know, the way I index the b matrix should be correct but it seems like the count variable won't update for each iteration.
The print statements serve only as a way of checking what is going on.

I assume that it's pretty simple, so I would highly appreciate if one could point out were I'm wrong.

```<code>#!/usr/bin/python
import sys
#from string import maketrans
#import re
import numpy as np

lines = sum(1 for line in sys.stdin)
b = np.zeros((lines,2))

count = 0
for line in sys.stdin:

    line = line.strip()
    myline = line.split(",")

    Depart = myline[3]
    DepartDelay = float(myline[6])

    if DepartDelay<0:

        DepartDelay=0

    b[count,0] = Depart
    b[count, 1] = DepartDelay

    count = count + 1
    print(count)
print(b)
print(count)
</code>```

I use the following command to execute the code within the terminal of Ubuntu.

```<code>cat sample.txt | mapper.py
</code>```

which is why there as such aren't specified any data/text file.

In advance, thank you!

答:
sys.stdin is basically a file object, so it's just my opinion not to do something like for line in sys.stdin (it may technically work, but it's bad form. plus, you have other issues, all ahead)

i would prefer to call read() or readlines() methods on sys.stdin to read the contents

get familiar with the basics of stdin here: How do you read from stdin in Python?

a loop that would work for you should look like this:

```<code>lines = sys.stdin.readlines()
for line in lines:
    do_something(line)
</code>```

but be careful, if you iterate over the entire stdin at the start of your program (when you did lines = sum(1 for line in sys.stdin)) you can't simply start iterating again

a more simple approach for you will be to read all the lines as mentioned above, but if you need the length of lines you can simply do this first:

```<code>count_lines = len(lines)
</code>```

to summarize, the start of your program should be this:

```<code>lines = sys.stdin.readlines()
b = []
count = 0
for line in lines:
    Depart, DepartDelay = do_something(line)
    b.append([Depart, DepartDelay])
</code>```

EDIT: i wouldnt use numpy at all for such a simple problem with multiple types to store (float and string)

Body:
I can't figure out why my below code won't assign a new value to the nth row inside the for loop. As far as I know, the way I index the b matrix should be correct but it seems like the count variable won't update for each iteration.
The print statements serve only as a way of checking what is going on.

I assume that it's pretty simple, so I would highly appreciate if one could point out were I'm wrong.

#!/usr/bin/python
import sys
#from string import maketrans
#import re
import numpy as np

lines = sum(1 for line in sys.stdin)
b = np.zeros((lines,2))

count = 0
for line in sys.stdin:

    line = line.strip()
    myline = line.split(",")

    Depart = myline[3]
    DepartDelay = float(myline[6])

    if DepartDelay<0:

        DepartDelay=0

    b[count,0] = Depart
    b[count, 1] = DepartDelay

    count = count + 1
    print(count)
print(b)
print(count)

I use the following command to execute the code within the terminal of Ubuntu.

cat sample.txt | mapper.py

which is why there as such aren't specified any data/text file.

In advance, thank you!

Body:
sys.stdin is basically a file object, so it's just my opinion not to do something like for line in sys.stdin (it may technically work, but it's bad form. plus, you have other issues, all ahead)

i would prefer to call read() or readlines() methods on sys.stdin to read the contents

get familiar with the basics of stdin here: How do you read from stdin in Python?

a loop that would work for you should look like this:

lines = sys.stdin.readlines()
for line in lines:
    do_something(line)

but be careful, if you iterate over the entire stdin at the start of your program (when you did lines = sum(1 for line in sys.stdin)) you can't simply start iterating again

a more simple approach for you will be to read all the lines as mentioned above, but if you need the length of lines you can simply do this first:

count_lines = len(lines)

to summarize, the start of your program should be this:

lines = sys.stdin.readlines()
b = []
count = 0
for line in lines:
    Depart, DepartDelay = do_something(line)
    b.append([Depart, DepartDelay])

EDIT: i wouldnt use numpy at all for such a simple problem with multiple types to store (float and string)