问:
ViewPager inside Fragment do not Showing ImageView
I'm trying to make carousel view using ViewPager which is in Fragment.

Fragment is also showed by another ViewPager which is in MainActivity.

However, ViewPager in Fragment do not showing ImageView.

I think ViewPager is ok, because when I change ViewPager's background and ImageView's background respectively, only ImageView's background was not showed.

Please help.

MainActivity.java

package com.rudolphriding.giftfriend.activity;

import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.rudolphriding.giftfriend.app.friend.FriendFragment;
import com.rudolphriding.giftfriend.base.BaseActivity;
import com.rudolphriding.giftfriend.app.home.HomeFragment;
import com.rudolphriding.giftfriend.R;
import com.rudolphriding.giftfriend.app.trend.TrendFragment;

public class MainActivity extends BaseActivity
{
    ViewPager viewPager;
    TabLayout tabLayout;
    DrawerLayout drawerLayout;
    View friendDrawer;
    ImageButton menuButton;
    ImageButton slidMenuBackButton;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //view custom action bar
        customActionbar();

        //initialize tab
        initTab();

        friendDrawer = (View) findViewById(R.id.drawer);
        drawerLayout = (DrawerLayout) findViewById(R.id.activity_main);
        menuButton = (ImageButton) findViewById(R.id.actionbar_button_menu);
        slidMenuBackButton = (ImageButton) findViewById(R.id.sidemenu_button_close);

        //set MainPagerAdapter
        viewPager = (ViewPager) findViewById(R.id.activity_main_veiwpager);
        MainPagerAdapter pagerAdapter = new MainPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        //drawer open by button on action bar
        draweOpnebyMenuButton();

        //drawer close by button on slide menu
        drawerClosebyBackButton();

    }

    /* /////////////////////////////////////////////////
    //                                                //
    //                    About UI                    //
    //                                                //
    ///////////////////////////////////////////////// */

    public void customActionbar()
    {
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.item_main_actionbar);
    }

    public void initTab()
    {
        tabLayout = (TabLayout) findViewById(R.id.activity_main_tablayout);
        tabLayout.addTab(tabLayout.newTab().setText("선물스토리"));
        tabLayout.addTab(tabLayout.newTab().setText("친구스토리"));
    }

    /* /////////////////////////////////////////////////
    //                                                //
    //                  About drawer                  //
    //                                                //
    ///////////////////////////////////////////////// */

    public void draweOpnebyMenuButton()
    {
        menuButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                drawerLayout.openDrawer(friendDrawer);
            }
        });
    }

    public void drawerClosebyBackButton()
    {
        slidMenuBackButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                drawerLayout.closeDrawer(friendDrawer);
            }
        });
    }

}
```

<p>BaseActivity is for convenient which extents AppCompatActivity.</p>

<h1>HomeFragment.java</h1>

<pre class="lang-java prettyprint-override"><code>package com.rudolphriding.giftfriend.app.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.rudolphriding.giftfriend.R;
import com.rudolphriding.giftfriend.model.HomeItem;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment
{
    ViewPager viewPager;
    VpAdapter adapter;
    TabLayout tabLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View hView = inflater.inflate(R.layout.fragment_home, container, false);

        viewPager = (ViewPager) hView.findViewById(R.id.home_viewPager);
        adapter = new VpAdapter(getChildFragmentManager());
        viewPager.setAdapter(adapter);

        tabLayout = (TabLayout) hView.findViewById(R.id.home_dotNavi_tabLayout);
        tabLayout.setupWithViewPager(viewPager, true);

        return hView;
    }

    public static HomeFragment newInstance()
    {
        Bundle args = new Bundle();

        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

}
</code>```

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/home_viewPager"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:background="@color/ut_std_main_mint_01">

    </android.support.v4.view.ViewPager>

    <android.support.design.widget.TabLayout
        android:id="@+id/home_dotNavi_tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/home_viewPager"
        app:tabBackground="@drawable/btn_homebanner_round_selector"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp">

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

    <TableLayout
        android:id="@+id/home_buttoncontainer_tableLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/home_viewPager"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="15dp"
        android:stretchColumns="*">
        <TableRow
            android:layout_weight="1"
            android:weightSum="4">
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1" />
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"/>
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"/>
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_weight="1"/>

        </TableRow>

        <TableRow>
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="기념일 별\n추천 선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="감정으로\n찾는 선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="브랜드\n선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_weight="1"
                android:text="선물 기획전"
                android:textAlignment="center"/>

        </TableRow>
    </TableLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="40dp"
        android:background="@drawable/btn_giftfindbg_roundrect_selector"
        style="?android:attr/borderlessButtonStyle"
        android:text="선물 준비 시작하기"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textAlignment="center"
        android:textColor="@color/ut_std_text_gray_01"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>
```

<h1>VpAdapter.java</h1>

<pre class="lang-java prettyprint-override"><code>package com.rudolphriding.giftfriend.app.home;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.View;
import com.rudolphriding.giftfriend.R;

public class VpAdapter extends FragmentStatePagerAdapter {

    private int[] sampleImg = new int[] { R.drawable.img_home_cardviewbg_01, R.drawable.img_home_cardviewbg_02 };

    public VpAdapter(FragmentManager fragmentManager)
    {
        super(fragmentManager);
    }

    @Override
    public int getCount() {
        return sampleImg.length;
    }

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

    @Override
    public Fragment getItem(int position) {
        return VpFragment.create(sampleImg[position]);
    }
}
</code>```

VpFragment.java

package com.rudolphriding.giftfriend.app.home;

import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.rudolphriding.giftfriend.R;

/**
 * Created by LeeJihye on 2017-11-09.
 */

public class VpFragment extends android.support.v4.app.Fragment
{
    private int image;
    private ViewGroup rootView;
    private ImageView imageView;
    private Bitmap bitmapImg;
    BitmapFactory.Options options;

    public static VpFragment create(int image)
    {
        VpFragment fragment = new VpFragment();
        Bundle args = new Bundle();
        args.putInt("image", image);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        image = getArguments().getInt("image");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        rootView = (ViewGroup) inflater.inflate(R.layout.item_home_viewpager, container, false);
        options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        bitmapImg = BitmapFactory.decodeResource(rootView.getResources(), image, options);

        imageView = (ImageView) rootView.findViewById(R.id.viewPager_ImageView);
        imageView.setImageBitmap(bitmapImg);

        return rootView;
    }
}
```

<h1>item_home_viewpager.xml</h1>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/viewPager_ImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/ut_std_text_gray_01"/>

</LinearLayout>
</code>```

答:
There is an exception about bitmap limit of the device. This exception doesn't stop your app but you cannot see the background drawable because of device limit. Every device has it's own limit. Don't think your drawables are so small, if you have a lot of images on the screen, then you will reach that limit.

On This Post
How to avoid the "Canvas: trying to draw too large (216090000bytes) bitmap." exception is explained.

I'm not telling this is your problem but it can be.

Body:
I'm trying to make carousel view using ViewPager which is in Fragment.

Fragment is also showed by another ViewPager which is in MainActivity.

However, ViewPager in Fragment do not showing ImageView.

I think ViewPager is ok, because when I change ViewPager's background and ImageView's background respectively, only ImageView's background was not showed.

Please help.

MainActivity.java

package com.rudolphriding.giftfriend.activity;

import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.rudolphriding.giftfriend.app.friend.FriendFragment;
import com.rudolphriding.giftfriend.base.BaseActivity;
import com.rudolphriding.giftfriend.app.home.HomeFragment;
import com.rudolphriding.giftfriend.R;
import com.rudolphriding.giftfriend.app.trend.TrendFragment;

public class MainActivity extends BaseActivity
{
    ViewPager viewPager;
    TabLayout tabLayout;
    DrawerLayout drawerLayout;
    View friendDrawer;
    ImageButton menuButton;
    ImageButton slidMenuBackButton;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //view custom action bar
        customActionbar();

        //initialize tab
        initTab();

        friendDrawer = (View) findViewById(R.id.drawer);
        drawerLayout = (DrawerLayout) findViewById(R.id.activity_main);
        menuButton = (ImageButton) findViewById(R.id.actionbar_button_menu);
        slidMenuBackButton = (ImageButton) findViewById(R.id.sidemenu_button_close);

        //set MainPagerAdapter
        viewPager = (ViewPager) findViewById(R.id.activity_main_veiwpager);
        MainPagerAdapter pagerAdapter = new MainPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        //drawer open by button on action bar
        draweOpnebyMenuButton();

        //drawer close by button on slide menu
        drawerClosebyBackButton();

    }

    /* /////////////////////////////////////////////////
    //                                                //
    //                    About UI                    //
    //                                                //
    ///////////////////////////////////////////////// */

    public void customActionbar()
    {
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.item_main_actionbar);
    }

    public void initTab()
    {
        tabLayout = (TabLayout) findViewById(R.id.activity_main_tablayout);
        tabLayout.addTab(tabLayout.newTab().setText("선물스토리"));
        tabLayout.addTab(tabLayout.newTab().setText("친구스토리"));
    }

    /* /////////////////////////////////////////////////
    //                                                //
    //                  About drawer                  //
    //                                                //
    ///////////////////////////////////////////////// */

    public void draweOpnebyMenuButton()
    {
        menuButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                drawerLayout.openDrawer(friendDrawer);
            }
        });
    }

    public void drawerClosebyBackButton()
    {
        slidMenuBackButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                drawerLayout.closeDrawer(friendDrawer);
            }
        });
    }

}

BaseActivity is for convenient which extents AppCompatActivity.

HomeFragment.java

package com.rudolphriding.giftfriend.app.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.rudolphriding.giftfriend.R;
import com.rudolphriding.giftfriend.model.HomeItem;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment
{
    ViewPager viewPager;
    VpAdapter adapter;
    TabLayout tabLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View hView = inflater.inflate(R.layout.fragment_home, container, false);

        viewPager = (ViewPager) hView.findViewById(R.id.home_viewPager);
        adapter = new VpAdapter(getChildFragmentManager());
        viewPager.setAdapter(adapter);

        tabLayout = (TabLayout) hView.findViewById(R.id.home_dotNavi_tabLayout);
        tabLayout.setupWithViewPager(viewPager, true);

        return hView;
    }

    public static HomeFragment newInstance()
    {
        Bundle args = new Bundle();

        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

}

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/home_viewPager"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:background="@color/ut_std_main_mint_01">

    </android.support.v4.view.ViewPager>

    <android.support.design.widget.TabLayout
        android:id="@+id/home_dotNavi_tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/home_viewPager"
        app:tabBackground="@drawable/btn_homebanner_round_selector"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp">

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

    <TableLayout
        android:id="@+id/home_buttoncontainer_tableLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/home_viewPager"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="15dp"
        android:stretchColumns="*">
        <TableRow
            android:layout_weight="1"
            android:weightSum="4">
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1" />
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"/>
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"/>
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_weight="1"/>

        </TableRow>

        <TableRow>
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="기념일 별\n추천 선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="감정으로\n찾는 선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="브랜드\n선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_weight="1"
                android:text="선물 기획전"
                android:textAlignment="center"/>

        </TableRow>
    </TableLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="40dp"
        android:background="@drawable/btn_giftfindbg_roundrect_selector"
        style="?android:attr/borderlessButtonStyle"
        android:text="선물 준비 시작하기"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textAlignment="center"
        android:textColor="@color/ut_std_text_gray_01"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

VpAdapter.java

package com.rudolphriding.giftfriend.app.home;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.View;
import com.rudolphriding.giftfriend.R;

public class VpAdapter extends FragmentStatePagerAdapter {

    private int[] sampleImg = new int[] { R.drawable.img_home_cardviewbg_01, R.drawable.img_home_cardviewbg_02 };

    public VpAdapter(FragmentManager fragmentManager)
    {
        super(fragmentManager);
    }

    @Override
    public int getCount() {
        return sampleImg.length;
    }

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

    @Override
    public Fragment getItem(int position) {
        return VpFragment.create(sampleImg[position]);
    }
}

VpFragment.java

package com.rudolphriding.giftfriend.app.home;

import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.rudolphriding.giftfriend.R;

/**
 * Created by LeeJihye on 2017-11-09.
 */

public class VpFragment extends android.support.v4.app.Fragment
{
    private int image;
    private ViewGroup rootView;
    private ImageView imageView;
    private Bitmap bitmapImg;
    BitmapFactory.Options options;

    public static VpFragment create(int image)
    {
        VpFragment fragment = new VpFragment();
        Bundle args = new Bundle();
        args.putInt("image", image);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        image = getArguments().getInt("image");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        rootView = (ViewGroup) inflater.inflate(R.layout.item_home_viewpager, container, false);
        options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        bitmapImg = BitmapFactory.decodeResource(rootView.getResources(), image, options);

        imageView = (ImageView) rootView.findViewById(R.id.viewPager_ImageView);
        imageView.setImageBitmap(bitmapImg);

        return rootView;
    }
}

item_home_viewpager.xml

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

    <ImageView
        android:id="@+id/viewPager_ImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/ut_std_text_gray_01"/>

</LinearLayout>


来源: stackexchange

问:
How to detect whether android app is running UI test with Espresso
I am writing some Espresso tests for Android. I am running in the the following problem:

In order for a certain test case to run properly, I need to disable some features in the app. Therefore, in my app, I need to detect whether I am running Espresso test so that I can disable it. However, I don't want to use BuildConfig.DEBUG to because I don't want those features to be disabled in a debug build. Also, I would like to avoid creating a new buildConfig to avoid too many build variants to be created (we already have a lot of flavors defined).

I was looking for a way to define buildConfigField for test but I couldn't find any reference on Google.

答:
i prefer not to use reflection which is slow on android. Most of us have dagger2 set up for dependency injection. I have a test component set up for testing.  Here is a brief way you can get the application mode (testing or normal):

create a enum:

```<code>public enum ApplicationMode {
    NORMAL,TESTING;
}
</code>```

and a normal AppModule:

```<code>@Module
public class AppModule {

    @Provides
    public ApplicationMode provideApplicationMode(){
        return ApplicationMode.NORMAL;
    }
}
</code>```

create a test runner like me:

```<code>public class PomeloTestRunner extends AndroidJUnitRunner {

    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            return super.newApplication(cl, MyTestApplication.class.getName(), context);
    }
}
</code>```

dont forget to declare it in gradle like this:

```<code>defaultConfig {
testInstrumentationRunner "com.mobile.pomelo.base.PomeloTestRunner"
}
</code>```

Now create a subclass of the AppModule with override method that looks exactly like this and do not mark it as a module above the class definition :

```<code>public class TestAppModule extends AppModule{

    public TestAppModule(Application application) {
        super(application);
    }

    @Override
    public ApplicationMode provideApplicationMode(){
        return ApplicationMode.TESTING; //notice we are testing here
    }
}
</code>```

now in your MyTestApplication class that you declared in custom test runner have the following declared:

```<code>public class PomeloTestApplication extends PomeloApplication {

    @Singleton
    @Component(modules = {AppModule.class})
    public interface TestAppComponent extends AppComponent {
        }

    @Override
    protected AppComponent initDagger(Application application) {
        return DaggerPomeloTestApplication_TestAppComponent.builder()
                .appModule(new TestAppModule(application)) //notice we pass in our Test appModule here that we subclassed which has a ApplicationMode set to testing
                .build();
    }
}
</code>```

Now to use it simply inject it in production code wherever like this:

```<code>@Inject
    ApplicationMode appMode;
</code>```

so when your running espresso tests it will be testing enum but when in production code it will be normal enum.

ps not necessary but if you need to see how my production dagger builds the graph its like this and declared in application subclass:

```<code> protected AppComponent initDagger(Application application) {
        return DaggerAppComponent.builder()
                .appModule(new AppModule(application))
                .build();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i prefer not to use reflection which is slow on android. Most of us have dagger2 set up for dependency injection. I have a test component set up for testing.  Here is a brief way you can get the application mode (testing or normal):

create a enum:

public enum ApplicationMode {
    NORMAL,TESTING;
}

and a normal AppModule:

@Module
public class AppModule {

    @Provides
    public ApplicationMode provideApplicationMode(){
        return ApplicationMode.NORMAL;
    }
}

create a test runner like me:

public class PomeloTestRunner extends AndroidJUnitRunner {

    @Override
    public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
            return super.newApplication(cl, MyTestApplication.class.getName(), context);
    }
}

dont forget to declare it in gradle like this:

defaultConfig {
testInstrumentationRunner "com.mobile.pomelo.base.PomeloTestRunner"
}

Now create a subclass of the AppModule with override method that looks exactly like this and do not mark it as a module above the class definition :

public class TestAppModule extends AppModule{

    public TestAppModule(Application application) {
        super(application);
    }

    @Override
    public ApplicationMode provideApplicationMode(){
        return ApplicationMode.TESTING; //notice we are testing here
    }
}

now in your MyTestApplication class that you declared in custom test runner have the following declared:

public class PomeloTestApplication extends PomeloApplication {

    @Singleton
    @Component(modules = {AppModule.class})
    public interface TestAppComponent extends AppComponent {
        }

    @Override
    protected AppComponent initDagger(Application application) {
        return DaggerPomeloTestApplication_TestAppComponent.builder()
                .appModule(new TestAppModule(application)) //notice we pass in our Test appModule here that we subclassed which has a ApplicationMode set to testing
                .build();
    }
}

Now to use it simply inject it in production code wherever like this:

@Inject
    ApplicationMode appMode;

so when your running espresso tests it will be testing enum but when in production code it will be normal enum.

ps not necessary but if you need to see how my production dagger builds the graph its like this and declared in application subclass:

 protected AppComponent initDagger(Application application) {
        return DaggerAppComponent.builder()
                .appModule(new AppModule(application))
                .build();
    }


问:
How to get cancellation policy for Sabre Flights
I have used InstaFlightSearch to get the flight segments. But I want to get cancellation policy details. I don't know what Sabre API does provide the detail? Thanks.

答:
You can use AirPricing_RulesFromPriceRQ API
As well as RulesFromPriceLLSRQ</p>


问:
HTML5 Touch event: Getting word touched
I'm building a dicionary function for my website for mobile users.
I would like this function:
The user touches on a word, a popup window shows its definition.

I've found out the touch API of HTML5.
But couldn't figure out how to get the word touched.
Any hint?

答:
You can sort of achieve it thanks to the Range API and its handy getBoundingClientRect method.

Indeed, this method allows us to get the position of a textNode, while normally we can only get the position of an Element.

All we have to do then, is to first retrieve the original textNode that got clicked, split its content into as many textNodes as there are words, and grab the one we want.

document.onclick = function(e){ console.log(getWord(e));};
// didn't really test with touch device yet, but should be about the same...
document.ontouchstart = function(e){ console.log(getWord(e.touches[0]));};

function getWord(e) {
  // FF gives us a shortcut
  var target = e.explicitOriginalTarget || e.target,
    // We will use this to get the positions of our textNodes
    range = document.createRange(),
    rect, i;
  // so first let's get the textNode that was clicked
  if (target.nodeType !== 3) {
    var children = target.childNodes;
    i = 0;
    while (i < children.length) {
      range.selectNode(children[i]);
      rect = range.getBoundingClientRect();
      if (rect.left <= e.clientX && rect.right >= e.clientX &&
        rect.top <= e.clientY && rect.bottom >= e.clientY) {
        target = children[i];
        break;
      }
      i++;
    }
  }
  if (target.nodeType !== 3) {
    return '[not a textNode]';
  }
  // Now, let's split its content to words
  var words = target.nodeValue.split(' '),
    textNode, newText;
  i = 0;
  while (i < words.length) {
    // create a new textNode with only this word
    textNode = document.createTextNode((i ? ' ' : '') + words[i]);
    newText = words.slice(i + 1);
    // update the original node's text
    target.nodeValue = newText.length ? (' ' + newText.join(' ')) : '';
    // insert our new textNode
    target.parentNode.insertBefore(textNode, target);
    // get its position
    range.selectNode(textNode);
    rect = range.getBoundingClientRect();
    // if it is the one
    if (rect.left <= e.clientX && rect.right >= e.clientX &&
      rect.top <= e.clientY && rect.bottom >= e.clientY) {
      return words[i];
    }
    i++;
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac fermentum ipsum, in efficitur felis. Nam fringilla semper lectus, pretium luctus tortor. Pellentesque vel aliquet orci. Quisque at accumsan felis. Phasellus a ligula congue, viverra tellus
  sit amet, consequat arcu. Mauris et congue diam, eget vehicula ante. Curabitur varius augue eget augue posuere, ut tincidunt purus sodales. Suspendisse luctus fermentum justo, sed scelerisque ipsum dignissim nec.
</p>
<p>
  Suspendisse sed dui elit. Vivamus laoreet ipsum ut metus finibus, eu ultrices lorem bibendum. Fusce ante nibh, egestas nec neque id, semper volutpat orci. Donec a porta nunc. Sed interdum hendrerit mauris. Donec sed semper eros. Integer rhoncus diam quis
  augue ornare consequat. Sed eleifend congue ante quis malesuada. Maecenas et purus venenatis arcu malesuada condimentum id quis nunc. Integer non suscipit sapien, id iaculis mi.
</p>
<p>
  Mauris cursus mauris vitae nulla tempor lacinia. Quisque tristique ullamcorper magna et consequat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus faucibus sit amet enim non sollicitudin. Aliquam malesuada,
  massa hendrerit condimentum pulvinar, ex est finibus massa, at efficitur velit est eu dolor. Pellentesque facilisis ligula hendrerit lacus efficitur venenatis. Ut pretium turpis quis laoreet mattis. Quisque tempor ornare maximus. Nunc augue urna, egestas
  non lectus at, fringilla pharetra nisl. Pellentesque ac quam cursus, volutpat libero eget, ultricies dolor. Donec eleifend iaculis dui dignissim pulvinar. Cras semper vehicula augue, ut ultricies arcu consectetur ut. Mauris congue turpis justo, ac feugiat
  dolor semper nec. Donec id augue posuere, efficitur nunc in, hendrerit est. Morbi eget pretium odio.
</p>
<p>
  Morbi at volutpat nulla. Pellentesque elementum blandit imperdiet. Morbi id lacinia quam. Sed sed accumsan mauris. Donec nulla mi, rutrum id blandit id, hendrerit at turpis. Integer ante orci, venenatis a felis id, suscipit dignissim metus. Pellentesque
  dictum, lectus aliquam facilisis mattis, nisi est porttitor nulla, et semper enim ante quis ex. Quisque ante magna, viverra et ante quis, fringilla tempor mauris. Phasellus posuere nulla in eleifend egestas. Proin augue arcu, semper quis metus sit amet,
  placerat porta lorem. Integer tempus mi at faucibus posuere. Vestibulum ut malesuada turpis. In malesuada eros nisl, eget laoreet velit auctor vitae.
</p>
<p>
  Aliquam maximus varius metus vel congue. Ut tristique risus metus, in tempor leo tempor laoreet. Donec scelerisque ipsum vitae nisi facilisis eleifend. Vivamus condimentum risus non lectus bibendum elementum. Cras vitae malesuada lorem. Curabitur et posuere
  massa, ut luctus mi. Sed et enim nec nisl sollicitudin semper. Donec eget consectetur leo, a faucibus nulla. Nam accumsan hendrerit neque, ultrices aliquam ex auctor id. Nunc euismod faucibus ullamcorper. Sed ornare interdum congue. Quisque eget erat
  erat. Morbi congue orci vitae porttitor semper.
</p></code>```

Title: HTML5 Touch event: Getting word touched

Body:
You can sort of achieve it thanks to the Range API and its handy getBoundingClientRect method.

Indeed, this method allows us to get the position of a textNode, while normally we can only get the position of an Element.

All we have to do then, is to first retrieve the original textNode that got clicked, split its content into as many textNodes as there are words, and grab the one we want.

document.onclick = function(e){ console.log(getWord(e));};
// didn't really test with touch device yet, but should be about the same...
document.ontouchstart = function(e){ console.log(getWord(e.touches[0]));};

function getWord(e) {
  // FF gives us a shortcut
  var target = e.explicitOriginalTarget || e.target,
    // We will use this to get the positions of our textNodes
    range = document.createRange(),
    rect, i;
  // so first let's get the textNode that was clicked
  if (target.nodeType !== 3) {
    var children = target.childNodes;
    i = 0;
    while (i < children.length) {
      range.selectNode(children[i]);
      rect = range.getBoundingClientRect();
      if (rect.left <= e.clientX && rect.right >= e.clientX &&
        rect.top <= e.clientY && rect.bottom >= e.clientY) {
        target = children[i];
        break;
      }
      i++;
    }
  }
  if (target.nodeType !== 3) {
    return '[not a textNode]';
  }
  // Now, let's split its content to words
  var words = target.nodeValue.split(' '),
    textNode, newText;
  i = 0;
  while (i < words.length) {
    // create a new textNode with only this word
    textNode = document.createTextNode((i ? ' ' : '') + words[i]);
    newText = words.slice(i + 1);
    // update the original node's text
    target.nodeValue = newText.length ? (' ' + newText.join(' ')) : '';
    // insert our new textNode
    target.parentNode.insertBefore(textNode, target);
    // get its position
    range.selectNode(textNode);
    rect = range.getBoundingClientRect();
    // if it is the one
    if (rect.left <= e.clientX && rect.right >= e.clientX &&
      rect.top <= e.clientY && rect.bottom >= e.clientY) {
      return words[i];
    }
    i++;
  }
};

<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac fermentum ipsum, in efficitur felis. Nam fringilla semper lectus, pretium luctus tortor. Pellentesque vel aliquet orci. Quisque at accumsan felis. Phasellus a ligula congue, viverra tellus
  sit amet, consequat arcu. Mauris et congue diam, eget vehicula ante. Curabitur varius augue eget augue posuere, ut tincidunt purus sodales. Suspendisse luctus fermentum justo, sed scelerisque ipsum dignissim nec.
</p>
<p>
  Suspendisse sed dui elit. Vivamus laoreet ipsum ut metus finibus, eu ultrices lorem bibendum. Fusce ante nibh, egestas nec neque id, semper volutpat orci. Donec a porta nunc. Sed interdum hendrerit mauris. Donec sed semper eros. Integer rhoncus diam quis
  augue ornare consequat. Sed eleifend congue ante quis malesuada. Maecenas et purus venenatis arcu malesuada condimentum id quis nunc. Integer non suscipit sapien, id iaculis mi.
</p>
<p>
  Mauris cursus mauris vitae nulla tempor lacinia. Quisque tristique ullamcorper magna et consequat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus faucibus sit amet enim non sollicitudin. Aliquam malesuada,
  massa hendrerit condimentum pulvinar, ex est finibus massa, at efficitur velit est eu dolor. Pellentesque facilisis ligula hendrerit lacus efficitur venenatis. Ut pretium turpis quis laoreet mattis. Quisque tempor ornare maximus. Nunc augue urna, egestas
  non lectus at, fringilla pharetra nisl. Pellentesque ac quam cursus, volutpat libero eget, ultricies dolor. Donec eleifend iaculis dui dignissim pulvinar. Cras semper vehicula augue, ut ultricies arcu consectetur ut. Mauris congue turpis justo, ac feugiat
  dolor semper nec. Donec id augue posuere, efficitur nunc in, hendrerit est. Morbi eget pretium odio.
</p>
<p>
  Morbi at volutpat nulla. Pellentesque elementum blandit imperdiet. Morbi id lacinia quam. Sed sed accumsan mauris. Donec nulla mi, rutrum id blandit id, hendrerit at turpis. Integer ante orci, venenatis a felis id, suscipit dignissim metus. Pellentesque
  dictum, lectus aliquam facilisis mattis, nisi est porttitor nulla, et semper enim ante quis ex. Quisque ante magna, viverra et ante quis, fringilla tempor mauris. Phasellus posuere nulla in eleifend egestas. Proin augue arcu, semper quis metus sit amet,
  placerat porta lorem. Integer tempus mi at faucibus posuere. Vestibulum ut malesuada turpis. In malesuada eros nisl, eget laoreet velit auctor vitae.
</p>
<p>
  Aliquam maximus varius metus vel congue. Ut tristique risus metus, in tempor leo tempor laoreet. Donec scelerisque ipsum vitae nisi facilisis eleifend. Vivamus condimentum risus non lectus bibendum elementum. Cras vitae malesuada lorem. Curabitur et posuere
  massa, ut luctus mi. Sed et enim nec nisl sollicitudin semper. Donec eget consectetur leo, a faucibus nulla. Nam accumsan hendrerit neque, ultrices aliquam ex auctor id. Nunc euismod faucibus ullamcorper. Sed ornare interdum congue. Quisque eget erat
  erat. Morbi congue orci vitae porttitor semper.
</p>


问:
Create a procedure that acts like an object - Scheme
I am trying to create a procedure that would act as an object class. Such as having its own attribute and methods. I am trying to create a make-list procedure that would be bound to a variable (define L1 (make-list)), however I am having issue with implementing the the attribute local-list which is the stored list in the bounded to the variable L1. My issue that no matter how I changed (define local-list '(1 2 3 4)) - I always get Empty on my print-list procedure</p>

```<code>  (define (make-list)
    ;;Helper procedures
    (define (print-list list)
      (if (eq? list '())
        (display "Empty")
        (begin (car list)
          (print-list (cdr list)))))
    (begin
      (define local-list '(1 2 3 4))
      (lambda (x)
        (cond
          ((eq? x 'size)
           (begin
             (display "L1: ")
             (newline)
             (local-list)
             (print-list (local-list))))
           (else #f)))
</code>```

答:
You're pretty close

```<code>(define (make-list)

  ;;Helper procedures
  (define (print-list list)
    (if (eq? list '())
        (display "Empty")
        (begin (displayln (car list)) ; <-display missing
               (print-list (cdr list)))))
  ; no begin here
  (define local-list '(1 2 3 4))

  (lambda (x)
    (cond
      ((eq? x 'size)
       (begin
         (display "L1: ")
         (newline)
         (print-list local-list))) ; <- no call to local-list (2x)
      (else #f))))
</code>```

Testing

```<code>> (define L1 (make-list))
> (L1 'size)
L1:
1
2
3
4
Empty
>
</code>```

Body:
I am trying to create a procedure that would act as an object class. Such as having its own attribute and methods. I am trying to create a make-list procedure that would be bound to a variable (define L1 (make-list)), however I am having issue with implementing the the attribute local-list which is the stored list in the bounded to the variable L1. My issue that no matter how I changed (define local-list '(1 2 3 4)) - I always get Empty on my print-list procedure

  (define (make-list)
    ;;Helper procedures
    (define (print-list list)
      (if (eq? list '())
        (display "Empty")
        (begin (car list)
          (print-list (cdr list)))))
    (begin
      (define local-list '(1 2 3 4))
      (lambda (x)
        (cond
          ((eq? x 'size)
           (begin
             (display "L1: ")
             (newline)
             (local-list)
             (print-list (local-list))))
           (else #f)))

Body:
You're pretty close

(define (make-list)

  ;;Helper procedures
  (define (print-list list)
    (if (eq? list '())
        (display "Empty")
        (begin (displayln (car list)) ; <-display missing
               (print-list (cdr list)))))
  ; no begin here
  (define local-list '(1 2 3 4))

  (lambda (x)
    (cond
      ((eq? x 'size)
       (begin
         (display "L1: ")
         (newline)
         (print-list local-list))) ; <- no call to local-list (2x)
      (else #f))))

Testing

> (define L1 (make-list))
> (L1 'size)
L1:
1
2
3
4
Empty
>


问:
Symfony2 No Metadata Classes to process
After creating entity with:

```<code>php app/console doctrine:generate:entity
</code>```

and while using:

```<code>php app/console doctrine:schema:update --force
</code>```

I encountered:

No Metadata Classes to process.

Entity

```<code>namespace ISLab\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="menu_items")
 */
class MenuItem
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="parent", type="integer")
     */
    private $parent;

    // ...
}
</code>```

答: I've had the same issue. For me it was that my directory called 'Entity' was not in the 'AppBundle' but in the 'src' directory. Moving the 'Entity' directory into the 'AppBundle' directory fixed the problem for me!</p>

Title: Symfony2 No Metadata Classes to process

Body:
After creating entity with:

php app/console doctrine:generate:entity

and while using:

php app/console doctrine:schema:update --force

I encountered:

No Metadata Classes to process.

Entity

namespace ISLab\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="menu_items")
 */
class MenuItem
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(name="parent", type="integer")
     */
    private $parent;

    // ...
}


问:
mule : How to maintain sessions in Web Service consumer
I am trying to add a record in NetSuite by using the same JSESSIONID returned during login call. I fetched the JESSIONID value from cookie header and set it as outbound property for JSESSIONID. And then I am doing add operation using Web Service Consumer. But I am getting the error as Invalid Session ID.
Any ideas on how to use the same session id in subsequent calls to NetSuite.</p>

```<code><set-property propertyName="JSESSIONID" value="#[flowVars.sessionID]" doc:name="Property"/>
        <set-payload value=" <urn:add xmlns:urn="urn:messages_2017_1.platform.webservices.netsuite.com" xmlns:urn1="urn:core_2017_1.platform.webservices.netsuite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:list="urn:relationships_2017_1.lists.webservices.netsuite.com">
         <urn:record xsi:type="list:Customer">
                <list:companyName>ABC</list:companyName>
                <list:subsidiary internalId="1"/>
         </urn:record>
 </urn:add>" doc:name="Set Payload"/>
        <ws:consumer config-ref="Web_Service_Consumer" operation="add" doc:name="Web Service Consumer"/>
</code>```

答:
To persist or maintain application state/session ,you can leverage Object store in Mule.
You can store the JSESSIONID/map of JSESSIONID for particular user in object store and use it in subsequent requests.
Remove them once session is lost/timeout.
Try to explore below links

Managing Application Data Storage with Object Stores

Object Store Connector

Body:
I am trying to add a record in NetSuite by using the same JSESSIONID returned during login call. I fetched the JESSIONID value from cookie header and set it as outbound property for JSESSIONID. And then I am doing add operation using Web Service Consumer. But I am getting the error as Invalid Session ID.
Any ideas on how to use the same session id in subsequent calls to NetSuite.

<set-property propertyName="JSESSIONID" value="#[flowVars.sessionID]" doc:name="Property"/>
        <set-payload value=" <urn:add xmlns:urn="urn:messages_2017_1.platform.webservices.netsuite.com" xmlns:urn1="urn:core_2017_1.platform.webservices.netsuite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:list="urn:relationships_2017_1.lists.webservices.netsuite.com">
         <urn:record xsi:type="list:Customer">
                <list:companyName>ABC</list:companyName>
                <list:subsidiary internalId="1"/>
         </urn:record>
 </urn:add>" doc:name="Set Payload"/>
        <ws:consumer config-ref="Web_Service_Consumer" operation="add" doc:name="Web Service Consumer"/>


问:
WCF Service methods + Synchronous calls from javascript
I have written a WCF service and am trying to call the service methods in a script in my ASPX page.

Eg:

```<code><script language="javascript" type="text/javascript">

<!--

        function Test() {
          **// The following call is an Async call.
          tempuri.org.IService.GetData(1,OnRequestComplete, OnError, "");**
        }

        function OnRequestComplete(result, state) {
            var textBox = $get("txtInput");
            textBox.value = result;

        }
        function OnError(result) {
            var textBox = $get("txtInput");
            textBox.value = result;
        }

    //-->
</script>
</code>```

What I want is to be able to call the service method "synchronously"

eg: var result = tempuri.org.IService.GetData(1);

Is this possible?

答:
If you use regular AJAX you can make your call synchronous.

See: http://www.w3schools.com/Ajax/ajax_xmlhttprequest_send.asp
and scroll down to the part "Asynchronous - True or False?"

Here I use AJAX but sometimes it hangs
www.DomainGuarder.com

ContentLicense: CC BY-SA 2.5

Body:
I have written a WCF service and am trying to call the service methods in a script in my ASPX page.

Eg:

What I want is to be able to call the service method "synchronously"

eg: var result = tempuri.org.IService.GetData(1);

Is this possible?


问:
Adding page to multipage
I use Excel 2016

I want to add a page to a Multi Page control.
For some reason I get the error "Run-time error '13': Type mismatch"

I have a blank Excel file with a UserForm. On the UserForm I have a CommandButton and a MultiPage, both are out of the box. I added the following code to the CommandButton

```<code>Private Sub CommandButton1_Click()
    Dim myPage As Page
    Set myPage = Me.MultiPage1.Pages.Add("testpage", "TestPage")
End Sub
</code>```

Do I need to add references to some toolkit for this to work? For the moment I have the following references active

Visual Basic For Applications

Microsfot Excel 16.0 Object Library

OLE Automation

Microsoft Office 16.0 Object Library

Microsoft Forms 2.0 Object Library

When I write the Dim myPage declaration I get a list of objects.. I have two Page objects? Also when I write

```<code>myPage.
</code>```

to get a list of available things for that object I see the following

CenterFooter

CenterHeader

LeftFooter

LeftHeader

RightFooter

RightHeader

So I assume myPage object is not from the right Page type

答:
This works without getting a reference to the new Page object</p>

```<code>Me.MultiPage1.Pages.Add
Me.MultiPage1.Pages(Me.MultiPage1.Pages.Count - 1).Name = "testpage"
Me.MultiPage1.Pages(Me.MultiPage1.Pages.Count - 1).Caption = "TestPage"
Debug.Print Me.MultiPage1.Pages(Me.MultiPage1.Pages.Count - 1).Name
Debug.Print Me.MultiPage1.Pages(Me.MultiPage1.Pages.Count - 1).Caption
</code>```

Title: Adding page to multipage

Body:
I use Excel 2016

I want to add a page to a Multi Page control.
For some reason I get the error "Run-time error '13': Type mismatch"

I have a blank Excel file with a UserForm. On the UserForm I have a CommandButton and a MultiPage, both are out of the box. I added the following code to the CommandButton

Private Sub CommandButton1_Click()
    Dim myPage As Page
    Set myPage = Me.MultiPage1.Pages.Add("testpage", "TestPage")
End Sub

Do I need to add references to some toolkit for this to work? For the moment I have the following references active

Visual Basic For Applications

Microsfot Excel 16.0 Object Library

OLE Automation

Microsoft Office 16.0 Object Library

Microsoft Forms 2.0 Object Library

When I write the Dim myPage declaration I get a list of objects.. I have two Page objects? Also when I write

myPage.

to get a list of available things for that object I see the following

CenterFooter

CenterHeader

LeftFooter

LeftHeader

RightFooter

RightHeader

So I assume myPage object is not from the right Page type

Body:
This works without getting a reference to the new Page object

Me.MultiPage1.Pages.Add
Me.MultiPage1.Pages(Me.MultiPage1.Pages.Count - 1).Name = "testpage"
Me.MultiPage1.Pages(Me.MultiPage1.Pages.Count - 1).Caption = "TestPage"
Debug.Print Me.MultiPage1.Pages(Me.MultiPage1.Pages.Count - 1).Name
Debug.Print Me.MultiPage1.Pages(Me.MultiPage1.Pages.Count - 1).Caption


问:
Convert : to comma separated value
I came across a row which has multiple values separated by a colon (:).
SQL considers the values to be one and throws an error" Cannot fine the requested Privilege". Example of the row shown below.

```<code>Servername  Instancename    Databasename Environment userid      access
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV       userid SYSADMIN:SERVERADMIN
</code>```

Here 2 roles are requested seperated by :
Need some assistance on how can we make SQL consider the values different?

答:
First, you should fix the data structure.  Storing multiple values in a single column is a bad idea.  Instead, you should have a table, with one row per instance and access (assuming instance is the right entity).

Sometimes you are stuck with other people's really bad design decisions.  For merely searching for a single value, you can use like:

```<code>where ':'  + access + ':' like '%:' + 'SERVERADMIN' + ':%'
</code>```

Such a query cannot take advantage of an index and is limited in optimization options.  The real solution is to create the second table, as described above.

Title: Convert : to comma separated value

Body:
I came across a row which has multiple values separated by a colon (:).
SQL considers the values to be one and throws an error" Cannot fine the requested Privilege". Example of the row shown below.

Servername  Instancename    Databasename Environment userid      access
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV       userid SYSADMIN:SERVERADMIN

Here 2 roles are requested seperated by :
Need some assistance on how can we make SQL consider the values different?

Body:
First, you should fix the data structure.  Storing multiple values in a single column is a bad idea.  Instead, you should have a table, with one row per instance and access (assuming instance is the right entity).

Sometimes you are stuck with other people's really bad design decisions.  For merely searching for a single value, you can use like:

where ':'  + access + ':' like '%:' + 'SERVERADMIN' + ':%'

Such a query cannot take advantage of an index and is limited in optimization options.  The real solution is to create the second table, as described above.


问:
SQL connection from Visual C++ Windows Form project
I'm very new to C++. just created a C++ Windows Forms project using Visual Studio Community 2015. And used the below main function to obtain a SQL connection.

```<code>#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sql.h>

using namespace std;

int main()
{

#define SQL_RESULT_LEN 240
#define SQL_RETURN_CODE_LEN 1000
    //define handles and variables
    SQLHANDLE sqlConnHandle;
    SQLHANDLE sqlStmtHandle;
    SQLHANDLE sqlEnvHandle;
    SQLWCHAR retconstring[SQL_RETURN_CODE_LEN];
    //initializations
    sqlConnHandle = NULL;
    sqlStmtHandle = NULL;
    //allocations
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle))
        goto COMPLETED;
    if (SQL_SUCCESS != SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
        goto COMPLETED;
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle))
        goto COMPLETED;
    //output
    cout << "Attempting connection to SQL Server...";
    cout << "\n";
    //connect to SQL Server

    switch (SQLDriverConnect(sqlConnHandle,
        NULL,
        (SQLWCHAR*)L"Server=P2005\SQLEXPRESS2014;Database=CPPDB;User Id=myuid;Password=mypswd;",

        SQL_NTS,
        retconstring,
        1024,
        NULL,
        SQL_DRIVER_NOPROMPT)) {
    case SQL_SUCCESS:
        cout << "Successfully connected to SQL Server";
        cout << "\n";
        break;
    case SQL_SUCCESS_WITH_INFO:
        cout << "Successfully connected to SQL Server";
        cout << "\n";
        break;
    case SQL_INVALID_HANDLE:
        cout << "Could not connect to SQL Server";
        cout << "\n";
        goto COMPLETED;
    case SQL_ERROR:
        cout << "Could not connect to SQL Server";
        cout << "\n";
        goto COMPLETED;
    default:
        break;
    }
    //if there is a problem connecting then exit application
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlConnHandle, &sqlStmtHandle))
        goto COMPLETED;
    //output
    cout << "\n";
    cout << "Executing T-SQL query...";
    cout << "\n";
    //if there is a problem executing the query then exit application
    //else display query result
    if (SQL_SUCCESS != SQLExecDirect(sqlStmtHandle, (SQLWCHAR*)L"SELECT @@VERSION", SQL_NTS)) {
        cout << "Error querying SQL Server";
        cout << "\n";
        goto COMPLETED;
    }
    else {
        //declare output variable and pointer
        SQLCHAR sqlVersion[SQL_RESULT_LEN];
        SQLINTEGER ptrSqlVersion;
        while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) {
            SQLGetData(sqlStmtHandle, 1, SQL_CHAR, sqlVersion, SQL_RESULT_LEN, &ptrSqlVersion);
            //display query result
            cout << "\nQuery Result:\n\n";
            cout << sqlVersion << endl;
        }
    }
    //close connection and free resources
COMPLETED:
    SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle);
    SQLDisconnect(sqlConnHandle);
    SQLFreeHandle(SQL_HANDLE_DBC, sqlConnHandle);
    SQLFreeHandle(SQL_HANDLE_ENV, sqlEnvHandle);
    //pause the console window - exit when key is pressed
    cout << "\nPress any key to exit...";
    getchar();
    return 0;
}
</code>```

When I build and run the above code, It always gives "Could not connect to SQL Server".
SQL connection string is given below as,

```<code>"Server=P2005\SQLEXPRESS2014;Database=CPPDB;User Id=myuid;Password=mypswd;"
</code>```

I got the above connection string format from this link.
And I'm using Microsoft SQL Server 2014 via SQL Management Studio.

Note : It always triggers the SQL_ERROR case in switch.
I'm trying to trace the error. But I didn't get any luck.

Why this occurs?

Any help would be appreciated.
Thanks.

答:
This is a suggestion.

Try Visual C++ MFC Template.

Include belows.

```<code>//For CDatabase class
#include "odbcinst.h"
#include "afxdb.h"
//
</code>```

Do below stuff anywhere you want.

```<code>    CDatabase database;
    CString SqlString;
    CString strID, strName, strAge;
    CString sDriver = L"ODBC Driver 11 for SQL Server";
    CString sDsn;
    int iRec = 0;

    // Build ODBC connection string
    sDsn.Format(L"ODBC;DRIVER={%s};DSN='';DBQ=%s;DATABASE=MYDBNAME", sDriver, NULL);
    TRY{
        // Open the database
        database.Open(NULL,false,false,sDsn);

    SqlString = "INSERT INTO MY_TABLE (id,name,age) VALUES (1,'Sanjaya',25)";
    database.ExecuteSQL(SqlString);
    // Close the database
    database.Close();
    }CATCH(CDBException, e) {
        // If a database exception occured, show error msg
        AfxMessageBox(L"Database error: " + e->m_strError);
    }
    END_CATCH;
</code>```

You should create ODBC Datasource, and it should specify as "ODBC Driver 11 for SQL Server".
I'm using VS Community 2015 and SQL Server 2014.

Body:
I'm very new to C++. just created a C++ Windows Forms project using Visual Studio Community 2015. And used the below main function to obtain a SQL connection.

#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sql.h>

using namespace std;

int main()
{

#define SQL_RESULT_LEN 240
#define SQL_RETURN_CODE_LEN 1000
    //define handles and variables
    SQLHANDLE sqlConnHandle;
    SQLHANDLE sqlStmtHandle;
    SQLHANDLE sqlEnvHandle;
    SQLWCHAR retconstring[SQL_RETURN_CODE_LEN];
    //initializations
    sqlConnHandle = NULL;
    sqlStmtHandle = NULL;
    //allocations
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlEnvHandle))
        goto COMPLETED;
    if (SQL_SUCCESS != SQLSetEnvAttr(sqlEnvHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0))
        goto COMPLETED;
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_DBC, sqlEnvHandle, &sqlConnHandle))
        goto COMPLETED;
    //output
    cout << "Attempting connection to SQL Server...";
    cout << "\n";
    //connect to SQL Server

    switch (SQLDriverConnect(sqlConnHandle,
        NULL,
        (SQLWCHAR*)L"Server=P2005\SQLEXPRESS2014;Database=CPPDB;User Id=myuid;Password=mypswd;",

        SQL_NTS,
        retconstring,
        1024,
        NULL,
        SQL_DRIVER_NOPROMPT)) {
    case SQL_SUCCESS:
        cout << "Successfully connected to SQL Server";
        cout << "\n";
        break;
    case SQL_SUCCESS_WITH_INFO:
        cout << "Successfully connected to SQL Server";
        cout << "\n";
        break;
    case SQL_INVALID_HANDLE:
        cout << "Could not connect to SQL Server";
        cout << "\n";
        goto COMPLETED;
    case SQL_ERROR:
        cout << "Could not connect to SQL Server";
        cout << "\n";
        goto COMPLETED;
    default:
        break;
    }
    //if there is a problem connecting then exit application
    if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, sqlConnHandle, &sqlStmtHandle))
        goto COMPLETED;
    //output
    cout << "\n";
    cout << "Executing T-SQL query...";
    cout << "\n";
    //if there is a problem executing the query then exit application
    //else display query result
    if (SQL_SUCCESS != SQLExecDirect(sqlStmtHandle, (SQLWCHAR*)L"SELECT @@VERSION", SQL_NTS)) {
        cout << "Error querying SQL Server";
        cout << "\n";
        goto COMPLETED;
    }
    else {
        //declare output variable and pointer
        SQLCHAR sqlVersion[SQL_RESULT_LEN];
        SQLINTEGER ptrSqlVersion;
        while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) {
            SQLGetData(sqlStmtHandle, 1, SQL_CHAR, sqlVersion, SQL_RESULT_LEN, &ptrSqlVersion);
            //display query result
            cout << "\nQuery Result:\n\n";
            cout << sqlVersion << endl;
        }
    }
    //close connection and free resources
COMPLETED:
    SQLFreeHandle(SQL_HANDLE_STMT, sqlStmtHandle);
    SQLDisconnect(sqlConnHandle);
    SQLFreeHandle(SQL_HANDLE_DBC, sqlConnHandle);
    SQLFreeHandle(SQL_HANDLE_ENV, sqlEnvHandle);
    //pause the console window - exit when key is pressed
    cout << "\nPress any key to exit...";
    getchar();
    return 0;
}

When I build and run the above code, It always gives "Could not connect to SQL Server".
SQL connection string is given below as,

"Server=P2005\SQLEXPRESS2014;Database=CPPDB;User Id=myuid;Password=mypswd;"

I got the above connection string format from this link.
And I'm using Microsoft SQL Server 2014 via SQL Management Studio.

Note : It always triggers the SQL_ERROR case in switch.
I'm trying to trace the error. But I didn't get any luck.

Why this occurs?

Any help would be appreciated.
Thanks.

Body:
This is a suggestion.

Try Visual C++ MFC Template.

Include belows.

//For CDatabase class
#include "odbcinst.h"
#include "afxdb.h"
//

Do below stuff anywhere you want.

    CDatabase database;
    CString SqlString;
    CString strID, strName, strAge;
    CString sDriver = L"ODBC Driver 11 for SQL Server";
    CString sDsn;
    int iRec = 0;

    // Build ODBC connection string
    sDsn.Format(L"ODBC;DRIVER={%s};DSN='';DBQ=%s;DATABASE=MYDBNAME", sDriver, NULL);
    TRY{
        // Open the database
        database.Open(NULL,false,false,sDsn);

    SqlString = "INSERT INTO MY_TABLE (id,name,age) VALUES (1,'Sanjaya',25)";
    database.ExecuteSQL(SqlString);
    // Close the database
    database.Close();
    }CATCH(CDBException, e) {
        // If a database exception occured, show error msg
        AfxMessageBox(L"Database error: " + e->m_strError);
    }
    END_CATCH;

You should create ODBC Datasource, and it should specify as "ODBC Driver 11 for SQL Server".
I'm using VS Community 2015 and SQL Server 2014.


问:
How to change a oldest version object to latest version object in aws s3 without deleting new versions
In aws s3 versioning enabled buckets we can upload same name objects, it preserved in buckets with version Id. If i upload 10 versions in a bucket the latest version is which was i upload last.

If i want to make my 4th version as latest version, one way to do this  removing all latest 6 versions it automatically change the 4th version as a latest version.

Another way is re upload a version 4 , it takes as 11th version & also it is a latest version. We upload a existing object with its old version ID.

How we can do the second way in AWS command line interface ?

答:
I found Solution to re upload object with its older version Id.
"copy-object" command can be used.

aws s3api copy-object --bucket YOUR BUCKET--key img.jpg --copy-source "YOUR BUCKET/img.jpg?versionId=fRP7UzABrXTsBgBu9WAhZ0VgU3pif9Lp" --acl public-read

it copy the old version as new version ...


问:
Error C1083 Cannot open include file: 'vtkGUISupportQtOpenGLModule.h': No such file or directory
I'm trying to link VTK library to my project on Windows 7. The error I get is:

Error  C1083   Cannot open include file: 'vtkGUISupportQtOpenGLModule.h': No such file or directory

The thing in my code that provokes the error is #include<QVTKWidget2.h>.

Src and build directories of my VTK copy are separate. The linking tool I use is cmake. The build tool: VS 2015.

My CMakeLists.txt and VTK's cache u can see below.

Thanks in advance for any suggestions.

CMakeLists.txt

```<code>cmake_minimum_required(VERSION 2.8)
set(PROJECT Pro)
project(${PROJECT})

set(BUILD_SHARED_LIBS false)
message("  BUILD_SHARED_LIBS " ${BUILD_SHARED_LIBS})
list(APPEND CMAKE_EXE_LINKER_FLAGS -static)

find_package(VTK REQUIRED)
include(${VTK_USE_FILE})

set(VTK_INCLUDE_DIRS
    "D:/libs/VTK-7.1.1"
    )

set(VTK_QT_INCLUDE_DIR
    "D:/libs/VTK-7.1.1/GUISupport/QtOpenGL"
    )

include_directories(${VTK_INCLUDE_DIRS} ${VTK_QT_INCLUDE_DIR})

# ... Local src declaration

add_executable(${PROJECT} ${PRO_APP_HEADERS}${PRO_APP_SOURCES})

if(VTK_LIBRARIES)
  message("VTK_LIBRARIES is set.")
  target_link_libraries(${PROJECT} ${VTK_LIBRARIES})
else(VTK_LIBRARIES)
  message("! VTK_LIBRARIES are not set completely")
  target_link_libraries(${PROJECT} vtkHybrid vtkWidgets)
endif(VTK_LIBRARIES)
</code>```

VTK's cache
enter image description here

答: Ensure that file "vtkGUISupportQtOpenGLModule.h" is actually located in one of those included dirs (${VTK_INCLUDE_DIRS}  or  ${VTK_QT_INCLUDE_DIR})  (you did not mention whether it is there), and that you have permissions to it.</p>

Body:
I'm trying to link VTK library to my project on Windows 7. The error I get is:

Error  C1083   Cannot open include file: 'vtkGUISupportQtOpenGLModule.h': No such file or directory

The thing in my code that provokes the error is #include<QVTKWidget2.h>.

Src and build directories of my VTK copy are separate. The linking tool I use is cmake. The build tool: VS 2015.

My CMakeLists.txt and VTK's cache u can see below.

Thanks in advance for any suggestions.

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)
set(PROJECT Pro)
project(${PROJECT})

set(BUILD_SHARED_LIBS false)
message("  BUILD_SHARED_LIBS " ${BUILD_SHARED_LIBS})
list(APPEND CMAKE_EXE_LINKER_FLAGS -static)

find_package(VTK REQUIRED)
include(${VTK_USE_FILE})

set(VTK_INCLUDE_DIRS
    "D:/libs/VTK-7.1.1"
    )

set(VTK_QT_INCLUDE_DIR
    "D:/libs/VTK-7.1.1/GUISupport/QtOpenGL"
    )

include_directories(${VTK_INCLUDE_DIRS} ${VTK_QT_INCLUDE_DIR})

# ... Local src declaration

add_executable(${PROJECT} ${PRO_APP_HEADERS}${PRO_APP_SOURCES})

if(VTK_LIBRARIES)
  message("VTK_LIBRARIES is set.")
  target_link_libraries(${PROJECT} ${VTK_LIBRARIES})
else(VTK_LIBRARIES)
  message("! VTK_LIBRARIES are not set completely")
  target_link_libraries(${PROJECT} vtkHybrid vtkWidgets)
endif(VTK_LIBRARIES)

VTK's cache
enter image description here


问:
React+redux get data from child component
I have creator, I mean step1 -next-> step2 -next-> ...
In my parent component I have buttons preview and next, steps content are render as child.

```<code>class MyCreator extends React.Component {
   render() {
      return (
         <div>
            {this.renderStep(this.props.step.id)}
         </div>
         <div>
            <button>back</button>
            <button>next</button>
         </div>
      );
   }
}
</code>```

In a step  I have a component which has only two methods: getData, setData. This is a third party component (so I cannot change implementation).
When I click button next I want to getData from the current step. I mean call some generic method on each step child component, like leaveStep. Then leaveStep returns some data, which I will pass to redux action.

答:
If I got it right, the ideal solution would be lifting state up to the Parent component, take a look at this part of the React documentation. But since you don't have control of your components and it may create you some problems to sync the states. Something like this will do the trick:

```<code>class Parent extends Component {
    state = {
        childData: null
    }

    getChildData = (data) => {
        this.setState({
            childData: data,
        }, () => { console.log(this.state); });
    }
    render() {
        return <Child setData={this.getChildData} />
    }
}

class Child extends Component {
    state = {
        data: 'this is child data'
    }

    render() {
        return <button onClick={() => this.props.setData(this.state.data)}>Next</button>;
    }
}
</code>```

But remember that this creates a duplicate state, breaking the single source of truth and can be very messy for large applications.

Body:
I have creator, I mean step1 -next-> step2 -next-> ...
In my parent component I have buttons preview and next, steps content are render as child.

class MyCreator extends React.Component {
   render() {
      return (

            {this.renderStep(this.props.step.id)}

            <button>back</button>
            <button>next</button>

      );
   }
}

In a step  I have a component which has only two methods: getData, setData. This is a third party component (so I cannot change implementation).
When I click button next I want to getData from the current step. I mean call some generic method on each step child component, like leaveStep. Then leaveStep returns some data, which I will pass to redux action.

Body:
If I got it right, the ideal solution would be lifting state up to the Parent component, take a look at this part of the React documentation. But since you don't have control of your components and it may create you some problems to sync the states. Something like this will do the trick:

class Parent extends Component {
    state = {
        childData: null
    }

    getChildData = (data) => {
        this.setState({
            childData: data,
        }, () => { console.log(this.state); });
    }
    render() {
        return <Child setData={this.getChildData} />
    }
}

class Child extends Component {
    state = {
        data: 'this is child data'
    }

    render() {
        return <button onClick={() => this.props.setData(this.state.data)}>Next</button>;
    }
}

But remember that this creates a duplicate state, breaking the single source of truth and can be very messy for large applications.


问:
Why undefined elements inside ngOnInit method in Angular
I am initializing a library in my ngOnInit method as follows:

```<code>ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});
......
}
</code>```

then i am calling this method from that instance, inside ngOnInit as well:

```<code> // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);
} );
</code>```

so it the method finally looks like this:

```<code>ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});

 // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);
} );

}
</code>```

But I dont understand why the result printed by console.log is undefined if actually is this.$grid who is calling console.log.

I need to use that instance again inside that method to do something like this:

```<code>// bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  this.$grid.masonry('layout');
} );
</code>```

but I can not because this.$grid is undefined inside that method which does no makes sense for me at all.

Any ideas?

答:
try call these inside the AfterViewInit callback lifecycle.

```<code>ngAfterViewInit(): void {
  this.$grid = jQuery('.grid').masonry({
  itemSelector: '.grid-item',
  columnWidth: 384,
  gutter: 24
 });
 this.$grid.on( 'layoutComplete',() => {
  console.log(this.$grid);
 });
}
</code>```

ngAfterViewInit(): Respond after Angular initializes the component's views and child views.
  Called once after the first ngAfterContentChecked().
  A component-only hook.

see angular documentation
https://angular.io/guide/lifecycle-hooks

Body:
I am initializing a library in my ngOnInit method as follows:

ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});
......
}

then i am calling this method from that instance, inside ngOnInit as well:

 // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);
} );

so it the method finally looks like this:

ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});

 // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);
} );

}

But I dont understand why the result printed by console.log is undefined if actually is this.$grid who is calling console.log.

I need to use that instance again inside that method to do something like this:

// bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  this.$grid.masonry('layout');
} );

but I can not because this.$grid is undefined inside that method which does no makes sense for me at all.

Any ideas?

Body:
try call these inside the AfterViewInit callback lifecycle.

ngAfterViewInit(): void {
  this.$grid = jQuery('.grid').masonry({
  itemSelector: '.grid-item',
  columnWidth: 384,
  gutter: 24
 });
 this.$grid.on( 'layoutComplete',() => {
  console.log(this.$grid);
 });
}

ngAfterViewInit(): Respond after Angular initializes the component's views and child views.
  Called once after the first ngAfterContentChecked().
  A component-only hook.

see angular documentation
https://angular.io/guide/lifecycle-hooks


问:
RestTemplate not working with S3 pre-signed put URLs
I have a server generate AWS S3 pre-signed PUT URLs and then I'm trying to uploading a byte[] into that URL using RestTemplate with this code:

```<code>RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<byte[]> entity = new HttpEntity<>("Testing testing testing".getBytes(), headers);
System.out.println(restTemplate.exchange(putUrl, HttpMethod.PUT, entity, String.class));
</code>```

When I run that code, I get this error:

```<code>Exception in thread "JavaFX Application Thread" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at tech.dashman.dashman.controllers.RendererAppController.lambda$null$2(RendererAppController.java:95)
</code>```

Unfortunately, there's nothing in the AWS S3 logs, so, I'm not sure what's going on. If I take that exact same URL and put it in the REST Client of IntelliJ IDEA, it just works (it creates an empty file in S3).

Any ideas what's wrong with my Java code?

Here's a full example that does the signing and tries to uploading a small payload to S3:

```<code>import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import org.joda.time.DateTime;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
import java.util.Date;

public class S3PutIssue {
    static public void main(String[] args) {
        String awsAccessKeyId = "";
        String awsSecretKey = "";
        String awsRegion = "";
        String path = "";
        String awsBucketName = "";
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretKey);
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(awsRegion).
                withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).build();
        Date expiration = new DateTime().plusDays(1).toDate();
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(awsBucketName, path);
        urlRequest.setMethod(HttpMethod.PUT);
        urlRequest.setExpiration(expiration);
        String putUrl = s3Client.generatePresignedUrl(urlRequest).toString();

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<byte[]> entity = new HttpEntity<>("Testing testing testing".getBytes(), headers);
        restTemplate.exchange(putUrl, org.springframework.http.HttpMethod.PUT, entity, Void.class);
    }
}
</code>```

答:
Do not convert your URL to String.  Instead convert it to URI.  I think there are some encoding issues when you converted to String.  For example the URL in String format had %252F, where it should have just been %2F.  Looks like some sort of double encoding issue.

Leave as URL...

```<code>     URL putUrl = amazonS3Client.generatePresignedUrl(urlRequest);
</code>```

Convert to URI...

```<code>    ResponseEntity<String> re = restTemplate.exchange(putUrl.toURI(), org.springframework.http.HttpMethod.PUT, entity, String.class);
</code>```

EDIT:  More info to clarify what is going on.

The problem that occurred here is that when you call URL.toString() in this instance you are given back an encoded String representation of the URL.  But the RestTemplate is expecting a String url that is not yet encoded.  RestTemplate will do the encoding for you.

For example look at the code below...

```<code>public static void main(String[] args) {
    RestTemplate rt = new RestTemplate();
    rt.exchange("http://foo.com/?var=<val>", HttpMethod.GET, HttpEntity.EMPTY, String.class);
}
</code>```

When you run this you get the following debug message from Spring, notice how the url in the debug msg is encoded.

```<code>[main] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://foo.com/?var=%3Cval%3E"
</code>```

So you can see the RestTemplate will encode for you any String url's passed to it.  But the URL provided by AmazonS3Client is already encoded.  See the code below.

```<code>URL putUrl = amazonS3Client.generatePresignedUrl(urlRequest);
System.out.println("putUrl.toString = " + putUrl.toString());
</code>```

This prints out a String that is already encoded.

```<code>https://private.s3.amazonaws.com/testing/?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20171114T191829Z&X-Amz-SignedHeaders=host&X-Amz-Expires=0&X-Amz-Credential=AKIAIJ7ZSL22IJTM6NTQ%2F20171114%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=eca611ea33d9ad5710207568dcf181e4318ce39271fd0f1ce05bd99ebbf4097
</code>```

So when I stick that into the exchange method of the RestTemplate I get the following debug message.

```<code>[main] DEBUG org.springframework.web.client.RestTemplate - PUT request for "https://turretmaster.s3.amazonaws.com/testing/?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20171114T191829Z&X-Amz-SignedHeaders=host&X-Amz-Expires=0&X-Amz-Credential=AKIAIJ7ZSL22IJTM6NTQ%252F20171114%252Fus-east-1%252Fs3%252Faws4_request&X-Amz-Signature=eca611ea33d9ad5710207568dcf181e4318ce39271fd0f1ce05bd99ebbf40975"
</code>```

Notice how every %2F from the url String turned into %252F.  %2F is the encoded representation of /.  But %25 is %.  So it encoded a url that was already encoded.  The solution was to pass a URI object to RestTemplate.exchange, instead of an encoded String url.

Body:
I have a server generate AWS S3 pre-signed PUT URLs and then I'm trying to uploading a byte[] into that URL using RestTemplate with this code:

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
HttpEntity<byte[]> entity = new HttpEntity<>("Testing testing testing".getBytes(), headers);
System.out.println(restTemplate.exchange(putUrl, HttpMethod.PUT, entity, String.class));

When I run that code, I get this error:

Exception in thread "JavaFX Application Thread" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at tech.dashman.dashman.controllers.RendererAppController.lambda$null$2(RendererAppController.java:95)

Unfortunately, there's nothing in the AWS S3 logs, so, I'm not sure what's going on. If I take that exact same URL and put it in the REST Client of IntelliJ IDEA, it just works (it creates an empty file in S3).

Any ideas what's wrong with my Java code?

Here's a full example that does the signing and tries to uploading a small payload to S3:

import com.amazonaws.HttpMethod;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import org.joda.time.DateTime;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
import java.util.Date;

public class S3PutIssue {
    static public void main(String[] args) {
        String awsAccessKeyId = "";
        String awsSecretKey = "";
        String awsRegion = "";
        String path = "";
        String awsBucketName = "";
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretKey);
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(awsRegion).
                withCredentials(new AWSStaticCredentialsProvider(awsCredentials)).build();
        Date expiration = new DateTime().plusDays(1).toDate();
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(awsBucketName, path);
        urlRequest.setMethod(HttpMethod.PUT);
        urlRequest.setExpiration(expiration);
        String putUrl = s3Client.generatePresignedUrl(urlRequest).toString();

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<byte[]> entity = new HttpEntity<>("Testing testing testing".getBytes(), headers);
        restTemplate.exchange(putUrl, org.springframework.http.HttpMethod.PUT, entity, Void.class);
    }
}

Body:
Do not convert your URL to String.  Instead convert it to URI.  I think there are some encoding issues when you converted to String.  For example the URL in String format had %252F, where it should have just been %2F.  Looks like some sort of double encoding issue.

Leave as URL...

     URL putUrl = amazonS3Client.generatePresignedUrl(urlRequest);

Convert to URI...

    ResponseEntity<String> re = restTemplate.exchange(putUrl.toURI(), org.springframework.http.HttpMethod.PUT, entity, String.class);

EDIT:  More info to clarify what is going on.

The problem that occurred here is that when you call URL.toString() in this instance you are given back an encoded String representation of the URL.  But the RestTemplate is expecting a String url that is not yet encoded.  RestTemplate will do the encoding for you.

For example look at the code below...

public static void main(String[] args) {
    RestTemplate rt = new RestTemplate();
    rt.exchange("http://foo.com/?var=<val>", HttpMethod.GET, HttpEntity.EMPTY, String.class);
}

When you run this you get the following debug message from Spring, notice how the url in the debug msg is encoded.

[main] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://foo.com/?var=%3Cval%3E"

So you can see the RestTemplate will encode for you any String url's passed to it.  But the URL provided by AmazonS3Client is already encoded.  See the code below.

URL putUrl = amazonS3Client.generatePresignedUrl(urlRequest);
System.out.println("putUrl.toString = " + putUrl.toString());

This prints out a String that is already encoded.

https://private.s3.amazonaws.com/testing/?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20171114T191829Z&X-Amz-SignedHeaders=host&X-Amz-Expires=0&X-Amz-Credential=AKIAIJ7ZSL22IJTM6NTQ%2F20171114%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=eca611ea33d9ad5710207568dcf181e4318ce39271fd0f1ce05bd99ebbf4097

So when I stick that into the exchange method of the RestTemplate I get the following debug message.

[main] DEBUG org.springframework.web.client.RestTemplate - PUT request for "https://turretmaster.s3.amazonaws.com/testing/?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20171114T191829Z&X-Amz-SignedHeaders=host&X-Amz-Expires=0&X-Amz-Credential=AKIAIJ7ZSL22IJTM6NTQ%252F20171114%252Fus-east-1%252Fs3%252Faws4_request&X-Amz-Signature=eca611ea33d9ad5710207568dcf181e4318ce39271fd0f1ce05bd99ebbf40975"

Notice how every %2F from the url String turned into %252F.  %2F is the encoded representation of /.  But %25 is %.  So it encoded a url that was already encoded.  The solution was to pass a URI object to RestTemplate.exchange, instead of an encoded String url.


问:
"Command not found" piping a variable to cut when output stored in a variable
In a bash script I am using a variable to hold a path like this:

```<code>MY_DIR=/just/a/string/to/my/path
</code>```

And I want to remove the last two parts of it so it looks like this:

```<code>/just/a/string
</code>```

I am using 'cut' to do it, like this:

```<code>echo $MY_DIR | cut -d'/' -f-4
</code>```

The output is what I expect. Fine.
But I want to store in an other variable, like this:

```<code>MY_DIR2=$($MY_DIR | cut -d'/' -f-4)
</code>```

When I execute the script I get the error:

```<code>... /just/a/string/to/my/path: No such file or directory
</code>```

Why is the direct output with echo working, but storing the output in a variable is not?

答:
Use the grave accent(`) to emulate a command, and use echo too.</p>

```<code>MY_DIR2=`echo $MY_DIR | cut -d'/' -f-4`
</code>```

Body:
In a bash script I am using a variable to hold a path like this:

MY_DIR=/just/a/string/to/my/path

And I want to remove the last two parts of it so it looks like this:

/just/a/string

I am using 'cut' to do it, like this:

echo $MY_DIR | cut -d'/' -f-4

The output is what I expect. Fine.
But I want to store in an other variable, like this:

MY_DIR2=$($MY_DIR | cut -d'/' -f-4)

When I execute the script I get the error:

... /just/a/string/to/my/path: No such file or directory

Why is the direct output with echo working, but storing the output in a variable is not?

Body:
Use the grave accent(`) to emulate a command, and use echo too.

MY_DIR2=`echo $MY_DIR | cut -d'/' -f-4`


问:
I need to set default username(i.e username by windows log in) value in userid label for some security reasons and how can i do that?
I need to set my user-id(default) from the windows logged in for security reason and i don't have any idea,
Here is my code:</p>

```<code>import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldExample {
    public static void main(String[] args) {
    JFrame f=new JFrame("User-ID");
     final JLabel label = new JLabel();
     label.setBounds(20,150, 200,50);

     JLabel l1=new JLabel("User-Id:");
        l1.setBounds(20,20, 80,30);
        JButton b = new JButton("Login");
        b.setBounds(100,120, 80,30);
        final JTextField text = new JTextField(12); text.setText(System.getProperty("user.name")); text.setBounds(100, 20, 100, 30);
               f.add(l1); f.add(label); f.add(b); f.add(text);
                f.setSize(300,300);
                f.setLayout(null);
                f.setVisible(true);
               /** b.addActionListener(new ActionListener() {
                // public void actionPerformed(ActionEvent e) {
                 //  String data = "Username " + text.getText();
                  // label.setText(data);
               // }
        });   */
    }
}
</code>```

答: use java's System.getProperty("user.name"); for a default account name

Body:
I need to set my user-id(default) from the windows logged in for security reason and i don't have any idea,
Here is my code:

import javax.swing.*;
import java.awt.event.*;
public class PasswordFieldExample {
    public static void main(String[] args) {
    JFrame f=new JFrame("User-ID");
     final JLabel label = new JLabel();
     label.setBounds(20,150, 200,50);

     JLabel l1=new JLabel("User-Id:");
        l1.setBounds(20,20, 80,30);
        JButton b = new JButton("Login");
        b.setBounds(100,120, 80,30);
        final JTextField text = new JTextField(12); text.setText(System.getProperty("user.name")); text.setBounds(100, 20, 100, 30);
               f.add(l1); f.add(label); f.add(b); f.add(text);
                f.setSize(300,300);
                f.setLayout(null);
                f.setVisible(true);
               /** b.addActionListener(new ActionListener() {
                // public void actionPerformed(ActionEvent e) {
                 //  String data = "Username " + text.getText();
                  // label.setText(data);
               // }
        });   */
    }
}


问:
Unable to add a source with url that begins with 'git@github.com'
In my Podfile I have this kind of operations:

```<code>source 'https://github.com/CocoaPods/Specs.git'
source 'git@github.com:xxxxxxx/cocoapods-specs.git'
</code>```

And recive :

```<code> Unable to add a source with url `git@github.com:xxxxxxx/cocoapods-specs.git`
</code>```

But when I change git@github.com to https://github.com everything is working fine.

Could you pls share you're experience about how could I use git@github.com kind of the declaration ?

Should I use some macros ?

答:
To be able to use git@github.com:xxxxxxx/cocoapods-specs.git style you should add SSH keys to verify you're account.

You can do this in SSH and GPG keys section in GitHub settings tab.

To generete SSH key pls follow this link.

Body:
In my Podfile I have this kind of operations:

source 'https://github.com/CocoaPods/Specs.git'
source 'git@github.com:xxxxxxx/cocoapods-specs.git'

And recive :

 Unable to add a source with url `git@github.com:xxxxxxx/cocoapods-specs.git`

But when I change git@github.com to https://github.com everything is working fine.

Could you pls share you're experience about how could I use git@github.com kind of the declaration ?

Should I use some macros ?


问:
Is there a native interface that matches "string" and "Object that implements __toString()"?
We have objects that implement __toString():

```<code>class Foo {
    public function __toString()
    {
        return 'bar';
    }
}
</code>```

Then we have functions that return either string or object that implement __toString(), like the example above.

While using return type string for strings works of course:

```<code>function getString():string {
    return 'Works!';
}
</code>```

Returning object of type Foo does not work, because it's not a string:

```<code>function getString(Foo $foo):string {
    return $foo; // Fatal TypeError!
}
</code>```

Is there any PHP interface that we can use to type hint both string and objects that implement that unknown interface, e.g. Printable or Stringable (lol)?

The goal is to being able to return either string or objects that implement a specific interface (which would enforce the implementation of __toString).

答: Strings and objects implementing __toString are not interchangeable, for instance $s[1] will fail on an object (unless it implements some other magic methods). An object might be a valid substitute in contexts where an argument is coerced to a string anyway, but that doesn't apply to all possible operations you can do on a string. So, no, there's no native interface for that, and you shouldn't intermix these types for this reason either.

ContentLicense: CC BY-SA 4.0

Body:
We have objects that implement __toString():

class Foo {
    public function __toString()
    {
        return 'bar';
    }
}

Then we have functions that return either string or object that implement __toString(), like the example above.

While using return type string for strings works of course:

function getString():string {
    return 'Works!';
}

Returning object of type Foo does not work, because it's not a string:

function getString(Foo $foo):string {
    return $foo; // Fatal TypeError!
}

Is there any PHP interface that we can use to type hint both string and objects that implement that unknown interface, e.g. Printable or Stringable (lol)?

The goal is to being able to return either string or objects that implement a specific interface (which would enforce the implementation of __toString).