问:
Getting "multiple types were found that match the controller" error when submitting a form
I have came across this error and I solved it by using the overload of MapRoute that accepts a string array of namespaces. I had this issue mostly with hyperlinks. But now I have this issue when submitting a form. I call BeginForm() like this:

```<code>@using (Html.BeginForm("SearchMotorcycle", "Motorcycle", FormMethod.Get))
</code>```

But I have two Motorcycle controllers, I assume I have to specify a namespace. If I am correctly, how can I do that.

My motorcycle controllers are in:

appName.Controllers.Search
appName.Controllers.add

and that's what is reported to me when the error occurs.

答:
You can do this using Routing, and keeping the controllers in separate namespaces. MapRoute lets you specify which namespace corresponds to a route.

Example

Given this controllers:

```<code> namespace CustomControllerFactory.Controllers
{
public class HomeController : Controller
{
    public ActionResult Index()
    {
       return new ContentResult("Controllers");
    }
}
}

 namespace CustomControllerFactory.ServiceControllers
 {
  public class HomeController : Controller
  {
    public ActionResult Index()
    {
       return new ContentResult("ServiceControllers");
    }
   }
 }
</code>```

and add the following routing:

```<code>routes.MapRoute(
       "Services",
       "Services/{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        new string[] { "CustomControllerFactory.ServiceControllers" } // Namespace
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        new string[] { "CustomControllerFactory.Controllers"} // Namespace
    );
</code>```

You should expect the following responses

/Services/Home - ServiceControllers

and
/Home - Controller

Body:
I have came across this error and I solved it by using the overload of MapRoute that accepts a string array of namespaces. I had this issue mostly with hyperlinks. But now I have this issue when submitting a form. I call BeginForm() like this:

@using (Html.BeginForm("SearchMotorcycle", "Motorcycle", FormMethod.Get))

But I have two Motorcycle controllers, I assume I have to specify a namespace. If I am correctly, how can I do that.

My motorcycle controllers are in:

appName.Controllers.Search
appName.Controllers.add

and that's what is reported to me when the error occurs.

Body:
You can do this using Routing, and keeping the controllers in separate namespaces. MapRoute lets you specify which namespace corresponds to a route.

Example

Given this controllers:

 namespace CustomControllerFactory.Controllers
{
public class HomeController : Controller
{
    public ActionResult Index()
    {
       return new ContentResult("Controllers");
    }
}
}

 namespace CustomControllerFactory.ServiceControllers
 {
  public class HomeController : Controller
  {
    public ActionResult Index()
    {
       return new ContentResult("ServiceControllers");
    }
   }
 }

and add the following routing:

routes.MapRoute(
       "Services",
       "Services/{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        new string[] { "CustomControllerFactory.ServiceControllers" } // Namespace
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        new string[] { "CustomControllerFactory.Controllers"} // Namespace
    );

You should expect the following responses

/Services/Home - ServiceControllers

and
/Home - Controller


来源: stackexchange

问:
subprocess not running the command generated though the command works on terminal
```<code>cmd= ["sudo", "cat", "{filepath}".format(filepath=filepath), "|","egrep", "-v","\'{filteruser}\'".format(filteruser=filteruser)]
</code>```

fileformat and filteruser can be blank too

config file below

```<code>[plugin_haproxy]
user= tara
host=localhost
filepath=/etc/haproxy/haproxy.global.inc
filter=
</code>```

This is the command I want to run on subprocess, checking the above variable values with pdb shows bellow value and looks great

```<code>['sudo', 'cat', '/etc/haproxy/haproxy.global.inc', '|', 'egrep', '-v', "''"]
</code>```

Manullay running the code sudo cat /etc/haproxy/haproxy.global.inc | egrep -v " '' " on terminal works great

Why is subprocess not able to process it.

"cat: |: No such file or directory\ncat: egrep: No such file or
  directory\ncat:

答:
your shell will take a command such $ a | b | c and turn it into three separate processes (a,b,c) and attach the output of one to the input of the next in the chain.

['sudo', 'cat', '/etc/haproxy/haproxy.global.inc', '|', 'egrep', '-v', "''"]

The above will execute the sudo command (which will in-turn fork the cat command and pass all the remaining args to cat).  It doesn't understand the "|" symbol.  It just treats it as another arg.  It is cat that is complaining that it can not open "|", "egrep", etc at it is treating these as file names to cat.

You can try the Popen with shell=True.  I have not tried that and not sure if it will handle pipes.

The other option is to use Popen to execute the sudo command only (no filter) and then use Popen.communicate to read the output from the command in python and do the empty line filtering in python.

EDIT:
I did a quick check for the shell=True.  Here is the script below:

```<code>#!/usr/bin/env python
import subprocess

subprocess.call(["ls", "-l", "|", "cat"], shell=False)
</code>```

With shell=False, I get the following error: ls: cat: No such file or directory and ls: |: No such file or directory.  This is expected as ls is trying to list the contents of | and cat.

with shell=True, I get the desired output.  That is, the output of ls is piped to cat.  The shell is processing the |.

ContentLicense: CC BY-SA 3.0

Body:
cmd= ["sudo", "cat", "{filepath}".format(filepath=filepath), "|","egrep", "-v","\'{filteruser}\'".format(filteruser=filteruser)]

fileformat and filteruser can be blank too

config file below

[plugin_haproxy]
user= tara
host=localhost
filepath=/etc/haproxy/haproxy.global.inc
filter=

This is the command I want to run on subprocess, checking the above variable values with pdb shows bellow value and looks great

['sudo', 'cat', '/etc/haproxy/haproxy.global.inc', '|', 'egrep', '-v', "''"]

Manullay running the code sudo cat /etc/haproxy/haproxy.global.inc | egrep -v " '' " on terminal works great

Why is subprocess not able to process it.

"cat: |: No such file or directory\ncat: egrep: No such file or
  directory\ncat:

Body:
your shell will take a command such $ a | b | c and turn it into three separate processes (a,b,c) and attach the output of one to the input of the next in the chain.

['sudo', 'cat', '/etc/haproxy/haproxy.global.inc', '|', 'egrep', '-v', "''"]

The above will execute the sudo command (which will in-turn fork the cat command and pass all the remaining args to cat).  It doesn't understand the "|" symbol.  It just treats it as another arg.  It is cat that is complaining that it can not open "|", "egrep", etc at it is treating these as file names to cat.

You can try the Popen with shell=True.  I have not tried that and not sure if it will handle pipes.

The other option is to use Popen to execute the sudo command only (no filter) and then use Popen.communicate to read the output from the command in python and do the empty line filtering in python.

EDIT:
I did a quick check for the shell=True.  Here is the script below:

#!/usr/bin/env python
import subprocess

subprocess.call(["ls", "-l", "|", "cat"], shell=False)

With shell=False, I get the following error: ls: cat: No such file or directory and ls: |: No such file or directory.  This is expected as ls is trying to list the contents of | and cat.

with shell=True, I get the desired output.  That is, the output of ls is piped to cat.  The shell is processing the |.


问:
Ruby on Rails running on a vps slice
What are the major gotchas and tricks when running Rails on a small slice (256MB)?  What is the best server setup for cramped quarters?  Passenger, Nginx, Mongrel?  What is the best background task processor in this kind of environment?  What do you need to watch out for? I'd love to hear the stories of people who have done this and bumped into some of the virtual walls.</p>

答: Nginx proxying for a couple of mongrels.  Updating gems can cause you to run out of memory, but this can be solved by downloading and compiling rubygems from source.  You will have no problem using cron for background tasks as it is very lightweight.</p>

OwnerDisplayName: srboisvert

ContentLicense: CC BY-SA 2.5

Title: Ruby on Rails running on a vps slice

OwnerDisplayName: briancollins


问:
CoreData Relationship not updating after insert
I have a 1 to many relationship between 2 entities in my model.  I fetch entity1 that is on the '1' side and access the relationships set.  When I find that there are no items currently in the set I request information from my service, create/insert entities, set properties, set relationship back to entity1, and save the ManagedObjectContext.

I then reload a TableView, which immediately accesses the relationships set on entity1 and checks the count to see if there are any relationships to display.  No matter what I do, even if I call refreshObject, the count on the relationships set is always 0.
If I restart my app, the count is correct and I can see that the relationships to entity1 have been setup correctly.

Any idea what I am doing wrong here?  I am doing similar code with other entities in my data model and am not having this problem.  Something is strangely out of sync.

Thanks!

答:
Are you sure you're referencing the same entity1 object when you set the relationships? You can check by printing its URI representation when you fetch it in your table controller and when you do the import.

This may also be a result of using separate MOC instances to do the first fetch and the import (though that's the correct way to do it). It might help if you give some more detail about your import routine.

Update:

(Answered in the comments below). Bidirectional relationships need to be established in both directions. For example:

```<code>// set citation's owner
[citation setOwner:owner]; // or: citation.owner = owner;
// add citation to owner's citations
[owner addCitationsObject:citation];
</code>```

Body:
Are you sure you're referencing the same entity1 object when you set the relationships? You can check by printing its URI representation when you fetch it in your table controller and when you do the import.

This may also be a result of using separate MOC instances to do the first fetch and the import (though that's the correct way to do it). It might help if you give some more detail about your import routine.

Update:

(Answered in the comments below). Bidirectional relationships need to be established in both directions. For example:

// set citation's owner
[citation setOwner:owner]; // or: citation.owner = owner;
// add citation to owner's citations
[owner addCitationsObject:citation];


问:
Day and month swapping only for single digits in SSIS
I have written an SSIS integration which fetches an employee and his expiry date. All the data is flowing correctly; however when a single digit day and month is present in expiry date, the destination column swaps the month and day (when the date has double unit for months or days its fine).

Example:

```<code>      07/08/2016   to  2016-07-08     WRONG

      15/03/2016   to  2016-03-15     CORRECT
</code>```

答:
since your date are in dd/MM/yyyy and you are in trying to convert it into datetime,so problem occurs.
I think this more safe,</p>

```<code>declare @jk varchar(20)='07/08/2016'

select right(@jk,4)+'-'+substring(@jk,charindex('/',@jk)+1,2)+'-'+substring(@jk,1,2)
</code>```

Body:
I have written an SSIS integration which fetches an employee and his expiry date. All the data is flowing correctly; however when a single digit day and month is present in expiry date, the destination column swaps the month and day (when the date has double unit for months or days its fine).

Example:

      07/08/2016   to  2016-07-08     WRONG

      15/03/2016   to  2016-03-15     CORRECT

Body:
since your date are in dd/MM/yyyy and you are in trying to convert it into datetime,so problem occurs.
I think this more safe,

declare @jk varchar(20)='07/08/2016'

select right(@jk,4)+'-'+substring(@jk,charindex('/',@jk)+1,2)+'-'+substring(@jk,1,2)


问:
Java Compare Two Lists
I have two lists ( not java lists, you can say two columns)

For example

```<code>**List 1**            **Lists 2**
  milan                 hafil
  dingo                 iga
  iga                   dingo
  elpha                 binga
  hafil                 mike
  meat                  dingo
  milan
  elpha
  meat
  iga
  neeta.peeta
</code>```

I'd like a method that returns how many elements are same. For this example it should be
3 and it should return me similar values of both list and different values too.

Should I use hashmap if yes then what method to get my result?

Please help

P.S: It is not a school assignment :) So if you just guide me it will be enough

答:
Using java 8 removeIf</p>

```<code>public int getSimilarItems(){
    List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
    List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
    int initial = two.size();

    two.removeIf(one::contains);
    return initial - two.size();
}
</code>```

Title: Java Compare Two Lists

Body:
I have two lists ( not java lists, you can say two columns)

For example

**List 1**            **Lists 2**
  milan                 hafil
  dingo                 iga
  iga                   dingo
  elpha                 binga
  hafil                 mike
  meat                  dingo
  milan
  elpha
  meat
  iga
  neeta.peeta

I'd like a method that returns how many elements are same. For this example it should be
3 and it should return me similar values of both list and different values too.

Should I use hashmap if yes then what method to get my result?

Please help

P.S: It is not a school assignment :) So if you just guide me it will be enough

Body:
Using java 8 removeIf

public int getSimilarItems(){
    List<String> one = Arrays.asList("milan", "dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta");
    List<String> two = new ArrayList<>(Arrays.asList("hafil", "iga", "binga", "mike", "dingo")); //Cannot remove directly from array backed collection
    int initial = two.size();

    two.removeIf(one::contains);
    return initial - two.size();
}


问:
My app crashes when I return back to my main activity from other activities(StackOverflowError)
My MainActivity contains one mikepenz/MaterialDrawer and one pager view which contains 5 fragments. I am using material drawer to launch other activities but after launching many activities and coming back to my base Main activity the below crash occurs.
    I have no clue to find the actual root cause of this issue. Your help will be highly appreciated.

```<code>java.lang.StackOverflowError
 at android.view.GLES20Canvas.drawTextRun(GLES20Canvas.java:1345)
 at android.text.SpannableStringBuilder.drawTextRun(SpannableStringBuilder.java:1139)
 at android.view.GLES20Canvas.drawTextRun(GLES20Canvas.java:1372)
 at android.text.TextLine.drawTextRun(TextLine.java:988)
 at android.text.TextLine.handleText(TextLine.java:789)
 at android.text.TextLine.handleRun(TextLine.java:956)
 at android.text.TextLine.drawRun(TextLine.java:395)
 at android.text.TextLine.draw(TextLine.java:193)
 at android.text.Layout.drawText(Layout.java:348)
 at android.widget.Editor.drawHardwareAccelerated(Editor.java:1455)
 at android.widget.Editor.onDraw(Editor.java:1378)
 at android.widget.TextView.onDraw(TextView.java:5170)
 at android.view.View.draw(View.java:14476)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.getDisplayList(View.java:13368)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.getDisplayList(View.java:13368)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.widget.FrameLayout.draw(FrameLayout.java:472)
 at android.widget.HorizontalScrollView.draw(HorizontalScrollView.java:1609)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.widget.FrameLayout.draw(FrameLayout.java:472)
 at android.widget.HorizontalScrollView.draw(HorizontalScrollView.java:1609)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.getDisplayList(View.java:13368)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.widget.FrameLayout.draw(FrameLayout.java:472)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.support.v4.view.ViewPager.draw(ViewPager.java:2443)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
</code>```

    public class MainActivity extends MyAppFragmentActivity {

```<code>public static final String app_version="v1.134";

@Inject protected MyAppServiceProvider serviceProvider;
@Inject protected LogoutService logoutService;

private MyApplication app =MyApplication.getInstance();

private boolean userHasAuthenticated = false;

MainActivity activity;

public static final String TAG = MainActivity.class.getSimpleName();

public static final String permission = MainActivity.class+".permission";

//NEW CODE
private FrameLayout rootLayout;
private LinearLayout msgContainer;

//save our header or result
private AccountHeader headerResult = null;
private Drawer result = null;
private Login login;
private String sourceMenuJson;

//PAGER RELATED
ViewPager pager;
PagerAdapter pagerAdapter;
SlidingTabLayout tabs;
static final int noOfTabs= 5;
CharSequence pagerTitles[] = {
        //some strings
};

//TABLET LAUNCH SCREEN RELATED
private myappHorizontalOptionsMenu mmyappHorizontalOptionsMenu;
private myappHorizontalOption mSelectedmyappOption;

private TeachingPlanListFragment mTeachingPlanListFragment;
private Bus bus = app.getBus();
private Bundle savedInstanceState; //used by drawer menu

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.savedInstanceState = savedInstanceState;
    setContentView(R.layout.main_activity);
    msgContainer = (LinearLayout) findViewById(R.id.croutonContainer);
    rootLayout = (FrameLayout) findViewById(R.id.rootLayout);
    rootLayout.getForeground().setAlpha(0);
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    View mobilePagerView = findViewById(R.id.pager);
    View tabletWrapperView = findViewById(R.id.tablet_wrapper_view);

    // View injection with ButterKnife
    Views.inject(this);
    //INJECTS INTO DAGGER
    Injector.inject(this);
    activity = this;
    checkAuth();
    Log.d(TAG,"userHasAuthenticated "+userHasAuthenticated);

    if(isTablet()) {
        //setContentView(R.layout.main_activity_tablet);
        Log.d(TAG,"IS table view");
        processTabletView();
    } else {
        //setContentView(R.layout.main_activity);
        Log.d(TAG,"IS mobile view");
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
        mobilePagerView.setLayoutParams(param);
        tabletWrapperView.setVisibility(View.GONE);
    }
}

@Override
protected void onPostCreate(final Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
}

@Override
protected void onResume() {
    super.onResume();
    bus.register(this);

    if(userHasAuthenticated){
        initScreen();
    }

}

@Override
public void onBackPressed() {
    //handle the back press :D close the drawer first and if the drawer is closed close the activity
    if (result != null && result.isDrawerOpen()) {
        result.closeDrawer();
    } else {
        super.onBackPressed();
    }
}

public boolean isTablet() {
    return UIUtils.isTablet(this);
}

private void initScreen() {
    if (userHasAuthenticated) {
        login = app.getLogin();
        setNavigationDrawer();
        setUserProfile();
        initPager();
    }
}

private void setAttendenceType() {
    if (NetworkUtil.isInternetAvailable())
        new AttendanceType().execute();

}

private void checkAuth() {
    new SafeAsyncTask<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            final MyAppService svc = serviceProvider.getService(MainActivity.this);
            return svc != null;
        }

        @Override
        protected void onException(final Exception e) throws RuntimeException {
            super.onException(e);
            if (e instanceof OperationCanceledException) {
                // User cancelled the authentication process (back button, etc).
                // Since auth could not take place, lets finish this activity.
                finish();
            }
        }

        @Override
        protected void onSuccess(Boolean hasAuthenticated) throws Exception {
            Log.d(TAG,"onSuccess "+hasAuthenticated);
            if(app.getLogin() == null
                    || app.getLogin().getId() == null){
                Login login = new Login();
                SharedPreferences pref = getApplicationContext().getSharedPreferences("session", 0); // 0 - for private mode

                app.setLogin(login);
            }

            setAttendenceType();

            /**GCM RELATED CODE**/
            myappGCMUtil gcmUtil = new myappGCMUtil(getApplicationContext(), app.getLogin());

            String regid = gcmUtil.getRegistrationId();

            if (regid.isEmpty()) {
                gcmUtil.registerInBackground();
            }
            super.onSuccess(hasAuthenticated);
            userHasAuthenticated = true;
            initScreen();
        }
    }.execute();
}

private class AttendanceType extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            serviceProvider.getService(activity).getAttendanceType(activity);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AccountsException e) {
            e.printStackTrace();
        }
        return null;
    }
}

//get the list of permission
private void getPermissions(){
    String permissions = "";
    new AsyncTask<Void, Void, String>(){
        @Override
        protected String doInBackground(Void... voids) {
            PermissionWrapper postPermission = new PermissionWrapper();

            List<PermissionCode> permissionCodes = new ArrayList<PermissionCode>();

            for(int i=0; i < MainActivity.permissionCodes.length; i++){
                PermissionCode code = new PermissionCode();
                code.setCode(MainActivity.permissionCodes[i]);
                permissionCodes.add(code);
            }

            for(int i=0; i < MainActivity.canPermissionCodes.length; i++){
                PermissionCode code = new PermissionCode();
                code.setCode(MainActivity.canPermissionCodes[i]);
                permissionCodes.add(code);
            }

            postPermission.setId(app.getLogin().getName());

            postPermission.setResperm(permissionCodes);

            Log.d(TAG, new Gson().toJson(postPermission));

            try {
                HttpRequest requestPermission = post(app.getURL_PERMISSION())
                        .contentType("application/json")
                        .header(HEADER_TOKEN_KEY, HEADER_TOKEN)
                        .send(new Gson().toJson(postPermission));

                if (requestPermission.ok()) {
                    Log.d(TAG, "permission loaded");
                    return Strings.toString(requestPermission.buffer());
                } else {
                    Log.d(TAG, "permission loading failed");
                    return "";
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
            return "";
        }

        @Override
        protected void onPostExecute(String permissionList) {
            super.onPostExecute(permissionList);

            SharedPreferences pref = getApplicationContext().getSharedPreferences("session", 0); // 0 - for private mode
            SharedPreferences.Editor editor = pref.edit();
            if(permissionList!=null && permissionList.length() > 0)
                editor.putString(MainActivity.permission, permissionList);
            editor.apply();
        }
    }.execute();

}

//RETRIEVES INSTITUTES LIST FROM STRING
public List<Institute> retrieveInstitutes(String instituteString){
    List<Institute> institutes = new ArrayList<Institute>();
    if(instituteString!=null){
        Gson gson = new Gson();
        Institute[] institutesArray = gson.fromJson(instituteString,Institute[].class);
        institutes = Arrays.asList(institutesArray);
        institutes = new ArrayList<Institute>(institutes);
    }
    return  institutes;
}

/***********************************************
 * PAGER RELATED
 * **********************************************/
//INIT PAGER RELATED
private void initPager(){
    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return ContextCompat.getColor(getApplicationContext(),R.color.colorWhite);
        }
    });
    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    pagerAdapter = new PagerAdapter(getSupportFragmentManager(), pagerTitles, noOfTabs);

    pager.setAdapter(null);
    pager.setAdapter(pagerAdapter);
    pager.setCurrentItem(1, true);

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);
}

/***************************************************
 * Navigation Drawer Menu Related
 * *************************************************/

//TO LOAD READ DRAWER MENUS FROM JSON FILE
public String loadJSONMenuFromAsset() {
    if(sourceMenuJson==null){
        try {

            InputStream is = getAssets().open("drawer_menus.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            sourceMenuJson = new String(buffer, "UTF-8");

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }else
        Log.d(TAG,"sourceMenuJson already exists");
    return sourceMenuJson;
}

//INITIALIZE NAVIGATION DRAWER
private void setNavigationDrawer(){
    // Handle Toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //set the back arrow in the toolbar
    setTitle(R.string.app_name);
    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    // Create the AccountHeader
    headerResult = new AccountHeaderBuilder()
            .withActivity(this)
            .withHeaderBackground(ContextCompat.getDrawable(this,R.drawable.left_menu_header_bg))
            .withTranslucentStatusBar(false)
            .withCompactStyle(true)
            .withSavedInstance(savedInstanceState)
            .build();

    result = new DrawerBuilder()
            .withActivity(this)
            .withToolbar(toolbar)
            .withDisplayBelowStatusBar(false)
            .withTranslucentStatusBar(false)
            .withActionBarDrawerToggleAnimated(true)
            .withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                    if (drawerItem != null) {
                        onDrawerMenuSelected(drawerItem.getIdentifier());
                    }

                    return false;
                }
            })
            .addDrawerItems(
                    setMenuList()
            )
            .addStickyDrawerItems(new PrimaryDrawerItem().withName(R.string.logout_action).withIcon(myappIcon.Icon.cmu_logout).withIdentifier(-1))
            .withSavedInstance(savedInstanceState)
            .withShowDrawerOnFirstLaunch(true)
            .build();
    result.getActionBarDrawerToggle().setDrawerIndicatorEnabled(true);//SHOW HAMBURGER ICON
}

@Nullable
private IDrawerItem[] setMenuList() {
    List<IDrawerItem> iDrawerItems = new ArrayList<IDrawerItem>();
    List<DrawerMenuItem> allMenus = new Gson().fromJson(loadJSONMenuFromAsset(),DrawerMenuWrapper.class).getMenuItems();

    SharedPreferences pref = app.getSharedPreferences("session", 0);

    if(null != pref.getString(MainActivity.permission, null)) {
        Log.d(TAG, pref.getString(MainActivity.permission, null));
        PermissionResponseWrapper responseWrapper;
        try {
            responseWrapper = new Gson().fromJson(pref.getString(MainActivity.permission, null), PermissionResponseWrapper.class);
        } catch (Exception e) {
            responseWrapper = null;
        }
        if (responseWrapper != null && responseWrapper.getOutput().getData().getResperm() != null) {
            for (DrawerMenuItem menuItem : allMenus) {
                // iterate through list add the permissions available
                for (PermissionCode code : responseWrapper.getOutput().getData().getResperm()) {
                    if (code.getCode().equals(menuItem.getCode())) {
                        //SETS MENU ITEM SHOW TO TRUE;
                        menuItem.setShow(true);
                    }
                }

            }

        }

        //ITERATE ALL MENUS AND ADD TO VIEW ONLY IF "show==true"
        for (DrawerMenuItem menuItem : allMenus){
            if (menuItem.isShow()) {
                int stringID = getResources().getIdentifier(menuItem.getName(), "string", this.getPackageName());
                iDrawerItems.add(new PrimaryDrawerItem().withName(stringID).withIcon(menuItem.getIcon()).withIdentifier(menuItem.getPos()));
                iDrawerItems.add(new DividerDrawerItem());
            }
        }

        return iDrawerItems.toArray(new IDrawerItem[iDrawerItems.size()]);
    }

    return null;
}

//SETS THE USER NAME AND PHOTO
private void setUserProfile(){
    IProfile profile =  new ProfileDrawerItem().withName(login.getUname()).withEmail(login.getOrgname());

    String imageUrl = login.getImageUrl();
    if(imageUrl!=null && imageUrl.length()>0){
        //LOADS IMAGE FROM SERVER
        //initialize and create the image loader logic
        DrawerImageLoader.init(new DrawerImageLoader.IDrawerImageLoader() {
            @Override
            public void set(ImageView imageView, Uri uri, Drawable placeholder) {
                Picasso.with(imageView.getContext()).load(uri).transform(new CircleTransformPicasso()).placeholder(placeholder).into(imageView);
            }

            @Override
            public void cancel(ImageView imageView) {
                Picasso.with(imageView.getContext()).cancelRequest(imageView);
            }

            @Override
            public Drawable placeholder(Context ctx) {
                return null;
            }
            @Override
            public Drawable placeholder(Context ctx,String s) {
                return null;
            }
        });
        profile.withIcon(app.getURL_GET_AVATAR()+imageUrl);
    }else {
        //SETS DEFAULT IMAGE
        profile.withIcon(myappIcon.Icon.cmu_students);
    }
    headerResult.addProfile(profile, 0);
}

public void onDrawerMenuSelected(long position) {

    int selectedMenu = (int) position;
    switch(selectedMenu) {
        case -1:
            //Logout
            logoutService.logout(new Runnable() {
                @Override
                public void run() {
                    //Reload activity
                    Intent intent =getIntent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    finish();
                    startActivity(intent);

                }
            });
            break;

    }
}

/***************************************************
 * Tablet Land Screen Related
 ****************************************************/
//Initialize Tablet screen related work
private void processTabletView(){
    mSelectedmyappOption = new myappHorizontalOption();
    loadHorizontalMenus();
}

//LOAD HORIZONTAL OPTION MENUS FOR TABLET VIEW
private void loadHorizontalMenus(){
    final Map<String,String> tabletLaunchOptions= new LinkedHashMap<>();
    tabletLaunchOptions.put("AA", app.getResources().getString(R.string.menu_teaching_plan));
    tabletLaunchOptions.put("BB", app.getResources().getString(R.string.assignments));
    tabletLaunchOptions.put("CC", app.getResources().getString(R.string.attendance));
    mmyappHorizontalOptionsMenu = (myappHorizontalOptionsMenu) findViewById(R.id.myappHorizontalOptionsMenu);
    mmyappHorizontalOptionsMenu.distributeEvenly(true);
    mmyappHorizontalOptionsMenu.setOptions(tabletLaunchOptions);
    mmyappHorizontalOptionsMenu.disableOptionClick(true);
    // Setting Custom Color for the Scroll bar indicator of the Tab View
    mmyappHorizontalOptionsMenu.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return ContextCompat.getColor(getApplicationContext(),R.color.colorPrimary);
        }
    });
}

//Launch Attendance Fragment
public void launchAttendanceFragment(final Intent intent, String sourceFragment){

    //Post deselection inorder to swap current selection view
    ListItemDeselectEvent event = new ListItemDeselectEvent();
    if(sourceFragment.equals("ScheduleListFragment")){
        event.setTargetClassName("MyClassListFragment");
    }else {
        event.setTargetClassName("ScheduleListFragment");
    }
    bus.post(event);

    //Get selected option and set option
    mSelectedmyappOption.setTag("ATTENDANCE");
    mSelectedmyappOption.setLabel(app.getResources().getString(R.string.attendance));
    mSelectedmyappOption.setPosition(2);
    mmyappHorizontalOptionsMenu.setSelectedOption(mSelectedmyappOption, false);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            AttendanceListFragment attendanceListFragment = new AttendanceListFragment();
            attendanceListFragment.intiFragment(MainActivity.this,intent);

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_details, attendanceListFragment)
                    .commit();
        }
    },300);
}

//Set selected schedule and launches teaching plan
public void launchTeachingPlanUpdateFragment(final Schedule schedule){

    //Post deselection inorder to swap current selection view
    ListItemDeselectEvent event = new ListItemDeselectEvent();
    event.setTargetClassName("MyClassListFragment");
    bus.post(event);

    mSelectedmyappOption.setTag("CC");
    mSelectedmyappOption.setLabel(app.getResources().getString(R.string.menu_teaching_plan));
    mSelectedmyappOption.setPosition(0);
    mmyappHorizontalOptionsMenu.setSelectedOption(mSelectedmyappOption, false);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mTeachingPlanListFragment = new TeachingPlanListFragment();

            mTeachingPlanListFragment.intiFragment(schedule);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_details, mTeachingPlanListFragment)
                    .commit();
        }
    },300);
}
</code>```

}

答: Finally I have cracked it myself. The problem is I have initialized "View Pager" and "Drawer Menu" from the onResume(). As whenever I come back from other activities  "View Pager" and "Drawer Menu" are initialized again which in turn produces StackOverflow exception.  </p>

Body:
My MainActivity contains one mikepenz/MaterialDrawer and one pager view which contains 5 fragments. I am using material drawer to launch other activities but after launching many activities and coming back to my base Main activity the below crash occurs.
    I have no clue to find the actual root cause of this issue. Your help will be highly appreciated.

java.lang.StackOverflowError
 at android.view.GLES20Canvas.drawTextRun(GLES20Canvas.java:1345)
 at android.text.SpannableStringBuilder.drawTextRun(SpannableStringBuilder.java:1139)
 at android.view.GLES20Canvas.drawTextRun(GLES20Canvas.java:1372)
 at android.text.TextLine.drawTextRun(TextLine.java:988)
 at android.text.TextLine.handleText(TextLine.java:789)
 at android.text.TextLine.handleRun(TextLine.java:956)
 at android.text.TextLine.drawRun(TextLine.java:395)
 at android.text.TextLine.draw(TextLine.java:193)
 at android.text.Layout.drawText(Layout.java:348)
 at android.widget.Editor.drawHardwareAccelerated(Editor.java:1455)
 at android.widget.Editor.onDraw(Editor.java:1378)
 at android.widget.TextView.onDraw(TextView.java:5170)
 at android.view.View.draw(View.java:14476)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.getDisplayList(View.java:13368)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.getDisplayList(View.java:13368)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.widget.FrameLayout.draw(FrameLayout.java:472)
 at android.widget.HorizontalScrollView.draw(HorizontalScrollView.java:1609)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.widget.FrameLayout.draw(FrameLayout.java:472)
 at android.widget.HorizontalScrollView.draw(HorizontalScrollView.java:1609)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.getDisplayList(View.java:13368)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.widget.FrameLayout.draw(FrameLayout.java:472)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)
 at android.view.View.draw(View.java:14193)
 at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
 at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
 at android.view.View.draw(View.java:14479)
 at android.support.v4.view.ViewPager.draw(ViewPager.java:2443)
 at android.view.View.getDisplayList(View.java:13373)
 at android.view.View.getDisplayList(View.java:13415)

    public class MainActivity extends MyAppFragmentActivity {

public static final String app_version="v1.134";

@Inject protected MyAppServiceProvider serviceProvider;
@Inject protected LogoutService logoutService;

private MyApplication app =MyApplication.getInstance();

private boolean userHasAuthenticated = false;

MainActivity activity;

public static final String TAG = MainActivity.class.getSimpleName();

public static final String permission = MainActivity.class+".permission";

//NEW CODE
private FrameLayout rootLayout;
private LinearLayout msgContainer;

//save our header or result
private AccountHeader headerResult = null;
private Drawer result = null;
private Login login;
private String sourceMenuJson;

//PAGER RELATED
ViewPager pager;
PagerAdapter pagerAdapter;
SlidingTabLayout tabs;
static final int noOfTabs= 5;
CharSequence pagerTitles[] = {
        //some strings
};

//TABLET LAUNCH SCREEN RELATED
private myappHorizontalOptionsMenu mmyappHorizontalOptionsMenu;
private myappHorizontalOption mSelectedmyappOption;

private TeachingPlanListFragment mTeachingPlanListFragment;
private Bus bus = app.getBus();
private Bundle savedInstanceState; //used by drawer menu

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.savedInstanceState = savedInstanceState;
    setContentView(R.layout.main_activity);
    msgContainer = (LinearLayout) findViewById(R.id.croutonContainer);
    rootLayout = (FrameLayout) findViewById(R.id.rootLayout);
    rootLayout.getForeground().setAlpha(0);
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    View mobilePagerView = findViewById(R.id.pager);
    View tabletWrapperView = findViewById(R.id.tablet_wrapper_view);

    // View injection with ButterKnife
    Views.inject(this);
    //INJECTS INTO DAGGER
    Injector.inject(this);
    activity = this;
    checkAuth();
    Log.d(TAG,"userHasAuthenticated "+userHasAuthenticated);

    if(isTablet()) {
        //setContentView(R.layout.main_activity_tablet);
        Log.d(TAG,"IS table view");
        processTabletView();
    } else {
        //setContentView(R.layout.main_activity);
        Log.d(TAG,"IS mobile view");
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
        mobilePagerView.setLayoutParams(param);
        tabletWrapperView.setVisibility(View.GONE);
    }
}

@Override
protected void onPostCreate(final Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
}

@Override
protected void onResume() {
    super.onResume();
    bus.register(this);

    if(userHasAuthenticated){
        initScreen();
    }

}

@Override
public void onBackPressed() {
    //handle the back press :D close the drawer first and if the drawer is closed close the activity
    if (result != null && result.isDrawerOpen()) {
        result.closeDrawer();
    } else {
        super.onBackPressed();
    }
}

public boolean isTablet() {
    return UIUtils.isTablet(this);
}

private void initScreen() {
    if (userHasAuthenticated) {
        login = app.getLogin();
        setNavigationDrawer();
        setUserProfile();
        initPager();
    }
}

private void setAttendenceType() {
    if (NetworkUtil.isInternetAvailable())
        new AttendanceType().execute();

}

private void checkAuth() {
    new SafeAsyncTask<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            final MyAppService svc = serviceProvider.getService(MainActivity.this);
            return svc != null;
        }

        @Override
        protected void onException(final Exception e) throws RuntimeException {
            super.onException(e);
            if (e instanceof OperationCanceledException) {
                // User cancelled the authentication process (back button, etc).
                // Since auth could not take place, lets finish this activity.
                finish();
            }
        }

        @Override
        protected void onSuccess(Boolean hasAuthenticated) throws Exception {
            Log.d(TAG,"onSuccess "+hasAuthenticated);
            if(app.getLogin() == null
                    || app.getLogin().getId() == null){
                Login login = new Login();
                SharedPreferences pref = getApplicationContext().getSharedPreferences("session", 0); // 0 - for private mode

                app.setLogin(login);
            }

            setAttendenceType();

            /**GCM RELATED CODE**/
            myappGCMUtil gcmUtil = new myappGCMUtil(getApplicationContext(), app.getLogin());

            String regid = gcmUtil.getRegistrationId();

            if (regid.isEmpty()) {
                gcmUtil.registerInBackground();
            }
            super.onSuccess(hasAuthenticated);
            userHasAuthenticated = true;
            initScreen();
        }
    }.execute();
}

private class AttendanceType extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            serviceProvider.getService(activity).getAttendanceType(activity);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (AccountsException e) {
            e.printStackTrace();
        }
        return null;
    }
}

//get the list of permission
private void getPermissions(){
    String permissions = "";
    new AsyncTask<Void, Void, String>(){
        @Override
        protected String doInBackground(Void... voids) {
            PermissionWrapper postPermission = new PermissionWrapper();

            List<PermissionCode> permissionCodes = new ArrayList<PermissionCode>();

            for(int i=0; i < MainActivity.permissionCodes.length; i++){
                PermissionCode code = new PermissionCode();
                code.setCode(MainActivity.permissionCodes[i]);
                permissionCodes.add(code);
            }

            for(int i=0; i < MainActivity.canPermissionCodes.length; i++){
                PermissionCode code = new PermissionCode();
                code.setCode(MainActivity.canPermissionCodes[i]);
                permissionCodes.add(code);
            }

            postPermission.setId(app.getLogin().getName());

            postPermission.setResperm(permissionCodes);

            Log.d(TAG, new Gson().toJson(postPermission));

            try {
                HttpRequest requestPermission = post(app.getURL_PERMISSION())
                        .contentType("application/json")
                        .header(HEADER_TOKEN_KEY, HEADER_TOKEN)
                        .send(new Gson().toJson(postPermission));

                if (requestPermission.ok()) {
                    Log.d(TAG, "permission loaded");
                    return Strings.toString(requestPermission.buffer());
                } else {
                    Log.d(TAG, "permission loading failed");
                    return "";
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
            return "";
        }

        @Override
        protected void onPostExecute(String permissionList) {
            super.onPostExecute(permissionList);

            SharedPreferences pref = getApplicationContext().getSharedPreferences("session", 0); // 0 - for private mode
            SharedPreferences.Editor editor = pref.edit();
            if(permissionList!=null && permissionList.length() > 0)
                editor.putString(MainActivity.permission, permissionList);
            editor.apply();
        }
    }.execute();

}

//RETRIEVES INSTITUTES LIST FROM STRING
public List<Institute> retrieveInstitutes(String instituteString){
    List<Institute> institutes = new ArrayList<Institute>();
    if(instituteString!=null){
        Gson gson = new Gson();
        Institute[] institutesArray = gson.fromJson(instituteString,Institute[].class);
        institutes = Arrays.asList(institutesArray);
        institutes = new ArrayList<Institute>(institutes);
    }
    return  institutes;
}

/***********************************************
 * PAGER RELATED
 * **********************************************/
//INIT PAGER RELATED
private void initPager(){
    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return ContextCompat.getColor(getApplicationContext(),R.color.colorWhite);
        }
    });
    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    pagerAdapter = new PagerAdapter(getSupportFragmentManager(), pagerTitles, noOfTabs);

    pager.setAdapter(null);
    pager.setAdapter(pagerAdapter);
    pager.setCurrentItem(1, true);

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);
}

/***************************************************
 * Navigation Drawer Menu Related
 * *************************************************/

//TO LOAD READ DRAWER MENUS FROM JSON FILE
public String loadJSONMenuFromAsset() {
    if(sourceMenuJson==null){
        try {

            InputStream is = getAssets().open("drawer_menus.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            sourceMenuJson = new String(buffer, "UTF-8");

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }else
        Log.d(TAG,"sourceMenuJson already exists");
    return sourceMenuJson;
}

//INITIALIZE NAVIGATION DRAWER
private void setNavigationDrawer(){
    // Handle Toolbar
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //set the back arrow in the toolbar
    setTitle(R.string.app_name);
    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

    // Create the AccountHeader
    headerResult = new AccountHeaderBuilder()
            .withActivity(this)
            .withHeaderBackground(ContextCompat.getDrawable(this,R.drawable.left_menu_header_bg))
            .withTranslucentStatusBar(false)
            .withCompactStyle(true)
            .withSavedInstance(savedInstanceState)
            .build();

    result = new DrawerBuilder()
            .withActivity(this)
            .withToolbar(toolbar)
            .withDisplayBelowStatusBar(false)
            .withTranslucentStatusBar(false)
            .withActionBarDrawerToggleAnimated(true)
            .withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                    if (drawerItem != null) {
                        onDrawerMenuSelected(drawerItem.getIdentifier());
                    }

                    return false;
                }
            })
            .addDrawerItems(
                    setMenuList()
            )
            .addStickyDrawerItems(new PrimaryDrawerItem().withName(R.string.logout_action).withIcon(myappIcon.Icon.cmu_logout).withIdentifier(-1))
            .withSavedInstance(savedInstanceState)
            .withShowDrawerOnFirstLaunch(true)
            .build();
    result.getActionBarDrawerToggle().setDrawerIndicatorEnabled(true);//SHOW HAMBURGER ICON
}

@Nullable
private IDrawerItem[] setMenuList() {
    List<IDrawerItem> iDrawerItems = new ArrayList<IDrawerItem>();
    List<DrawerMenuItem> allMenus = new Gson().fromJson(loadJSONMenuFromAsset(),DrawerMenuWrapper.class).getMenuItems();

    SharedPreferences pref = app.getSharedPreferences("session", 0);

    if(null != pref.getString(MainActivity.permission, null)) {
        Log.d(TAG, pref.getString(MainActivity.permission, null));
        PermissionResponseWrapper responseWrapper;
        try {
            responseWrapper = new Gson().fromJson(pref.getString(MainActivity.permission, null), PermissionResponseWrapper.class);
        } catch (Exception e) {
            responseWrapper = null;
        }
        if (responseWrapper != null && responseWrapper.getOutput().getData().getResperm() != null) {
            for (DrawerMenuItem menuItem : allMenus) {
                // iterate through list add the permissions available
                for (PermissionCode code : responseWrapper.getOutput().getData().getResperm()) {
                    if (code.getCode().equals(menuItem.getCode())) {
                        //SETS MENU ITEM SHOW TO TRUE;
                        menuItem.setShow(true);
                    }
                }

            }

        }

        //ITERATE ALL MENUS AND ADD TO VIEW ONLY IF "show==true"
        for (DrawerMenuItem menuItem : allMenus){
            if (menuItem.isShow()) {
                int stringID = getResources().getIdentifier(menuItem.getName(), "string", this.getPackageName());
                iDrawerItems.add(new PrimaryDrawerItem().withName(stringID).withIcon(menuItem.getIcon()).withIdentifier(menuItem.getPos()));
                iDrawerItems.add(new DividerDrawerItem());
            }
        }

        return iDrawerItems.toArray(new IDrawerItem[iDrawerItems.size()]);
    }

    return null;
}

//SETS THE USER NAME AND PHOTO
private void setUserProfile(){
    IProfile profile =  new ProfileDrawerItem().withName(login.getUname()).withEmail(login.getOrgname());

    String imageUrl = login.getImageUrl();
    if(imageUrl!=null && imageUrl.length()>0){
        //LOADS IMAGE FROM SERVER
        //initialize and create the image loader logic
        DrawerImageLoader.init(new DrawerImageLoader.IDrawerImageLoader() {
            @Override
            public void set(ImageView imageView, Uri uri, Drawable placeholder) {
                Picasso.with(imageView.getContext()).load(uri).transform(new CircleTransformPicasso()).placeholder(placeholder).into(imageView);
            }

            @Override
            public void cancel(ImageView imageView) {
                Picasso.with(imageView.getContext()).cancelRequest(imageView);
            }

            @Override
            public Drawable placeholder(Context ctx) {
                return null;
            }
            @Override
            public Drawable placeholder(Context ctx,String s) {
                return null;
            }
        });
        profile.withIcon(app.getURL_GET_AVATAR()+imageUrl);
    }else {
        //SETS DEFAULT IMAGE
        profile.withIcon(myappIcon.Icon.cmu_students);
    }
    headerResult.addProfile(profile, 0);
}

public void onDrawerMenuSelected(long position) {

    int selectedMenu = (int) position;
    switch(selectedMenu) {
        case -1:
            //Logout
            logoutService.logout(new Runnable() {
                @Override
                public void run() {
                    //Reload activity
                    Intent intent =getIntent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    finish();
                    startActivity(intent);

                }
            });
            break;

    }
}

/***************************************************
 * Tablet Land Screen Related
 ****************************************************/
//Initialize Tablet screen related work
private void processTabletView(){
    mSelectedmyappOption = new myappHorizontalOption();
    loadHorizontalMenus();
}

//LOAD HORIZONTAL OPTION MENUS FOR TABLET VIEW
private void loadHorizontalMenus(){
    final Map<String,String> tabletLaunchOptions= new LinkedHashMap<>();
    tabletLaunchOptions.put("AA", app.getResources().getString(R.string.menu_teaching_plan));
    tabletLaunchOptions.put("BB", app.getResources().getString(R.string.assignments));
    tabletLaunchOptions.put("CC", app.getResources().getString(R.string.attendance));
    mmyappHorizontalOptionsMenu = (myappHorizontalOptionsMenu) findViewById(R.id.myappHorizontalOptionsMenu);
    mmyappHorizontalOptionsMenu.distributeEvenly(true);
    mmyappHorizontalOptionsMenu.setOptions(tabletLaunchOptions);
    mmyappHorizontalOptionsMenu.disableOptionClick(true);
    // Setting Custom Color for the Scroll bar indicator of the Tab View
    mmyappHorizontalOptionsMenu.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return ContextCompat.getColor(getApplicationContext(),R.color.colorPrimary);
        }
    });
}

//Launch Attendance Fragment
public void launchAttendanceFragment(final Intent intent, String sourceFragment){

    //Post deselection inorder to swap current selection view
    ListItemDeselectEvent event = new ListItemDeselectEvent();
    if(sourceFragment.equals("ScheduleListFragment")){
        event.setTargetClassName("MyClassListFragment");
    }else {
        event.setTargetClassName("ScheduleListFragment");
    }
    bus.post(event);

    //Get selected option and set option
    mSelectedmyappOption.setTag("ATTENDANCE");
    mSelectedmyappOption.setLabel(app.getResources().getString(R.string.attendance));
    mSelectedmyappOption.setPosition(2);
    mmyappHorizontalOptionsMenu.setSelectedOption(mSelectedmyappOption, false);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            AttendanceListFragment attendanceListFragment = new AttendanceListFragment();
            attendanceListFragment.intiFragment(MainActivity.this,intent);

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_details, attendanceListFragment)
                    .commit();
        }
    },300);
}

//Set selected schedule and launches teaching plan
public void launchTeachingPlanUpdateFragment(final Schedule schedule){

    //Post deselection inorder to swap current selection view
    ListItemDeselectEvent event = new ListItemDeselectEvent();
    event.setTargetClassName("MyClassListFragment");
    bus.post(event);

    mSelectedmyappOption.setTag("CC");
    mSelectedmyappOption.setLabel(app.getResources().getString(R.string.menu_teaching_plan));
    mSelectedmyappOption.setPosition(0);
    mmyappHorizontalOptionsMenu.setSelectedOption(mSelectedmyappOption, false);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mTeachingPlanListFragment = new TeachingPlanListFragment();

            mTeachingPlanListFragment.intiFragment(schedule);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_details, mTeachingPlanListFragment)
                    .commit();
        }
    },300);
}

}


问:
Disable User Account in Active Directory using C# Code
I have created c# Winform application. via which I can disable an active directory user account using C# code. I have added a textbox in which I can enter my AD username. But unable to figure how to link this textbox entry with below code?</p>

```<code>private static void DiableADUserUsingUserPrincipal(string username)
{
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                (principalContext, username);
        userPrincipal.Enabled = false;
        userPrincipal.Save();
        Console.WriteLine("Active Directory User Account Disabled successfully through UserPrincipal");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
</code>```

答:
Try the following example:

C# CODE

First add an event click to your button:

```<code>// Button click event
private void btnDisableAcc_Click(object sender, EventArgs e)
{
    // When the user clicks the button
    String _ADUserName = textBox1.Text; // <-- The textbox you enter your username?

    // Call the method below 'DiableADUserUsingUserPrincipal'
    DiableADUserUsingUserPrincipal(_ADUserName); // <-- Pass in the user name via the local variable
}
</code>```

Then define your method in the same class due to protection level is private
otherwise if it is defined in another class / assembly ref then make the protection level public

```<code>// Private Method
private static void DiableADUserUsingUserPrincipal(string username)
{
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                (principalContext, username);
        userPrincipal.Enabled = false;
        userPrincipal.Save();

        MessageBox.Show("AD Account disabled for {0}", username);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
</code>```

To enable the account:

```<code>// Private Method with return type "Boolean" to determine if the method succeed or not.
private static bool EnableADUserUsingUserPrincipal(string username)
{
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
        (principalContext, username);
        userPrincipal.Enabled = true;
        userPrincipal.Save();

        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return false;
}

private void button2_Click(object sender, EventArgs e)
{
    String _ADUserName = textBox1.Text; // <-- The textbox you enter your username?

    // Check if the account is enabled
    if (EnableADUserUsingUserPrincipal(_ADUserName))
    {
        MessageBox.Show("AD Account Enabled for {0}", _ADUserName );
        this.StatusTextBox.Text = "Account Enabled";
    }
}
</code>```

Body:
I have created c# Winform application. via which I can disable an active directory user account using C# code. I have added a textbox in which I can enter my AD username. But unable to figure how to link this textbox entry with below code?

private static void DiableADUserUsingUserPrincipal(string username)
{
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                (principalContext, username);
        userPrincipal.Enabled = false;
        userPrincipal.Save();
        Console.WriteLine("Active Directory User Account Disabled successfully through UserPrincipal");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Body:
Try the following example:

C# CODE

First add an event click to your button:

// Button click event
private void btnDisableAcc_Click(object sender, EventArgs e)
{
    // When the user clicks the button
    String _ADUserName = textBox1.Text; // <-- The textbox you enter your username?

    // Call the method below 'DiableADUserUsingUserPrincipal'
    DiableADUserUsingUserPrincipal(_ADUserName); // <-- Pass in the user name via the local variable
}

Then define your method in the same class due to protection level is private
otherwise if it is defined in another class / assembly ref then make the protection level public

// Private Method
private static void DiableADUserUsingUserPrincipal(string username)
{
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
                (principalContext, username);
        userPrincipal.Enabled = false;
        userPrincipal.Save();

        MessageBox.Show("AD Account disabled for {0}", username);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

To enable the account:

// Private Method with return type "Boolean" to determine if the method succeed or not.
private static bool EnableADUserUsingUserPrincipal(string username)
{
    try
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
        (principalContext, username);
        userPrincipal.Enabled = true;
        userPrincipal.Save();

        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return false;
}

private void button2_Click(object sender, EventArgs e)
{
    String _ADUserName = textBox1.Text; // <-- The textbox you enter your username?

    // Check if the account is enabled
    if (EnableADUserUsingUserPrincipal(_ADUserName))
    {
        MessageBox.Show("AD Account Enabled for {0}", _ADUserName );
        this.StatusTextBox.Text = "Account Enabled";
    }
}


问:
Transform camel cased String to snake case or dash case in Velocity or IntelliJ File Template
I want to transform a camel cased string like "RoomAvailability" to a "dash cased" string like "room-availability" Velocity respectively in an IntelliJ File Template which is using Apache Velocity.

I've found dozens of posts with asking from snake case to camel case which is no problem with e. g.
#set($name = ${StringUtils.removeAndHump("room_availability")}) which leads to RoomAvailability.

Another possibility would be to transform camel case to snake case and then replace '_' with '-' via
#set($replaced = ${snake_cased_name("_", "-")})
but I'm also missing a possibility to transform a string to snake case.

Are there any options to do something like that in an IntelliJ File Template respectively Velocity?

答:
I've found a soloution. Not quite elegant as an ready to use function, but however, it works.

```<code>#set( $regex = "([a-z])([A-Z]+)")
#set( $replacement = "$1-$2")
#set( $toDash = $NAME.replaceAll($regex, $replacement).toLowerCase())
...
${toDash}
</code>```

Credits go to Elena Pogorelova from JetBrains for her post at enter link description here

Body:
I've found a soloution. Not quite elegant as an ready to use function, but however, it works.

#set( $regex = "([a-z])([A-Z]+)")
#set( $replacement = "$1-$2")
#set( $toDash = $NAME.replaceAll($regex, $replacement).toLowerCase())
...
${toDash}

Credits go to Elena Pogorelova from JetBrains for her post at enter link description here

ContentLicense: CC BY-SA 4.0


问:
How to just skip an element when building new list?
```<code>data =: '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH"`

   ];._1 data
MARY
,
PATRICIA
,
LINDA
,
BARBARA
,
ELIZABETH
(one more blank line here)
</code>```

So I want just skip every second line:

```<code>   ]`(0&#);._1 data
MARY

PATRICIA

LINDA

BARBARA

ELIZABETH
(one more blank line here)
</code>```

Doesn't work as I thought.

And I encounter this situation quite often. For example when using code like this:

```<code>]`(Do nothing. Just skip. Just SKIP!!!)@.(some condition)
</code>```

答:
if you want to skip every second element of a list, you can use (_2 {.\ ])

In other words: break the list up into pairs and get the first element of each pair.

Body:
data =: '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH"`

   ];._1 data
MARY
,
PATRICIA
,
LINDA
,
BARBARA
,
ELIZABETH
(one more blank line here)

So I want just skip every second line:

   ]`(0&#);._1 data
MARY

PATRICIA

LINDA

BARBARA

ELIZABETH
(one more blank line here)

Doesn't work as I thought.

And I encounter this situation quite often. For example when using code like this:

]`(Do nothing. Just skip. Just SKIP!!!)@.(some condition)


问:
Trying to fixed the navigation bar
I've been trying to fixed the problem with my navigation bar.

What I'd like to do, is to put always the home icon on the left and setting on the right while the navigation title on the center as shown in the image.

But still look like this

when view in smallest/large screen other than my laptop 1366px wide

Is there anyone can help me with the same problem?

here the code.

```<code><nav>
  <div class="nav__container">
    <div class="nav__container--left">
      <div class="">
        <a href="http://localhost/mpci_virtual_office/" title="Return Home">
          <i class="fa fa-home fa-lg" aria-hidden="true"></i>
        </a>
      </div>
    </div>
    <div class="nav__container--center">
      <strong>Home</strong>
    </div>
    <div class="nav__container--toggle">
      <a id="push" class="visible-xs visible-sm visible-md"><i class="fa fa-bars "></i></a>
    </div>
    <div class="nav__container--right">
      <a class="dropdown-toggle" data-toggle="dropdown" title="Settings">
        <i class="fa fa-gear fa-lg"></i>
      </a>
      <ul class="dropdown-menu">
        <li><a href="http://localhost/mpci_virtual_office/office/view_profile/index/1">View Profile</a></li>
        <li><a href="http://localhost/mpci_virtual_office/office/account_preference">Settings</a></li>
        <li><a href="http://localhost/mpci_virtual_office/auth/logout">Logout</a></li>
      </ul>
    </div>
  </div>
</nav>
</code>```

And this is my CSS

```<code>/* Naviation Style */
.nav__container {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 6;
}
.nav__container--left,
.nav__container--center,
.nav__container--toggle,
.nav__container--right {
  width: 50px;
  height: 100%;
  position: absolute;

  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-items:center;
  align-content:  center;
}
.nav__container--left { }
.nav__container--left div { }
.nav__container--left div a { }
.nav__container--center {
  width: 100%;
  z-index: -1;
  text-align: center;
}
.nav__container--toggle {
  right: 50px;
}
.nav__container--right {
  right: 0;
}
</code>```

答:
Something like the below should work (expand snippet).

/* Naviation Style */
.nav__container {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 6;
}
.nav__container--left,
.nav__container--center,
.nav__container--toggle,
.nav__container--right {
  width: 50px;
  height: 100%;
  position: absolute;

  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-items:center;
  align-content:  center;
}
.nav__container--left { }
.nav__container--left div { }
.nav__container--left div a { }
.nav__container--center {
  width: 100%;
  z-index: -1;
  text-align: center;
}
.nav__container--toggle {
  right: 50px;
}
.nav__container--right {
  right: 0;
}

.nav__container {
    position: fixed;
    background: cadetblue;
    left: 0;
    right: 0;
    height: auto;
    min-height: 50px;
    color: white;
}

ul.dropdown-menu {
    display: none;
}

.nav__container--right {
    background: #508587;
}

.nav__container--left {
    background: #508587;
}

body {
    min-height: 1000px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="nav__container">
    <div class="nav__container--left">
      <div class="">

          <i class="fa fa-home fa-lg" aria-hidden="true"></i>

      </div>
    </div>
    <div class="nav__container--center">
      <strong>Home</strong>
    </div>
    <div class="nav__container--toggle">
      <i class="fa fa-bars "></i>
    </div>
    <div class="nav__container--right">

        <i class="fa fa-gear fa-lg"></i>

      <ul class="dropdown-menu">
        <li>View Profile</li>
        <li>Settings</li>
        <li>Logout</li>
      </ul>
    </div>
  </div>
</nav></code>```

Essentially:

```<code>.nav__container {
    position: fixed;
    background: cadetblue;
    left: 0;
    right: 0;
}
</code>```

Title: Trying to fixed the navigation bar

Body:
I've been trying to fixed the problem with my navigation bar.

What I'd like to do, is to put always the home icon on the left and setting on the right while the navigation title on the center as shown in the image.

But still look like this

when view in smallest/large screen other than my laptop 1366px wide

Is there anyone can help me with the same problem?

here the code.

      Home

View Profile

Settings

Logout

And this is my CSS

/* Naviation Style */
.nav__container {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 6;
}
.nav__container--left,
.nav__container--center,
.nav__container--toggle,
.nav__container--right {
  width: 50px;
  height: 100%;
  position: absolute;

  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-items:center;
  align-content:  center;
}
.nav__container--left { }
.nav__container--left div { }
.nav__container--left div a { }
.nav__container--center {
  width: 100%;
  z-index: -1;
  text-align: center;
}
.nav__container--toggle {
  right: 50px;
}
.nav__container--right {
  right: 0;
}

Body:
Something like the below should work (expand snippet).

/* Naviation Style */
.nav__container {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 6;
}
.nav__container--left,
.nav__container--center,
.nav__container--toggle,
.nav__container--right {
  width: 50px;
  height: 100%;
  position: absolute;

  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: center;
  align-items:center;
  align-content:  center;
}
.nav__container--left { }
.nav__container--left div { }
.nav__container--left div a { }
.nav__container--center {
  width: 100%;
  z-index: -1;
  text-align: center;
}
.nav__container--toggle {
  right: 50px;
}
.nav__container--right {
  right: 0;
}

.nav__container {
    position: fixed;
    background: cadetblue;
    left: 0;
    right: 0;
    height: auto;
    min-height: 50px;
    color: white;
}

ul.dropdown-menu {
    display: none;
}

.nav__container--right {
    background: #508587;
}

.nav__container--left {
    background: #508587;
}

body {
    min-height: 1000px;
}

<nav>
  <div class="nav__container">
    <div class="nav__container--left">
      <div class="">
        <a href="http://localhost/mpci_virtual_office/" title="Return Home">
          <i class="fa fa-home fa-lg" aria-hidden="true"></i>
        </a>
      </div>
    </div>
    <div class="nav__container--center">
      <strong>Home</strong>
    </div>
    <div class="nav__container--toggle">
      <a id="push" class="visible-xs visible-sm visible-md"><i class="fa fa-bars "></i></a>
    </div>
    <div class="nav__container--right">
      <a class="dropdown-toggle" data-toggle="dropdown" title="Settings">
        <i class="fa fa-gear fa-lg"></i>
      </a>
      <ul class="dropdown-menu">
        <li><a href="http://localhost/mpci_virtual_office/office/view_profile/index/1">View Profile</a></li>
        <li><a href="http://localhost/mpci_virtual_office/office/account_preference">Settings</a></li>
        <li><a href="http://localhost/mpci_virtual_office/auth/logout">Logout</a></li>
      </ul>
    </div>
  </div>
</nav>

Essentially:

.nav__container {
    position: fixed;
    background: cadetblue;
    left: 0;
    right: 0;
}


问:
Android Push notification generated by broadcast intent filter replace with old notification
i am working on one project when i am put message then i am send it as notification to another user using broadcast it working fine but when i am send again new message then replace with old notification not create new notification

below is my code for generate notification

```<code>NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

inboxStyle.addLine(message);

Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
        .setAutoCancel(true)
        .setContentTitle(title)
        .setContentIntent(resultPendingIntent)
        .setSound(alarmSound)
        .setStyle(inboxStyle)
        .setColor(color)
        .setSmallIcon(setNotificationIcon(mBuilder))
        .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
        .setContentText(message)
        .build();

NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Config.NOTIFICATION_ID, notification);
</code>```

Broadcast code

```<code>public class IncomingReceiver extends BroadcastReceiver {
    public static final String CUSTOM_INTENT = "jason.wei.custom.intent.action.TEST";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(CUSTOM_INTENT)) {

            String message = intent.getStringExtra("message");
            String chat_id = intent.getStringExtra("chat_id");
            String username = intent.getStringExtra("username");
            String chatType = intent.getStringExtra("chatType");
            MyFirebaseMessagingService mMyFirebaseMessagingService = new MyFirebaseMessagingService();
            Log.e("CHATID BROADCADST",chat_id);
            Intent mIntent1;
            if(chatType.equalsIgnoreCase("group")){
                mIntent1=new Intent(context,ActivityChatMyGroup.class);
            }else {
                mIntent1=new Intent(context,ActivityChat.class);
            }
            Bundle mBundle=new Bundle();
            mBundle.putString("name",username);
            mIntent1.putExtras(mBundle);
            mMyFirebaseMessagingService.showChatNotificationMessage(context, chat_id, username, message, mIntent1);

        }
    }
}
</code>```

答:
You should increment Config.NOTIFICATION_ID each time notifications is shown. If two notifications have same notifications id then previous notification will be replaced.

Maintains a variable (static or preference based etc) and increment it in your method

//Preference

```<code>int notificationId = PreferenceManager.getDefaultSharedPreferences(context).getInt("Notification_ID", 0);

notificationId++;
PreferenceManager.getDefaultSharedPreferences (context).edit().putInt("Notification_ID", notificationId).apply();
</code>```

And then use this variable

```<code>notificationManager.notify(notificationId, notification);
</code>```

Body:
i am working on one project when i am put message then i am send it as notification to another user using broadcast it working fine but when i am send again new message then replace with old notification not create new notification

below is my code for generate notification

NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

inboxStyle.addLine(message);

Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
        .setAutoCancel(true)
        .setContentTitle(title)
        .setContentIntent(resultPendingIntent)
        .setSound(alarmSound)
        .setStyle(inboxStyle)
        .setColor(color)
        .setSmallIcon(setNotificationIcon(mBuilder))
        .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
        .setContentText(message)
        .build();

NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Config.NOTIFICATION_ID, notification);

Broadcast code

public class IncomingReceiver extends BroadcastReceiver {
    public static final String CUSTOM_INTENT = "jason.wei.custom.intent.action.TEST";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(CUSTOM_INTENT)) {

            String message = intent.getStringExtra("message");
            String chat_id = intent.getStringExtra("chat_id");
            String username = intent.getStringExtra("username");
            String chatType = intent.getStringExtra("chatType");
            MyFirebaseMessagingService mMyFirebaseMessagingService = new MyFirebaseMessagingService();
            Log.e("CHATID BROADCADST",chat_id);
            Intent mIntent1;
            if(chatType.equalsIgnoreCase("group")){
                mIntent1=new Intent(context,ActivityChatMyGroup.class);
            }else {
                mIntent1=new Intent(context,ActivityChat.class);
            }
            Bundle mBundle=new Bundle();
            mBundle.putString("name",username);
            mIntent1.putExtras(mBundle);
            mMyFirebaseMessagingService.showChatNotificationMessage(context, chat_id, username, message, mIntent1);

        }
    }
}

Body:
You should increment Config.NOTIFICATION_ID each time notifications is shown. If two notifications have same notifications id then previous notification will be replaced.

Maintains a variable (static or preference based etc) and increment it in your method

//Preference

int notificationId = PreferenceManager.getDefaultSharedPreferences(context).getInt("Notification_ID", 0);

notificationId++;
PreferenceManager.getDefaultSharedPreferences (context).edit().putInt("Notification_ID", notificationId).apply();

And then use this variable

notificationManager.notify(notificationId, notification);


问:
How a byte array is being stored in sql server table column of type Varbinary?
I have a requirement in which I want to store a byte array in a sql server table column of type Varbinary using C# code. Now when I try to do this, I get a value in sql server table as  "0x4A6974656E6472612053616E6B686C61" for a byte array a[] = { 74, 105, 116, 101, 110, 100, 114, 97, 32, 83, 97, 110, 107, 104, 108, 97}. I am not sure how this is done. The value I get is actually a hexa representation of each decimal number.

Is it like sql server performs some internal conversion while storing a byte array into a varbinary sql table column ?

答:
You see a hex-string representation of the actual binary value stored in the field, because that is one semi-readable version to represent the bytes. How else should it be shown?

The string representation and the actual bytes are not the same. This is true for most types. If you store an integer, say 7622389, that too is actually stored as some amount of bytes (depending on the size of the field). But showing the actual bytes instead of the string representation of the value would just be confusing.

For general purpose binary data, the hex-string format is the logical string representation. Sql Server management studio could theoretically show a thumbnail of a picture if the bytes happened to make up an image file or some other well known file format. But since the field just contains general purpose binary data, it cannot really know what would be the best display format so it uses hex-string.

When you actually select the field from the database to your C# program, what you get back will generally be a byte[], sometimes wrapped up inside a container type of some sort.


问:
This generic return value is not working
I am trying to return a generic ArrayList from a generic function in which i am passing a class instance but i am getting errors in type cast with the return value

below is the code:

```<code>public <T extends DefaultHandler> List<M> getItems(Class<T> handlerClass) throws Exception{
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    DefaultHandler handler = null;
    handler=handlerClass.newInstance();
    saxParser.parse("https://www.scoopwhoop.com/rss/category/news", handler);
    return handler.getRSSItemList();  // errorLine
}
</code>```

The errorline says since handler is of type DefaultHandler , it can't call the getRSSItemList() function which is in child classes of DefaultHandler

How can call this method ?

The hierarchy is like this :

```<code>Class RSSHandler1 extends DefaultHandler
{
  public List<RssItem1> getRSSItemList(){
    return rssItemList;
  }
}

Class RSSHandler2 extends DefaultHandler
{
   public List<RssItem2> getRSSItemList(){
    return rssItemList;
   }
}
</code>```

Thanks in Advance

答:
Your generic method accepts any class that is or extends DefaultHandler. There is thus no guarantee that there is a method getRSSItemList in the class. Just because you have two classes that extend DefaultHandler and define such methods isn't sufficient for the compiler.

So you need to pass a class that does have such a method:

```<code>public interface RSSLister<I> {
    List<I> getRSSItemList();
}

class RSSHandler1 extends DefaultHandler implements RSSLister<RssItem1> {
    public List<RssItem1> getRSSItemList(){
        return rssItemList;
    }
}
</code>```

And your method should be

```<code>public <I, T extends DefaultHandler & RSSLister<I>> List<I> getItems(Class<T> handlerClass) throws Exception {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    T handler = handlerClass.newInstance();
    saxParser.parse("https://www.scoopwhoop.com/rss/category/news", handler);
    return handler.getRSSItemList();
}
</code>```

Body:
I am trying to return a generic ArrayList from a generic function in which i am passing a class instance but i am getting errors in type cast with the return value

below is the code:

public <T extends DefaultHandler> List<M> getItems(Class<T> handlerClass) throws Exception{
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    DefaultHandler handler = null;
    handler=handlerClass.newInstance();
    saxParser.parse("https://www.scoopwhoop.com/rss/category/news", handler);
    return handler.getRSSItemList();  // errorLine
}

The errorline says since handler is of type DefaultHandler , it can't call the getRSSItemList() function which is in child classes of DefaultHandler

How can call this method ?

The hierarchy is like this :

Class RSSHandler1 extends DefaultHandler
{
  public List<RssItem1> getRSSItemList(){
    return rssItemList;
  }
}

Class RSSHandler2 extends DefaultHandler
{
   public List<RssItem2> getRSSItemList(){
    return rssItemList;
   }
}

Thanks in Advance

Body:
Your generic method accepts any class that is or extends DefaultHandler. There is thus no guarantee that there is a method getRSSItemList in the class. Just because you have two classes that extend DefaultHandler and define such methods isn't sufficient for the compiler.

So you need to pass a class that does have such a method:

public interface RSSLister<I> {
    List<I> getRSSItemList();
}

class RSSHandler1 extends DefaultHandler implements RSSLister<RssItem1> {
    public List<RssItem1> getRSSItemList(){
        return rssItemList;
    }
}

And your method should be

public <I, T extends DefaultHandler & RSSLister<I>> List<I> getItems(Class<T> handlerClass) throws Exception {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    T handler = handlerClass.newInstance();
    saxParser.parse("https://www.scoopwhoop.com/rss/category/news", handler);
    return handler.getRSSItemList();
}


问:
App freezes when I'm calling GetFolderFromPathAsync
My app completely freezes before it gets the chance to run even once. Here's the context:
I'm building a UWP app that will work with a user directory, monitor the files in it, and list them in a UI control. I added the directory to futureaccess list by creating a manual folder selection prompt. I also have a service class that's supposed to get me a list of files that reside in that directory. The app freezes as soon as I get to GetFolderFromPathAsync method. There's no exception or any kind of errors, the app attempts to start and just sits in the start up process indefinitely.
Here's the class where the method is called:

public class ReplayDirectoryManager
{
    public async static Task<List<StorageFile>> GetAllReplaysFromReplayDirectory()
    {
        string replayDirectoryPath = SettingsServices.SettingsService.Instance.ReplayFolderLocation;
        StorageFolder replayFolder = await StorageFolder.GetFolderFromPathAsync(replayDirectoryPath);

        return new List<StorageFile>(await replayFolder.GetFilesAsync());
    }
}
```

<p>How do I get my code to work? Any suggestions?</p>

<p>Here's the code that I use to add the location to the futureaccess list</p>

<pre class="lang-cs prettyprint-override"><code>FolderPicker picker = new FolderPicker();
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
picker.FileTypeFilter.Add("*");
StorageFolder folder = await picker.PickSingleFolderAsync();
if (folder != null)
{
    Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(folder);
    ReplayFolderLocation = folder.Path;
}
</code>```

答:
When you use Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(folder); you can get the token.

You can use save the token to setting .

You can get the Folder by token

```<code>folder =  await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token);
</code>```

@Romasz Thx.

Body:
My app completely freezes before it gets the chance to run even once. Here's the context:
I'm building a UWP app that will work with a user directory, monitor the files in it, and list them in a UI control. I added the directory to futureaccess list by creating a manual folder selection prompt. I also have a service class that's supposed to get me a list of files that reside in that directory. The app freezes as soon as I get to GetFolderFromPathAsync method. There's no exception or any kind of errors, the app attempts to start and just sits in the start up process indefinitely.
Here's the class where the method is called:

public class ReplayDirectoryManager
{
    public async static Task<List<StorageFile>> GetAllReplaysFromReplayDirectory()
    {
        string replayDirectoryPath = SettingsServices.SettingsService.Instance.ReplayFolderLocation;
        StorageFolder replayFolder = await StorageFolder.GetFolderFromPathAsync(replayDirectoryPath);

        return new List<StorageFile>(await replayFolder.GetFilesAsync());
    }
}

How do I get my code to work? Any suggestions?

Here's the code that I use to add the location to the futureaccess list

FolderPicker picker = new FolderPicker();
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
picker.FileTypeFilter.Add("*");
StorageFolder folder = await picker.PickSingleFolderAsync();
if (folder != null)
{
    Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(folder);
    ReplayFolderLocation = folder.Path;
}

Body:
When you use Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(folder); you can get the token.

You can use save the token to setting .

You can get the Folder by token

folder =  await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token);

@Romasz Thx.


问:
iPad Application disable Autlolayout Xcode 8
I am creating a ipad application , so I dont want to use Auto Layout Constraints. I searched a lot and got that I have to disable Autolayout and enable Size classes. This Link I reffered . But I am not getting this option in my project.  Please help me how to do this.

As perthe comment I disabled autolayout. But I am still not getting it in a proper way. Here is the screenshots

答: do like , select your current View Controller , and go  to File Inspector in Xcode, and uncheck the Use AutoLayout and uncheck the Use Trait variations


问:
SQL Server - Grouping to one column
I have problem with the columns right now. The result I expect suppose to be like this:

```<code>EmployeeID    EducationalLoan
--------------
1             0.00
2             100.00
</code>```

But the result shows,

```<code>EmployeeID    EducationalLoan
--------------
1             100.00
2             100.00
</code>```

What I am trying to achieved this time is that I want to see only the employee loan deduction price on the other hand it only shows 0.00.

I know theres a little trick behind, Can someone help me with it?

```<code>    DECLARE @EmployeeID AS INTEGER

SET @EmployeeID = 0;
SELECT DISTINCT
        [EmployeeID] = emp.EmployeeID,
        [EducationalLoan] = (SELECT ISNULL(SUM((CAST((lc.LoanAmount / ((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), LoanDateStart, 101), CONVERT(VARCHAR(15), LoanPaymentDue, 101)) * 12)  * 2)) AS DECIMAL(18,2)))),0) FROM LoanContract lc WHERE lc.LoanTypeID = 1)
FROM Employee emp
    INNER JOIN Salary sal ON sal.EmployeeID = emp.EmployeeID
    INNER JOIN LoanContract lc ON lc.EmployeeID = emp.EmployeeID
    INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
    LEFT JOIN LoanPayments lp ON lp.LoanID = lc.LoanID
    LEFT JOIN LoanFrequency lf ON lf.LoanFrequencyID = lc.LoanFrequencyID
WHERE emp.EmployeeID IN (SELECT EmployeeID FROM Employee WHERE EmployeeID LIKE '%' + CASE WHEN ISNULL(@EmployeeID,0) <> 0 THEN CAST(ISNULL(@EmployeeID, 0) AS VARCHAR(15)) ELSE '' END + '%')
GROUP BY emp.EmployeeID, lt.LoanTypeID
</code>```

答:
You do not filter by employee in your subquery

```<code>    SELECT ISNULL(SUM((CAST((lc.LoanAmount / ((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), LoanDateStart, 101), CONVERT(VARCHAR(15), LoanPaymentDue, 101)) * 12)  * 2)) AS DECIMAL(18,2)))),0)
    FROM LoanContract lc
    WHERE lc.LoanTypeID = 1
</code>```

should be something like this:

```<code>    SELECT ...
    FROM LoanContract lc
    WHERE lc.LoanTypeID = 1
    AND lc.EmployeeID = emp.EmployeeID
</code>```

Title: SQL Server - Grouping to one column

Body:
I have problem with the columns right now. The result I expect suppose to be like this:

EmployeeID    EducationalLoan
--------------
1             0.00
2             100.00

But the result shows,

EmployeeID    EducationalLoan
--------------
1             100.00
2             100.00

What I am trying to achieved this time is that I want to see only the employee loan deduction price on the other hand it only shows 0.00.

I know theres a little trick behind, Can someone help me with it?

    DECLARE @EmployeeID AS INTEGER

SET @EmployeeID = 0;
SELECT DISTINCT
        [EmployeeID] = emp.EmployeeID,
        [EducationalLoan] = (SELECT ISNULL(SUM((CAST((lc.LoanAmount / ((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), LoanDateStart, 101), CONVERT(VARCHAR(15), LoanPaymentDue, 101)) * 12)  * 2)) AS DECIMAL(18,2)))),0) FROM LoanContract lc WHERE lc.LoanTypeID = 1)
FROM Employee emp
    INNER JOIN Salary sal ON sal.EmployeeID = emp.EmployeeID
    INNER JOIN LoanContract lc ON lc.EmployeeID = emp.EmployeeID
    INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
    LEFT JOIN LoanPayments lp ON lp.LoanID = lc.LoanID
    LEFT JOIN LoanFrequency lf ON lf.LoanFrequencyID = lc.LoanFrequencyID
WHERE emp.EmployeeID IN (SELECT EmployeeID FROM Employee WHERE EmployeeID LIKE '%' + CASE WHEN ISNULL(@EmployeeID,0) <> 0 THEN CAST(ISNULL(@EmployeeID, 0) AS VARCHAR(15)) ELSE '' END + '%')
GROUP BY emp.EmployeeID, lt.LoanTypeID

Body:
You do not filter by employee in your subquery

    SELECT ISNULL(SUM((CAST((lc.LoanAmount / ((dbo.fnNumberOfYears(CONVERT(VARCHAR(15), LoanDateStart, 101), CONVERT(VARCHAR(15), LoanPaymentDue, 101)) * 12)  * 2)) AS DECIMAL(18,2)))),0)
    FROM LoanContract lc
    WHERE lc.LoanTypeID = 1

should be something like this:

    SELECT ...
    FROM LoanContract lc
    WHERE lc.LoanTypeID = 1
    AND lc.EmployeeID = emp.EmployeeID