Android - How to change fragments in the Navigation Drawer

Question: I'm fairly new to Android programming, but have been doing pretty well until now. I've read a lot of answers to this question but can't seem to make mine work. Basically what I have is a MainActivity with a Navigation Drawer. I have two fragments correctly initialized with corresponding fragment layout xmls. Currently I can get my first fragment to show up when the app starts and when I click on each item in the drawer, the titles change; however, the fragment stays the same. Any suggestions? What I believe to be relevant code is below (not shown is the code for the NavigationDrawerFragment.java with the necessary code automatically built by Eclipse). Thanks in advance!
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {

/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;

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

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(
            R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));

}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.content_frame, PlaceholderFragment.newInstance(position + 1))
            .commit();

}

public void onSectionAttached(int number) {
    switch (number) {
        case 1:
            mTitle = getString(R.string.title_home);
            break;
        case 2:
            mTitle = getString(R.string.title_infodirect);
            break;
        case 3:
            mTitle = getString(R.string.title_trailmap);
            break;
        case 4:
            mTitle = getString(R.string.title_poi);
            break;
        case 5:
            mTitle = getString(R.string.title_photomap);
            break;
        case 6:
            mTitle = getString(R.string.title_report);
            break;
        case 7:
            mTitle = getString(R.string.title_rulesreg);

    }
}

public void restoreActionBar() {
    ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.overview, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

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

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

public static class InfoDirectFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static InfoDirectFragment newInstance(int sectionNumber) {
        InfoDirectFragment fragment = new InfoDirectFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public InfoDirectFragment() {
    }

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

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}
}

Comment: I saw this link a few days ago, but was hesitant to follow it through because it would require changing almost all of my code. Since you suggested it, I decided I might as well try it out. Turns out it works great and was well worth changing my code. Thank you so much!
Comment: http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
Answer: Follow This link!! for more details and  use
private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            selectItem(position);
        }
    }

and
private void selectItem(int position) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction ft = fragmentManager.beginTransaction();

    switch (position) {

    case 0:

        ft.replace(R.id.content_frame, new Fragment1, Constants.TAG_FRAGMENT).commit();

        break;

    case 1:
        ft.replace(R.id.content_frame, new Fragment2, Constants.TAG_FRAGMENT);

        ft.commit();
        break;

    }

    mDrawerList.setItemChecked(position, true);
    setTitle(title[position]);

    // Close drawer
    mDrawerLayout.closeDrawer(mDrawerList);
}

Answer: @Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments

    FragmentManager fragmentManager = getSupportFragmentManager();

    if (position == 0) {
        fragmentManager.beginTransaction()
             .replace(R.id.container, FirstFragment.newInstance())
             .commit();
    } else if (position == 1) {
       fragmentManager.beginTransaction()
         .replace(R.id.container, SecondFragment.newInstance())
         .commit();
    } else if (position == 2) {
       fragmentManager.beginTransaction()
         .replace(R.id.container, ThridFragment.newInstance())
         .commit();
    }

}

and create fragment
public class FirstFragment extends Fragment {

   public static FirstFragment newInstance() {
     FirstFragment fragment = new FirstFragment();
     return fragment;
   }

   public FirstFragment() {
   }

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

   @Override
   public void onAttach(Activity activity) {
       super.onAttach(activity);
       ((MainActivity) activity).onSectionAttached(1);
   }
}

Comment: I tried your solution but my FirstFragment doesn't load the layout !!
Answer: I was working with the Navigation Drawer based on what Eclipse generated as well (yours looks like it was made with it as well), and I've pruned it a bit so that it's not perfectly silly. I also did some black magic at some points, because I was getting silly errors that I've fixed over times (such as being unable to update the action bar title on Back press, or that if you rotate the screen then the element at index 0 is recreated by the activity):
NavigationDrawerActivity:
public class NavigationDrawerActivity extends ActionBarActivity implements
    NavigationDrawerFragment.NavigationDrawerCallbacks
{

/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;

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

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mTitle = getString(R.string.drawer_0);

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
    getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener()
    {
        public void onBackStackChanged()
        {
            int backCount = getSupportFragmentManager().getBackStackEntryCount();
            if (backCount == 0)
            {
                finish();
            }
            else
            {
                Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
                mTitle = getString(((GetActionBarTitle) fragment).getActionBarTitleId());
                restoreActionBar();
            }
        }
    });
    if (savedInstanceState != null)
    {
        this.onBackPressed();
    }
}

public void restoreActionBar()
{
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    if (!mNavigationDrawerFragment.isDrawerOpen())
    {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@Override
public void onNavigationDrawerItemSelected(int position)
{
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    boolean addToBackStack = true;
    Fragment fragment = null;
    switch (position)
    {
        case 0:
            fragment = new Fragment0();
            break;
        case 1:
            fragment = new Fragment1();
            break;
        case 2:
            fragment = new Fragment2();
            break;
        case 3:
            fragment = new Fragment3();
            break;
        case 4:
            fragment = new Fragment4();
            break;
        case 5:
            logout();
        default:
            Log.w(this.getClass().getSimpleName(),
                    "Reached Default in onNavigationDrawerItemSelected!");
            break;
    }
    if (fragment != null)
    {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.replace(R.id.container, fragment);
        if (addToBackStack == true)
        {
            ft.addToBackStack(null);
        }
        ft.commit();
        mTitle = getString(((GetActionBarTitle) fragment).getActionBarTitleId());
        restoreActionBar();
    }
}

public void logout()
{
    this.finish();
}

}

The insidious "GetActionBarTitle":
 public interface GetActionBarTitle
 {
     public int getActionBarTitleId();
 }

The generated NavigationDrawerFragment (I don't think I've changed this at all):
public class NavigationDrawerFragment extends Fragment
{

/**
 * Remember the position of the selected item.
 */
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

/**
 * Per the design guidelines, you should show the drawer on launch until the user manually expands
 * it. This shared
 * preference tracks this.
 */
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

/**
 * A pointer to the current callbacks instance (the Activity).
 */
private NavigationDrawerCallbacks mCallbacks;

/**
 * Helper component that ties the action bar to the navigation drawer.
 */
private ActionBarDrawerToggle mDrawerToggle;

private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;

private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;

public NavigationDrawerFragment()
{
}

/**
 * Callbacks interface that all activities using this fragment must implement.
 */
public static interface NavigationDrawerCallbacks
{
    /**
     * Called when an item in the navigation drawer is selected.
     */
    void onNavigationDrawerItemSelected(int position);
}

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    // Read in the flag indicating whether or not the user has demonstrated awareness of the
    // drawer. See PREF_USER_LEARNED_DRAWER for details.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (savedInstanceState != null)
    {
        mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
        mFromSavedInstanceState = true;
    }

    // Select either the default item (0) or the last selected item.
    selectItem(mCurrentSelectedPosition);
}

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    // Indicate that this fragment would like to influence the set of actions in the action bar.
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    mDrawerListView = (ListView) inflater.inflate(R.layout.fragment_navigation_drawer, container,
            false);
    mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            selectItem(position);
        }
    });
    String[] drawerTitles = new String[] { getString(R.string.drawer_0),
            getString(R.string.drawer_1),
            getString(R.string.drawer_2), getString(R.string.drawer_3),
            getString(R.string.drawer_4), getString(R.string.drawer_5) };
    mDrawerListView.setAdapter(new ArrayAdapter<String>(getActionBar().getThemedContext(),
            android.R.layout.simple_list_item_1, android.R.id.text1, drawerTitles));
    mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
    return mDrawerListView;
}

public boolean isDrawerOpen()
{
    return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}

/**
 * Users of this fragment must call this method to set up the navigation drawer interactions.
 *
 * @param fragmentId
 *            The android:id of this fragment in its activity's layout.
 * @param drawerLayout
 *            The DrawerLayout containing this fragment's UI.
 */
public void setUp(int fragmentId, DrawerLayout drawerLayout)
{
    mFragmentContainerView = getActivity().findViewById(fragmentId);
    mDrawerLayout = drawerLayout;

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the navigation drawer and the action bar app icon.
    mDrawerToggle = new ActionBarDrawerToggle(getActivity(), /* host Activity */
    mDrawerLayout, /* DrawerLayout object */
    R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
    R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
    R.string.navigation_drawer_close /* "close drawer" description for accessibility */
    )
    {
        @Override
        public void onDrawerClosed(View drawerView)
        {
            super.onDrawerClosed(drawerView);
            if (!isAdded())
            {
                return;
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }

        @Override
        public void onDrawerOpened(View drawerView)
        {
            super.onDrawerOpened(drawerView);
            if (!isAdded())
            {
                return;
            }

            if (!mUserLearnedDrawer)
            {
                // The user manually opened the drawer; store this flag to prevent auto-showing
                // the navigation drawer automatically in the future.
                mUserLearnedDrawer = true;
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
            }

            getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
        }
    };

    // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!mUserLearnedDrawer && !mFromSavedInstanceState)
    {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    mDrawerLayout.post(new Runnable()
    {
        @Override
        public void run()
        {
            mDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

private void selectItem(int position)
{
    mCurrentSelectedPosition = position;
    if (mDrawerListView != null)
    {
        mDrawerListView.setItemChecked(position, true);
    }
    if (mDrawerLayout != null)
    {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null)
    {
        mCallbacks.onNavigationDrawerItemSelected(position);
    }
}

@Override
public void onAttach(Activity activity)
{
    super.onAttach(activity);
    try
    {
        mCallbacks = (NavigationDrawerCallbacks) activity;
    }
    catch (ClassCastException e)
    {
        throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
    }
}

@Override
public void onDetach()
{
    super.onDetach();
    mCallbacks = null;
}

@Override
public void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}

@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    // Forward the new configuration the drawer toggle component.
    mDrawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
    // If the drawer is open, show the global app actions in the action bar. See also
    // showGlobalContextActionBar, which controls the top-left area of the action bar.
    if (mDrawerLayout != null && isDrawerOpen())
    {
        inflater.inflate(R.menu.global, menu);
        showGlobalContextActionBar();
    }
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    if (mDrawerToggle.onOptionsItemSelected(item))
    {
        return true;
    }

    /*
     * if (item.getItemId() == R.id.action_example)
     * {
     * Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
     * return true;
     * }
     */

    return super.onOptionsItemSelected(item);
}

/**
 * Per the navigation drawer design guidelines, updates the action bar to show the global app
 * 'context', rather than
 * just what's in the current screen.
 */
private void showGlobalContextActionBar()
{
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setTitle(R.string.app_name);
}

private ActionBar getActionBar()
{
    return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
}

An example fragment that is created by this navigation drawer:
 public class MyFragment extends Fragment implements GetActionBarTitle, OnClickListener
{
private int titleId;
private Button btn0;
private Button btn1;
private Button btn2;

public MyFragment()
{
    super();
    titleId = R.string.drawer_myfragment_title;
}

@Override
public int getActionBarTitleId()
{
    return titleId;
}

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

@Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
    super.onViewCreated(view, savedInstanceState);
    btn0 = (Button) view.findViewById(R.id.btn0);
    btn1 = (Button) view.findViewById(R.id.btn1);
    btn2 = (Button) view.findViewById(R.id.btn2);

    btn0.setOnClickListener(this);
    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);
}

@Override
public void onClick(View v)
{
    if (btn0 == v)
    {

    }
    else if (btn1 == v)
    {

    }
    else if (btn2 == v)
    {

    }
}
}

I hope that works as you intended. I had to do magic with the BackStackListener and stuff to work properly.
Comment: good work. But if I want to open a fragment once a time. If again same title from navigation drawer is selected then it should use fragment that is opened before.
Comment: @BSKANIA Yeah, although I haven't had that figured out. I'm guessing I should keep track of them and essentially reimplement the FragmentPagerAdapter or the FragmentStatePagerAdapter in terms of functionality, and I haven't had that figured out, and I never needed to finish it.
Comment: @BSKANIA it actually shouldn't be that hard however, as considering I store the data in the backstack, it can be accessed with the fragment backstack entry ID `FragmentManager#getBackStackEntryAt(int)` and `FragmentManager#getBackStackEntry()`. It is important to note that after you rotate the screen, it calls upon display(0) and that is why I call onBackPressed(), but that would need to be changed to just display the current Fragment rather than 0.. that needs black magic if orientation change is allowed. However, other than that, I didn't need to implement this, but this is the start.
Comment: currently this is what I am using to handle backstack.https://github.com/rathodchintan/Fragment-Back-Stack
Comment: @BSKANIA while you *can* do that, I'm not sure what he means by Android not managing them. That's what the `addToBackStack(null)` call is for.
Comment: I am not using this for handling backpress event but mainly not to call single fragment more that one time if called again.  So for backpressed your example is good. But I am finding solution for not to assign same fragment again.
Answer: I  know this is quite old, but I would like to share some articles Ive written about the Application Drawer and Fragment navigation. They are up to date with the latest samples (as for 2017 at least). Feel free to take a look at:
https://aarcoraci.wordpress.com/2017/02/13/android-tutorial-drawer-and-fragment-navigation-made-easyier/
https://aarcoraci.wordpress.com/2017/02/14/android-drawer-and-fragment-navigation-a-more-real-life-scenario/


If $e_0$ are the OLS residuals, what is random in $\hat{\beta}_{OLS}|f(e_0) < \hat{\beta} < f^*(e_0)$?

Question: This is a follow up question to the question I've posted here.
Suppose $Y \sim N(X\beta, \sigma^2I)$, where $y \in \mathbb{R}^n$. Let $X \in \mathbb{R}^{n \times p}$ denote a full rank design matrix. By ordinary least squares, the residuals are $$\hat{e} = (I - X(X^TX)^{-1}X^T)Y$$ Let $u_1 \in \mathbb{R}^p$ denote a unit vector in $\mathbb{R}^p$. Let $\hat{\beta}_1 = u_1^T (X^TX)^{-1}X^TY$ denote the OLS estimate for the first covariate in $X$. Suppose I'm interested in the conditional distribution of $$\hat{\beta}_1 | f(\hat{e}) < \hat{\beta}_1 < f^*(\hat{e}), \hat{e} = e_0$$
where $f(e_0)$ and $f^*(e_0)$ are some functions of $e_0.$ From the answer to my previous post, $\hat{\beta}_1$ and residuals $\hat{e}$ are independent, so I can drop $\hat{e} = e_0$ from the conditioning to obtain
$$\hat{\beta}_1 | f(e_0) < \hat{\beta}_1 < f^*(e_0)$$
Since $\hat{\beta}_1$ is normal, then truncating $\hat{\beta}_1$ between some fixed quantities $f(e_0)$ and $f^*(e_0)$ leads to a truncated normal. Therefore, $\hat{\beta}_1|f(e_0) < \hat{\beta}_1 < f^*(e_0)$ is a truncated normal with lower truncation limit $f(e_0)$ and upper truncation limit $f^*(e_0)$
My question is, once I condition on $\hat{e} = e_0,$ is there still randomness left in $\hat{\beta}_1$? Based on my previous post, I learned that $$[\hat{\beta}_1|\hat{e} = e_0] \overset{d}{=} \hat{\beta}_1$$
Is the same true in this case? i.e.,
$$[\hat{\beta}_1 | f(e_0) < \hat{\beta}_1 < f^*(e_0)]\overset{d?}{=} \hat{\beta}_1$$
The reason I feel that this is not true is because changing the value of $e_0$ would lead to a different set of truncation limits on $\hat{\beta}_1$. On the other hand, if $\hat{\beta}_1$ is independent of $\hat{e}$, then it's independent from any functions of $\hat{e}$. This might suggest that $[\hat{\beta}_1 | f(e_0) < \hat{\beta}_1 < f^*(e_0)]\overset{d}{=} \hat{\beta}_1$. I am quite confused and would greatly appreciate any insight on this.
Comment: I'm a little confused by your notation. How does your notation $y\sim N(\mu,\sigma^2 I)$ relate to the rest of the problem. Based on the rest of the problem, I would have guessed you need something like  $Y|X\sim N(X\beta,\sigma^2 I)$? Also, what is $f$? Is it assumed known but arbitrary? Does it need to be invertible? And it sounds like it maps from $\mathbb{R}^n$ to $\mathbb{R}$?
Comment: Yes, technically $y|X \sim N(X\beta, \sigma^2I)$. $f$ is arbitrary and maps from $\mathbb{R}^n$ to $\mathbb{R}$.
Comment: Thanks. another question. I see now that my first comment may have misled you, notationally speaking, because you are using $\beta$ in a different sense than I assumed. I had interpreted $\beta_1$ as the regression coefficient corresponding to the first predictor, but you are writing $\beta_1$ as the fitted value of the outcome given $X=u_1$ for some covariate pattern $u_1$. In other words, what you are calling $\hat\beta_1$, I would write as $\hat Y|X=u_1$, or $\hat Y(u_1)$. Is my understanding correct?
Comment: $\beta_1$ is the coefficient corresponding to the first covariate. $u_1$ is a unit vector with 1 in the first position and 0 everywhere else. So $\beta_1 = u_1^T\beta$, where $\beta_1$ is a scalar, and $\beta$ is the entire coefficient vector of length $p$.
Comment: Ok. I understand a unit vector to be any vector with length 1, and I was confused by your stating that $u_1 \in \mathbb{R}^p$ instead of just saying $u_1=\{1, 0, \ldots, 0\}$.
Comment: What is the meaning of $$\hat{\beta}_1 | f(\hat{e}) < \hat{\beta}_1 < f^*(\hat{e}), \hat{e} = e_0$$
Answer: Knowing that $\hat\beta_1$ is statistically independent from the residual vector $\hat e$ is not relevant to the question. Your question comes down to: is it true that
$[\hat{\beta}_1 | c_l < \hat{\beta}_1 < c_u]\overset{d}{=}\hat{\beta}_1$ for some arbitrary constants $c_l$ and $c_u$ where $c_l<c_u$? The answer is 'no: they are not equal in distribution'. As a counterexample, assuming that $\hat\beta_1$ is normally distributed, $\Pr(\hat\beta_1 < c_l)>0$ but $\Pr(\hat\beta_1 < c_l | c_l < \hat{\beta}_1 < c_u)=0$.
Addendum To your comment, On the other hand, if $\hat\beta_1$ is independent of $\hat e$ , then it's independent from any functions of $\hat e$, that only applies to functions of $\hat e$ alone. You are proposing to condition on a random variable that is a function of both $\hat e$ and $\hat \beta_1$, which is an entirely different kind of dependence. Altogether.


Valor como Object ao selecionar item no Select2

Question: O plugin Select2 funciona normalmente, o único problema é quando faço a seleção do item o valor posto no hidden (obrigatório para trazer dados via AJAX) fica como [Object Value] e não o valor especificado pela formatação.
Segue formulário:
    <form id="Teste" method="get" action="">
        <input type="hidden" id="e6" name="e6" class="select2" style="width: 600px;" />

        <input type="submit" value="Enviar" />
    </form>

Valor no input hidden após a seleção:
<input type="hidden" id="e6" name="e6" class="select2 select2-offscreen" style="width: 600px;" tabindex="-1" title="" value="[object Object]">

JavaScript para criação do Select2:
function formataResultado(item) {
    return item.Text;
}

function formataSelecao(item) {
    return item.Value;
}

$("#e6").select2({
    placeholder: "Selecionar fornecedor",
    minimumInputLength: 0,
    id: function(data){return {id: data.id};},
    allowClear: true,
    ajax: {
        url: "http://localhost:1396/Lista/_GetDropDownListFornecedor",
        dataType: 'jsonp',
        quietMillis: 300,
        data: function (term, page) {
            return {
                searchString: term,
                pageSize: 60,
                pageIndex: page,
            };
        },
        results: function (data, page) {
            return {results: data.results, more: (page * 60) < data.total };
        }
    },
    formatResult: formataResultado,
    formatSelection: formataSelecao,
    dropdownCssClass: "bigdrop",
    escapeMarkup: function (m) { return m; }
});

JSON retornado pela consulta em AJAX feita pelo Select2:
{"results":[{"Selected":false,"Text":"Cezar Barbara","Value":"724"},
 {"Selected":false,"Text":"Cezar Barbara","Value":"765"}],
 "total":82}

Answer: Seu problema está na função id:
id: function(data){return {id: data.id};},

Ela não deveria retornar um objeto, e sim o próprio valor a ser atribuído ao campo escondido (que por sinal é Value, não id):
id: function(data){return data.Value;},

Provavelmente a função anterior se referia a alguma versão mais antiga do Select2 (isso explica seu [object Object] - pois essa é a representação padrão em string de um objeto qualquer, e como sua função id estava retornando um objeto...).
Exemplo no jsFiddle (adaptado). A propósito, fazendo dessa forma você fica livre pra mostrar um valor amigável pro usuário na sua função formataSelecao, não precisa exibir o Value na tela.
Comment: Resolvido, eu já tinha retornado direto o valor com essa mesma ideia que você propôs, porém estava na versão antiga e dava problema. Após atualizar funcionou como esperado (3.5.++). Obrigado pela ajuda.
Remova a parte sobre paginação para um próximo usuário com dúvidas não cometa o erro de paginar errado. O dado: data.total é um campo personalizado do meu json.

Off: Entrei no seu blog e não encontrei tópico algum, você desativou ou nem começou?
Comment: Obrigado pela resposta, vou dar uma olhada.

Quanto a paginação está correta, o controle fica no servidor.
Comment: @Trxplz0 Nem comecei... :P
Comment: E vai? haeuaheuaheuaheu
Comment: @Trxplz0 hahaha vamos ver... (pode notar que eu não mexo nele há tanto tempo que o certificado de segurança EXPIROU!) Eu tenho uns rascunhos começados mas não acabados, qualquer hora eu publico eles. :D


Facebook graph api get user IM

Question: is there any way to get the IM username in contact information, for example jabber or msn username? I didnt find the apropirate permission in api docs. Have any idea?
Answer: To put it simply: You can't access that information via graph API.

Facebook graph api get user IM


Tesseract OCR crash when used in thread

Question: i got a strange probem with tesseract ocr. everything works fine, like the ocr part. characters are recognized correctly. but it crashes after it has done all calculations
this only happens when i run the code in a thread.
<code>void server(boost::asio::io_service & io_service, unsigned short port)
    {

        tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
        for (;;)
        {

            a.accept(sock);

            //boost::thread t(session, boost::ref(sock));
            //t.detach();
            std::thread(session, std::move(sock)).detach();
        }
    }

void session(tcp::socket & sock)
{
        tesseract::TessBaseAPI api;
        if (api.Init("", "eng"))
        {
            fprintf(stderr, "Could not initialize tesseract.\n");
            exit(1);
        }
        for (int i = 0; i < 81; i++)
        {
            if (!sudokuDatainside[i].empty())
            {
                api.SetImage((uchar*)sudokuDatainside[i].data, sudokuDatainside[i].size().width, sudokuDatainside[i].size().height, sudokuDatainside[i].channels(), sudokuDatainside[i].step1());
                // Get OCR result

                outText = api.GetUTF8Text();
                std::cout << outText << std::endl;
            }
            else
            {
                std::cout << "Nothing - " << i << std::endl;
            }
        }
        api.End();
}
</code>
Edit: seems its not a problem with api.End(). even if i dont call this method the programm crashes when the thread ends... does tesseract support threads?
Answer: After some hours of trying to find a solution. I came across an error during building the debug libs.
So rebuilding the tesseract debug libs solved the problem.
Here are the instructions i used:
https://github.com/charlesw/tesseract-vs2012

Tesseract OCR crash when used in thread


Randomise References between Columns in MySQL

Question: I want to randomise a consisting data set in MySQL. Data looks like this:
<code>|---------|--------|
|Column 1 |Column 2|
|---------|--------|
|   A     |   1    |
|---------|--------|
|   B     |   2    |
|---------|--------|
|   C     |   3    |
|---------|--------|
</code>
... and should look like this after Shuffling them:
<code>|---------|--------|
|Column 1 |Column 2|
|---------|--------|
|   C     |   2    |
|---------|--------|
|   A     |   3    |
|---------|--------|
|   B     |   1    |
|---------|--------|
</code>
Is there a simple function for doing that? Only found RAND(), but selecting them in random order with existing ("Real") reference is not enough in this case.
Thanks in advance!
Comment: In a random ordering, C will sometimes be 3. Is that OK?
Answer: <code>WITH
cte1 AS ( SELECT column1, ROW_NUMBER() OVER (ORDER BY RAND()) rn FROM src_table ),
cte2 AS ( SELECT column2, ROW_NUMBER() OVER (ORDER BY RAND()) rn FROM src_table )
SELECT cte1.column1, cte2.column2
FROM cte1
JOIN cte2 USING (rn)
</code>
fiddle
Each column values are randomly enumerated separately, then the values are combined back into pairs by these random numbers.


What conditions guarantee that a function is bounded by these two "best-fit" parabolas?

Question: Let $f:[a,b]\to\mathbb R$ be an infinitely differentiable function. Define the left (right) best-fit parabola as follows:
The left [right] best-fit parabola is the quadratic function $p(x)=Ax^2+Bx+C$ such that $p(a)=f(a),p(b)=f(b)$, and $p'(a)=f'(a)$ $\big[p'(b)=f'(b)\big]$.
A bit of algebra reveals that there is exactly one choice of coefficients $A,B,C$ (for each parabola) that makes the definition work. You can get a visual of these parabolas on this Desmos module and play around with them.
My question is, under what conditions do these two parabolas create upper and lower bounds for $f$ on $[a,b]$? Some experimentation in the above Desmos module reveals that this is often the case, but not always. For example, it is not the case for $f(x)=\tanh(x)$, shown here, even on intervals that are increasing and concave down.
These counterexamples seem to occur when the third derivative changes sign on the interval (as in the above case). So my suspicion is that the parabolas bound the function if the third derivative does not change sign on the interval. Is this conjecture valid, and if so, can someone help me prove it?
Comment: The derivative of $f$ being convex or concave is a sufficient but not a necessary condition, since tangent lines of a convex function are always below the function. Convexity or concavity of a differentiable function follows from its second derivative (so, the third derivative of $f$).
Comment: Is it your intention that (in the current version of your question) the $a,b$ in $p(x)=ax^2+bx+c$ are the same as the $a,b$ in $[a,b]$ or $p(a)=f(a)$ ?
Comment: @EwanDelanoy Nope that was a mistake—just fixed it.
Comment: @LinAlg I'm not seeing your logic. The derivative of either parabola is not in general a tangent line to the function, since the second derivative of the parabolas does not necessarily agree with that of the function at points $a$ or $b$.
Comment: @WillG you are right! Then an extra condition is that the second derivative at $a$ or $b$ should be at least (or at most) 2
Comment: @WillG I think I know how to prove it but it is a nightmare :D. You start with $y''' = z \geq 0$, integrate it 3 times, then bound it from both sides, then solve for coefficients of the bounding functions and simplify. You will likely be left with two inequalities involving integrals of $z$. If the conjecture holds, it should be possible to rearrange the resulting inequalities into a true statement
Answer: I will start with the converse. Below are the bounds for $\sin (2\pi x)$ and $\cos (2\pi x)$. As can be seen, both of them change the sign of the 3rd derivative, however, sin is bound and cos is not. So, clearly, your conjecture is not a necessary criterion. I still need to think over if it is sufficient

Here's another example I came up with
$$y(x) = (x-0.5)^5$$ and
$$y(x) = (x-0.5)^5 + 0.001 * \mathcal{N}(\frac{x-0.5}{0.001})$$
where $\mathcal{N}$ is the standard normal distribution. As can be seen, both functions are bound, but the latter changes sign in the 3rd derivative, while the former does not.

I can't seem to come up with a counter-example to the sufficiency criterion by trial and error. Perhaps it does hold. Here's an attempt to prove it. I will present as far as I get, perhaps somebody has an idea on how to continue
WLOG, assume that the interval of interest is $[0,1]$. We will use two bounding functions
$$f_1(x) = A_1 x^2 + B_1 x + C_1$$
$$f_2(x) = A_2 x^2 + B_2 x + C_2$$
The constraints are
$$
\begin{eqnarray}
  f_1(0) &=& C_1 = f(0) \\
  f_1(1) &=& A_1 + B_1 + C_1 = f(1) \\
  f_1'(0) &=& B_1 = f'(1) \\
\end{eqnarray}
$$
and
$$
\begin{eqnarray}
  f_2(0) &=& C_2 = f(0) \\
  f_2(1) &=& A_2 + B_2 + C_2 = f(1) \\
  f_2'(1) &=& 2A_2 + B_2 = f'(1) \\
\end{eqnarray}
$$
Solving the above constraints, we obtain
$$
\begin{eqnarray}
f_1(x) &=& [f(1) - f(0) - f'(0)]x^2 + f'(0) x + f(0)\\
f_2(x) &=& [f(0) - f(1) + f'(1)]x^2 + [2f(1) - 2f(0) - f'(1)]x + f(0)
\end{eqnarray}
$$
This is where I get stuck. Why assuming $f(x)$ to be a 3rd anti-derivative of either positive or negative function enable it to be bound by some simple function of its endpoints. I feel like this idea resembles mean-value theorem and Green's theorem and/or Fundamental theorem of calculus, but neither really fits directly
Comment: Very nice plots! I wasn't really expecting it to be a necessary condition, by way of analogy with the fact that a function lies above its tangent lines if (but not only if) it is concave up.
Comment: @WillG I can send you the code in python. It calculates the derivatives numerically, so you can use any function you want


How to make a container view's height dynamic based on auto layout constraints?

Question: I made a custom TableViewCell in Xcode interface builder, with a UILabel and a UITextView stacked vertically, and I set the constraints of vertical spacings between them and the container cell view.

The UITextView may need to hold a lot of text, I don't want vertical scrollbar to appear, so I calculate the height of the UITextView with [NSString sizeWithFont:constraintTosize:], and set its frame with this new height.
But it doesn't work.
Then I noticed the custom cell in .xib has a fixed row height. I am wondering if this fixed height and the vertical constraints determines the height of UITextView, and I cannot change it?
What if I want the other way around: When I set the height of UITextView, the height of the containing cell is calculated based on the constraints? Is this possible?
Comment: UITableViewDelegate has a method tableView:heightForRowAtIndexPath: - Calculate the height and return it from this method.
Comment: @NeoWant auto layout / constraints still work within a UITableViewCell (just like any other view)...but size of each cell is determined by UITableView's rowHeight or it's delegate. Why? It's just how UITableView works. It manages it's view hierarchy in this specific manner to make it very optimized/not laggy. Imagine a tableview with 100s of cells (very common). It would then how to loop through each cell, apply constraints and determine contentSize of itself...very inefficient and one of the reasons why HTML/CSS box model/webviews, though superior in your opinion, is very laggy/inefficient.
Comment: And BTW, I think in spite of Apple's efforts on UI layout with auto layout and so on, it is still much inferior compared to HTML/CSS box model.
Comment: performance > easier layout
Comment: @0xSina Surely I can manually calculate the cell height, but that way the auto layout constraints would be useless, don't you think?
Answer: The following code should be helpful. I was able to do what you're describing and account for variable amounts of text on a UILabel, inside a custom UITableViewCell called CustomCell. CustomCell uses the boilerplate UITableViewCell code with no modifications.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...
    // Using some sample text in here for testing purposes.
    NSString *sampleText = @"The UITextView may need to hold a lot of text, I don't want vertical scrollbar to appear. The UITextView may need to hold a lot of text, I don't want vertical scrollbar to appear.";

    cell.textLabel.text = sampleText;
    [cell.textLabel layoutIfNeeded];

    return cell.textLabel.frame.size.height;
}

Last but not least, set up your UILabel inside your CustomCell with AutoLayout. Follow this link to see steps on how to do that: https://stackoverflow.com/a/16009707/885189


Unknown instrument named in "Ondine et le pêcheur" by Paul Dukas

Question:
(Image source)
What is the instrument's name, I've searched it but I can't find it. It's in the score of Ondine et le pêcheur by Paul Dukas (c. 1884, unpublished).
Answer: "Cor en fa" = Horn in F.
This is confirmed in the below recording. The link is timed to 27s, where the horns can be heard clearly.

Note: The seeming "z" (that is, "Coz en fa") is a script "r" missing its leading line. A similar "r" can be found in the "Contrabass" designation.
Comment: @Aaron well, I couldn't find a reliable source for that, but I know that manuscript/cursive R is often written similarly to that (with a very small, if not missing, leading line). Try searching Google Images with the "letter r cursive lowercase" query.
Comment: the 'z' shaped character is a old style cursive 'r'
Comment: @ElementsinSpace Well that explains a lot! Fascinating. How would I look something like that up? I tried some naive Google searches, but couldn't find anything except that R started out as a Phoenician character.
Comment: image search "cursive r"
Comment: @musicamante I see it now. The missing leading line was what I needed. Now it's clearly an "r".
Comment: @Aaron I'd also add the fact, from experience, that ***most*** of french manuscript scores are a nightmare of music reading. Not only they often wrote the crotchet rest *very similar* to a quaver one (a "Z"), but I also found lots of unbelievable notation. I still remember an *acciaccatura* written ***after*** the real note.
Comment: FWIW the word is "Contrebasses," the French plural, not "Contrabass," so the handwriting is rather less idiosyncratic than it might seem.  (Also, every letter started out as a Phoenician character.)

Unknown instrument named in "Ondine et le pêcheur" by Paul Dukas


Spring batch: FieldSetMapper should set field to null instead of empty

Question: I am using spring batch to read pipe (| delimited) separated file which have have 7 field. I created a class called MyLineMapper that extends spring's FieldSetMapper. This class maps field values provided in file to my object (XYZ type). Now the problem is that fieldSet object that i get inside class extending FieldSetMapper contain empty value for field that are not present in delimited values.
For example:
Suppose that the delimited file format is as follows: |ID|Country|City|Pin|
Suppose i provide following line in file: |1|India|
As you can see the above line does not contain information for City and Pin. Therefore, I expect FieldSet object should contain Null value for these two fiels (City and Pin) instead of empty string. I don't want empty value as Null will help me to know if that field was actually present in file or not.
How can I achieve this ? Do I need to extend DelimitedLineTokenizer which I am using for tokenizing ? Or this is a simple way to do this ?
Any help will be appreciated.
Answer: From FieldSetMapper javadoc

To customize the way that FieldSet values are converted to the desired
  type for injecting into the prototype there are several choices. You
  can inject PropertyEditor instances directly through the customEditors
  property, or you can override the createBinder(Object) and
  initBinder(DataBinder) methods, or you can provide a custom FieldSet
  implementation.

Depending on type of your target bean conversion is done using default Spring convention. If you need other type of logic write your own.


Flexible content area using Bootstrap

Question: I am building a page which is flexible for any device type and resolution. I saw some bootstrap tutorials and built this page from what I learnt from there.
Here is the jsfiddle link:  https://jsfiddle.net/z450vx6x/
Here is the code:

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sample Page</title>
<link
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    rel="stylesheet" type="text/css" />

Header

Home

Product

About

            What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and
                typesetting industry. Lorem Ipsum has been the industry's standard
                dummy text ever since the 1500s, when an unknown printer took a
                galley of type and scrambled it to make a type specimen book. It has
                survived not only five centuries, but also the leap into electronic
                typesetting, remaining essentially unchanged. It was popularised in
                the 1960s with the release of Letraset sheets containing Lorem Ipsum
                passages, and more recently with desktop publishing software like
                Aldus PageMaker including versions of Lorem Ipsum.

            Why do we use it?

It is a long established fact that a reader will be distracted
                by the readable content of a page when looking at its layout. The
                point of using Lorem Ipsum is that it has a more-or-less normal
                distribution of letters, as opposed to using 'Content here, content
                here', making it look like readable English. Many desktop publishing
                packages and web page editors now use Lorem Ipsum as their default
                model text, and a search for 'lorem ipsum' will uncover many web
                sites still in their infancy. Various versions have evolved over the
                years, sometimes by accident, sometimes on purpose (injected humour
                and the like).

© ABC Group. All
            Rights Reserved

My requirements are this:
     1. I need to fix the top level navigation to make the look and feel proper.
     2. Most important issue is how to make the content area stretch to cover the browser height and still be flexible for any device screen.
Thanks
Comment: This is too broad. What problem did you encounter when you attempted "to fix the top level navigation to make the look and feel proper"? What did you try to "make the content area stretch to cover the browser height and still be flexible for any device screen"? Please narrow it down to a single question.
Comment: Ok, the content area is the main issue. Right now, it's height changes based on content. What I want is to have a min height beyond which it will not reduce. and this should not effect the design's capability to free flow based on browser area. I tried setting the area to 70%, but when I load another html using jquery load() method, the div height again goes to 0.
Answer: 1. Please specify what you mean by "make it look and feel proper" as there are countless amount of things that can achieve that. Be more specific, do you want it centred, animated differently or something else?
2. If the content is too small to cover the entire page then you can't do much other than tweak the padding and margin values to position the content in inner centre and leave enough padding around the content so as for the footer to go lower.
Of course, there are other workarounds for part 2 but since you are at the beginning, I would recommend you to familiarise yourself with margin and padding.
P.S. Since you are using Bootstrap, add additional grid classes (e.g. col-md-X) to your grid div elements.
Comment: Thanks for the response. Proper look and feel would be the menu content set with proper spacing and on hover the whole section changing color instead of only the text. I am not adding any fix css property to keep the design adaptable to browser size. The content will keep changing based on what options are selected. I want it to be of certain size to accommodate most of the pages I will load in that div. Shall I use min-height? Will having extra padding make the page flexible when more content is added?
Comment: I tried using bootstrap navbar. but that is creating spaces between my header and content components. Not sure how to control the size without making the design static.

Flexible content area using Bootstrap


How to get the auto increment id for two fields in a table

Question: Hi i want to know that how the auto increment id can be get from the mysql db for two fields in a table
Comment: I'm afraid you're going to have to word your question a little better. Providing an example of what you're trying to accomplish would help as well.
Answer: In MySQL you're only allowed 1 auto_increment column per table.
If you try and create two you'll get:

Incorrect table definition; there can be only one auto column and it must be defined as a key
Answer: Well, there are two options, but I am not sure how useful it would be (I would just use the primary key auto-increment to achieve my needs).

Using the Database: Use a trigger on the insert to increment a field value.
Using PHP: Two ways, both not so pretty:
a. grab the previous row before the insert, and increment the field in the insert.
b. If you are basing it off of the created auto-increment, you can do the insert, get the insert_id, and then update the second field.

Once again, still not sure why you would need it, but those are the options.


How to validate an object before deserializing

Question: In my code, I am calling getObject() method from an ObjectMessage object received from a JMS queue. Fortify report is complaining about this getObject() method with an error name like this Dynamic Code Evaluation: Unsafe Deserialization.
Basically it says, I should not deserialize untrusted data without validating the contents of the object stream. Below is the code.
How and what methods I should be using to get rid of this Fortify report error please.
if (message instanceof ObjectMessage) {
    ObjectMessage objMessage = (ObjectMessage) message;
    Object objReportMessage = objMessage.getObject();
....

Here is the Fortify reported issue with recommendations. Then it points this error to the code above at the line objMessage.getObject();
Dynamic Code Evaluation: Unsafe Deserialization (1 issue)
Abstract
Deserializing user-controlled object streams at runtime can allow attackers to execute arbitrary code on the
server, abuse application logic or lead to denial of service.
Explanation
Java serialization turns object graphs into byte streams containing the objects themselves and the
necessary metadata to reconstruct them from the byte stream. Developers can create custom code to aid
in the process of deserializing Java objects, where they may even replace the deserialized objects with
different objects, or proxies. The customized deserialization process takes place during objects
reconstruction before the objects are returned to the application and cast into expected types. By the time
developers try to enforce an expected type, code may have already been executed.
Custom deserialization routines are defined in the serializable classes which need to be present in the
runtime classpath and cannot be injected by the attacker so the exploitability of these attacks depends on
the classes available in the application environment. Unfortunately, common third party classes or even
JDK classes can be abused to exhaust JVM resources, deploy malicious files, or run arbitrary code.
Certain protocols use Java serialization behind the scenes in the transport layer. RMI and JMX are
examples of these protocols.
Example 1: Here is an example of an RMI interface that can be exposed publicly, containing methods with
one or more parameters. When invoking these methods remotely, the arguments will be deserialized on the
server allowing attackers to inject malicious object graphs.
public interface MyService extends java.rmi.Remote {
public Object doSomething (Object arg0) throws RemoteException;
public Object doSomethingElse (Object arg0, Object arg1) throws
RemoteException;
...
}

Example 2: JMX MBeans also use Java serialization to transmit call arguments. In the example below, the
MyManagedBean class methods will be exposed to clients.
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("com.example:type=MyManagedBean");
MyManagedBean mbean = new MyManagedBean();
mbs.registerMBean(mbean, name);

Recommendation
If possible, do not deserialize untrusted data without validating the contents of the object stream. In order to
validate classes being deserialized, the look-ahead deserialization pattern should be used.
The object stream will first contain the class description metadata and then the serialized bytes of their
member fields. The Java serialization process allows developers to read the class description and decide
whether to proceed with the deserialization of the object or abort it. In order to do so, it is necessary to
subclass java.io.ObjectInputStream and provide a custom implementation of the
resolveClass(ObjectStreamClass desc) method where class validation and verification should
Sep 29, 2016, 5:09 PM
Copyright 2015 Hewlett Packard
Enterprise Development LP 13
take place.
There are existing implementations of the look-ahead pattern that can be easily used, such as the Apache
Commons IO (org.apache.commons.io.serialization.ValidatingObjectInputStream).
Always use a strict whitelist approach to only deserialize expected types. A blacklist approach is not
recommended since attackers can use many available gadgets to bypass the blacklist. Also, keep in mind
that although some classes to achieve code execution are publicly known, there may be others that are
unknown or undisclosed, so a whitelist approach will always be preferred. Any class allowed in the whitelist
should be audited to make sure it is safe to deserialize.
To avoid denial of service attacks, it is recommended that you override the resolveObject(Object
obj) method in order to count how many objects are being deserialized and abort the deserialization when
a threshold is surpassed.
When deserialization takes place in library, or framework (e.g. when using JMX, RMI, JMS, HTTP Invokers)
the above recommendation is not useful since it is beyond the developer's control. In those cases, you may
want to make sure that these protocols meet the following requirements:
- Not exposed publicly.
- Use authentication.
- Use integrity checks.
- Use encryption.
In addition, HPE Security Fortify Runtime provides security controls to be enforced every time the
application performs a deserialization from an ObjectInputStream, protecting both application code but
also library and framework code from this type of attack.
Comment: You can't, and the message can't seriously mean that.
Comment: Yeah, I could not find anything helpful online, maybe I understand it wrong or the Fortify report did not recognize the problem correctly. I just edited the post and attached the issue from Fortify report, can you please help me to take a look? Thanks.
Answer: If you look at the tips portion from the recommendations it states that the issue will be reported even if a look-ahead ObjectInputStream is implemented.  Therefore even if you were able to fix the issue, you will not get rid of the finding.
However, it looks like your code is using JMS and with JMS, you do not control the deserialization.  This is recognized by the recommendations you copied and pasted:

When deserialization takes place in library, or framework (e.g. when using JMX, RMI, JMS, HTTP Invokers) the above recommendation is not useful since it is beyond the developer's control. In those cases, you may want to make sure that these protocols meet the following requirements:

Not exposed publicly.
Use authentication.
Use integrity checks.
Use encryption.

Therefore, your true fix is to ensure those four bullet points are followed.  You will have to do research into your connection and, depending on your requirements and limitations, that may not be possible.
Answer: Take a look at the ValidatingObjectInputStream.  Basically you whitelist the classes that you will allow to be deserialized (you should know these based on the info you are pulling in).  The validator will then check the metadata to the serialized data and reject any classes that are not within the whitelist.
Comment: This answer is useless in the context of the original question because the only constructor of `ValidatingObjectInputStream` takes `InputStream` as an argument. You cannot get `InputStream` from `javax.jms.Message` or from `javax.jms.ObjectMessage`.
Comment: hey @aaron Is there any way by which we can do this without use of external libraries.
Answer: In case anyone visits this old post, I got around this issue by switching from ObjectMessage to TextMessage and just sending JSON instead of serialized objects.
This post was very informative
//Sender
      ObjectMapper mapper = new ObjectMapper();
      TextMessage message = session.createTextMessage(mapper.writeValueAsString(foo));
      messageBus.send(message);

//Receiver
    ObjectMapper mapper = new ObjectMapper();
    try {
        Foobar foo= mapper.readValue(textMessage.getText(), new TypeReference<Foobar>(){});
        dataHandlerProcess(foo);
    } catch (IOException e) {
        logger.error("Could not parse Foobar JSON ",e );
        return;
    }


How to use BlockBlob when uploading large file in Windows Azure web site

Question: All, I was trying to uploading a larger file (700MB) in a web page which include a File html element in a Form . and I want to in the server side can get the stream and upload it into Azure storage.
Here is some code snippet on the server side.
public void UploadFile()
{
    Stream source = Request.InputStream;

    long copiedByteCount = 0;

    byte[] buffer = new byte[2 * 1024];

    for (int len; (len = from.Read(buffer, 0, buffer.Length)) > 0; )
    {
        //Begin to write buffer to Azure.
        ....(I am still searching the BlockBlob code sample in google.)
        //
        copiedByteCount += len;
    }

}

My question is

1.I hope the app does not eat all the memory ,so read the stream by block. I don't know if it work as my wish.
2.Can someone help to give some example How to write all the buffer blocks into BlockBlob in parallel.

Thanks.
Answer: First you have to know that, to allow 700MB uploads, you'll need to allow this in the web.config:
<system.web>
  <httpRuntime executionTimeout="240" maxRequestLength="716800" />
</system.web>

<system.webServer>
    <security>
        <requestFiltering>
            <requestLimits maxAllowedContentLength="716800" />
        </requestFiltering>
    </security>
</system.webServer>

Whenever someone uploads a file larger than 256KB (this is the default), the file is buffered to disk (documented here). So you don't have to worry about the incoming file.
To upload this file to a blob without loading it in memory, you can simply use the stream of the HttpPostedFile and forward it to the storage client:
 var blob = container.GetBlockBlobReference(blobName);
 blob.UploadFromStream(Request.Files[0].InputStream);

Finally, if you want to upload the blob in parallel you can start with the code on this page: Blob Parallel Upload and Download (you will need to change the UploadFileToBlobAsync method to accept a stream instead of a filename).
Comment: Thanks you for this helpful [info](http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.aspx), But if my web site is deployed on the windows azure.  Maybe the Windows Azure website doesn't support large file uploaded. Because you said the file larger than 256KB will be buffered do disk. We known the Azure Website can not see the disk located in.We don't how what size is it,Maybe it is small than 700MB, So I think there is a problem with it .How do u think of this ? Thanks
Comment: If you use Windows Azure Web Sites you'll need to make the change in the web.config to see if this works (you can override some parts of the web.config but these changes should be allowed). Anyways, you don't need to access the file directly, it's simply buffered to disk for performance reasons. In the end you won't need to access the file directly, you can simply use the InputStream as explained in my answer. Keep in mind that free and shared websites are limited to 1GB of storage: https://www.windowsazure.com/en-us/pricing/details/#web-sites


How do I wait for an executable to open before continuing the code in PowerShell?

Question: Editor's note:
This question is about an event-based way to run PowerShell code whenever a new process (possibly with a given executable name) is created system-wide.
I have done a ton of research and I can't seem to find any solutions to this.
I have tried using Wait-Event -SourceIdentifier "ProcessStarted", but it doesn't seem to work at all. It just waits infinitely and does not make the code resume. If there is a way to wait for an executable to start or wait for a specific one to start, help a brother out!
Comment: Can you name a specific executable?  Please help us reproduce the problem, see: [how to ask](https://stackoverflow.com/help/how-to-ask)
Comment: Can you share the event handler registration code you've used?
Comment: @iRon There is no need in any specific executable file. All I'm asking for is a method to wait for an executable file or program to open before continuing the script
Comment: @MathiasR.Jessen I don't understand why you need that, my question is simple and should take one line to reproduce. I already showed you the line of code I tried to wait for an executable file to open, and it didn't work. Literally all I'm asking for is a way to do it.
Answer: From what I gather you have a script and want to pause it until a certain process starts and once it starts continue with the rest of the script.
A quick and dirty solution would be to use get-process and query the process name, in this example I use vlc. Ouput will  be $null until process is launched and once it's launched loop will exit. This would only work if the process is not already running. For example, if you are running Chrome already and you are trying to look for a new instance of the process this code won't work.
# some code
$processName = "vlc"
# wait until process starts
while ((Get-Process -name $processName -ErrorAction SilentlyContinue) -eq $null)
{
    write-host "waiting for process to start to continue"
    Start-Sleep -Seconds 2
}

# continue code
write-host "Process started"

--
Example output
.\wait_for_process.ps1
waiting for process to start to continue
waiting for process to start to continue
waiting for process to start to continue
waiting for process to start to continue
Process started

Answer: The OS is not magically going to announce process start events to you - you need to specify what exact events you want to know about and then register for the target event:
# define an event polling query - this will poll WMI for new process creations every 2 seconds
$processCreationEventQuery = "SELECT TargetInstance FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_Process'"

# add event registration to make PowerShell consume the event from WMI
Register-CimIndicationEvent -Query $processCreationEventQuery -SourceIdentifier ProcessStarted

Now that we have an event registration set up, Wait-Event will work:
Wait-Event -SourceIdentifier ProcessStarted

If you want to wait for a more specific process to launch, modify the query filter, eg:
$processCreationEventQuery = @"
SELECT TargetInstance
  FROM __InstanceCreationEvent
WITHIN 2
 WHERE TargetInstance ISA 'Win32_Process'
   AND TargetInstance.Name LIKE '%RelevantProcessNameGoesHere%'
"@

Comment: Nice; to add some context: Unlike the dedicated [`Win32_ProcessStartTrace`](https://learn.microsoft.com/en-us/previous-versions/windows/desktop/krnlprov/win32-processstarttrace) event, this `__InstanceCreationEvent`-based approach is based on _periodic polling_, which means that short-lived processes that are both created and terminate _between_ polling intervals (`1` second is the minimum) are missed (which may or may not matter in practice). However, the `__InstanceCreationEvent` approach has the advantage that it does not require elevation (running with admin privileges).
Answer:
To complement Mathias R. Jessen's helpful answer:
The __InstanceCreationEvent-based approach shown there is based on periodic polling, which means that short-lived processes may be missed, namely those that are both created and terminate between polling intervals (1 second is the minimum) - this may or may not matter in practice.

This answer shows a manual polling loop (no CIM/WMI events involved) with sub-second resolution, as well as __InstanceCreationEvent sample code that processes events indefinitely.

However, the __InstanceCreationEvent approach has the advantage that it does not require elevation (running with admin privileges), unlike the dedicated Win32_ProcessStartTrace event, which does.
If running with elevation is an option, the advantage of Win32_ProcessStartTrace is that it does not miss events; also, it is easier to set up.

Here's a self-contained Win32_ProcessStartTrace sample based on Register-CimIndicationEvent and Wait-Event that processes events indefinitely (press Ctrl-C to stop) - as noted, elevation is required:
#requires -RunAsAdmin

Write-Verbose -Verbose "Monitoring for new processes; press Ctrl-C to exit..."
try {

  # Note: This registers for *any* new process.
  #       To limit the scope, pass a -Query argument instead of -ClassName; e.g.:
  #       -Query 'Select * From Win32_ProcessStartTrace Where ProcessName = "cmd.exe"'
  Register-CimIndicationEvent -ClassName Win32_ProcessStartTrace -SourceIdentifier ProcessStarted

  # Wait for and process events indefinitly.
  while ($true) {
    ($evt = Wait-Event -SourceIdentifier ProcessStarted) | Remove-Event
    # $evt.SourceEventArgs.NewEvent contains the event details.
    # For demo purposes, print them here.
    $evt.SourceEventArgs.NewEvent | Out-Host
  }
}
finally {
  UnRegister-Event -SourceIdentifier ProcessStarted
}

Here's a variant that uses the -Action parameter to perform event processing in the background, which enables foreground activity in parallel - but note that event processing only happens between PowerShell statements; it is blocked during long-running commands, including .NET method calls:
#requires -RunAsAdmin

Write-Verbose -Verbose "Monitoring for new processes; press Ctrl-C to exit..."
try {

  # Pass the event-handler code to the -Action parameter.
  # Register-CimIndicationEvent then creates and returns an event job that must later be removed.
  # If your -Action block were to produce *data* to communicate to the main thread, you'd have to
  # to use Receive-Job in the main thread.
  $eventJob =
    Register-CimIndicationEvent `
         -ClassName Win32_ProcessStartTrace `
         -Action {
           # For demo purposes, simply print the event details to the console (host).
           $EventArgs.NewEvent | Out-Host
          }

  # You can now perform other operations here in the foreground,
  # but note that event processing happens only *between* PowerShell
  # statements.
  while ($true) {
    Write-Host . -NoNewline       # simulate foreground activity
    Start-Sleep -Milliseconds 100 # sleep a little
  }

}
finally {
  # Remove the event job, which also unsubscribes from the CIM event.
  Remove-Job -Force $eventJob
}


Can i Find the Matrix from Eigenvalues and Eigenvectors?

Question: If i given eigenvector:
$$V_1=\begin{pmatrix} {1\over \sqrt{3}}\\{1\over \sqrt{3}}\\{1\over \sqrt{3}}\end{pmatrix} , V_2=\begin{pmatrix} {1\over \sqrt{6}}\\{-2\over \sqrt{6}}\\{1\over \sqrt{6}}\end{pmatrix}  Space:\lambda=1 \\ V_3=\begin{pmatrix} {1\over \sqrt{2}}\\0\\{1\over \sqrt{2}}\end{pmatrix}Space: \lambda = 3$$
 I know finding eigenvectors from matrix but how can i find Matix from those given vectors and $\lambda$s ?Are those vectors orthonormal? (what are the properties of orthonormality ?)
Comment: You can't recover the matrix from the eigenpairs alone.
Comment: Since it is an exam question, I suspect the third vector was $(\pm 1,0,\mp 1)/\sqrt{2}$.  That would give 3 orthonormal vectors of $A$.  The inverse matrix,  $A^{-1}$, would then be given by $1/\lambda_1 V_1 V_1^T + 1/\lambda_2 V_2 V_2^T + 1/\lambda_3 V_3 V_3^T$.  Note that I am using $V V^T$ to denote the outer product of two vectors.
Comment: @Andy Here is a link to [matrix inverse eigendecomposition](http://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix).  You'll have to scroll down a few sections. The formula $A = Q \Lambda Q^T$ is known as the spectral theorem or the principal axis theorem.  $Q$ is a matrix whose columns are the eigenvectors of $A$.  The expansion that I used is a technique used for constructing a matrix from projections or from projection operators.  Gilbert Strang uses it in Linear Algebra and Its Applications, 4th edition, Section 5.5.
Comment: But i asked to find inverse of the matrix from it at the exam
Comment: I suggest you post the exact problem, maybe there's a misunderstanding somewhere.
Comment: Is the matrix symmetric? If so you can just use the eigenvalue decomposition $X = ZDZ^T$ where the columns of $Z$ are the eigenvectors and $D$ is a diagonal matrix with corresponding eigenvalues along the diagonal.
Comment: You cannot recover *the* original matrix since multiple matrices have the same eigenvalue/vector pairs.  However, one can easily find *a* matrix that has those eigenvalue/vector pairs.  (Consider a symmetric matrix).
Comment: it was exam question, and this is what i remember (i think there was notting more) and the question was Find $A^{-1}$ without finding Matrix A (hint: First expressing the eigendecomposition of vector products)
Comment: was something like this
Comment: @anortan I think it is unique if the matrix is diagonalizable. (The nonuniqueness comes from multiple possible Jordan forms.) But maybe I am confused? Is there a counterexample?
Comment: @noob I believe you are correct, but I'm a little out of my realm of certainty. :-)
Comment: @Louis $A^{-1}={1\over \lambda_1}V_1(V_1)^T+...$ is theorom or what? where did u come up with it ?
Answer: you can see that the vectors $\{v_1, v_2, v_3 \}$ is orthonormal meaning each has unit length($v_1.v_1 = v_1^T v_1 = 1$) and any pair($v_1.v_2 = v_1^Tv_2 = 0$) is orthogonal. so they for a basis for $R^3$ if you compose $A = v_1v_1^T + v_2v_2^T + 3v_3v_3^T$ as the linear combination three rank one matrices, then you can verify that $Av_1 = v_1, Av_2 = v_2$ and $Av_3 = 3v_3$ for  what this tells us is that the matrix has eigenvalues $1,1,3$ and the corresponding eigenvectors $v_1, v_2, v_3$
in fact, if $B = kv_1v_1^T + lv_2v_2^T + mv_3v_3^T,$ then the matrix $B$ has eigenvalues $k,l,m$ we can use this fact and that $A^{-1}$ has eigenvalues $1, 1, 1/3$(reciprocals of the eigenvalues of $A$) you have   $$ A^{-1} = v_1v_1^T + v_2v_2^T + {1 \over3}v_3v_3^T$$


Dúvida com uso do Optional

Question: Estou tentando usar essa classe optional para pegar os dados com null, mas retorna erro.
Na classe principal, uso o for com esse método.
Profissao e composicao de pessoas.
for(Pessoa p : pessoas) {

        Optional<Profissao> temNome = p.profissao.getNomeP();

Se usar como String
Optional<String> temNome =Optional.ofNullable(p.profissao.getNomeP());

funciona, mas nao entendi a diferença
Comment: Se você fizer assim `p.profissao.ifPresent(prof -> System.out.println(prof.getNomeP()));` mostra o nome?
Comment: Não aparece a opcao do ifPresent, voce quis dizer assim ? temNome.ifPresent() { }
Comment: Na realidade entendi sua dúvida agora. A sua segunda opção funciona porque você está chamando por último o `getNomeP` que retorna uma `String` e não uma Profissao
Answer: Olá!
Ao que me parece, vc está confundindo.
Veja, vc está acessando o nome da profissão, uma string, e está esperando que o mesmo retorne o objeto pai, profissão.
for(Pessoa p : pessoas) {
   Optional<Profissao> temNome = p.profissao.getNomeP();
   ...
}

O certo aqui seria:
for(Pessoa p : pessoas) {
   Optional<Profissao> possivelProfissao = Optional.ofNullable(p.profissao);
   possivelProfissao.ifPresent( profissao -> System.out.println(p.getNomeP()) );
   ...
}

Ou:
for(Pessoa p : pessoas) {
   Optional<Profissao> possivelProfissao = Optional.ofNullable(p.profissao);
   if(possivelProfissao.isPresent()){
      String nome = possivelProfissao.get().getNomeP();
      System.out.println(nome );
   }
   ...
}

Recomendo uma lida neste artigo da Caelum. Dá uma base legal.
A documentação, embora bem completa, não será lá mto didática
Quaisquer dúvidas, é só perguntar.
Edição 01
Caso vc queira retornar uma String padrão qdo não há profissão, vc poderá fazer algo assim:
public String temNome(Profissao profissao) {
  return Optional.ofNullable(profissao.getNomeP()).orElse("Nao tem Profissao");
}

O mais legal é que vc faça na sua classe pessoa, escrevendo um getNomeProfissao(), assim:
public class Pessoa{
   ...
   public String getNomeProfissao(){
      return Optional.ofNullable(this.profissao.getNomeP()).orElse("Nao tem Profissao");
   }
   ...
}

Assim você seguirá a Lei de Demeter, e não irá encadear chamadas.
Answer: Criei um método, creio que esteja correto
public  String temNome(Profissao profissao) {

        Optional<String> nomeProfissao = Optional.ofNullable(profissao.getNomeP());

        if(nomeProfissao.isPresent()) {

            return profissao.getNomeP();
        }

        return "Nao tem Profissao";

    }

Comment: Ser o que vc quer é saber se há profissão, o mais educado é usar o "nomeProfissao.isPresent()" e deixar a tomada de decisão pra camada de cima, deixando mais coeso.
O que vc pode fazer é encapsular na sua classe pessoa o método temProfissao(), e neste vc retorna um boolean.
no caso do metodo que vc postou, faça assim:

public  String temNome(Profissao profissao) {
    return Optional.ofNullable(profissao.getNomeP()).orElse("Nao tem Profissao");
    }

Dúvida com uso do Optional


CSS - How to completely center one box in another one?

Question: I am learning css as beginner and doing some basic tests. My question is: given the css below how can I position the box2 in exactly the middle of the box1?
.box1 {
  background: black;
  height: 400px;
  width: 400px;
  margin: auto;
}

.box2 {
  height:300px;
  width:300px;
  background: red;
  margin: auto;
}

At the beginning I thought giving box2 a margin auto so the box2 would be in equal distance from top and bottom but I get this result.

It looks like it sets the margin auto for left and right but not for top and bottom.
So if I give a margin top myself it works like this.

Code:
.box2 {
   margin: 20px auto;
}

How can I do so the box2 is completely centered in the box1?
Answer:

.box1 {
background: black;
height: 400px;
width: 400px;
margin: auto;
}

.box2 {
height:300px;
width:300px;
background: red;
position:relative;
left:12.5%;
top:12.5%;
}

try this.
Answer:

.box1 {
background: black;
height: 400px;
width: 400px;
display:flex;
justify-content:center;
align-items: center;
}

.box2 {
height:300px;
width:300px;
background: red;
}

Answer: You can do this using flexbox

.box1 {
  background: black;
  height: 400px;
  width: 400px;
  margin: auto;
  display:flex;
  align-items: center;
  justify-content: center;
}

.box2 {
  height:300px;
  width:300px;
  background: red;
  margin: auto;
}

Answer: .box1 {
  position:relative;
  background: black;
  height: 400px;
  width: 400px;
  margin: auto;
}

.box2 {
  position:absolute;
  height:300px;
  width:300px;
  background: red;
  left:50%;
  top:50%;
  transform: translate(-50%, -50%);
}

Check the fiddle: https://jsfiddle.net/wh4yqk2y/


How to estimate count for Pandas dataframe column values based on multiple conditions?

Question: Given a pandas DataFrame df of the following format:-
StudyNo   Condition1      Condition2      ResultVal
1222          25              30              0.5
1245          30              45              0.12
1672          40              15              0.46
1222          25              30              0.95
1245          30              45              0.88
1245          30              45              0.23

I would like to calculate frequency/count of the number of ResultVal attributes existing in the dataset for a specific StudyNo under a given Condition1 and Condition2. There are no exactly duplicate rows in this dataset.
e.g. for StudyNo 1245 at Condition1 of 30 and Condition2 of 45, the count would be 3 (because 3 ResultVal attributes exist for this aspect). Also, I would like to print out a list of StudyNo, Condition1 and Condition2 in cases wherein < =1 ResultVal attributes exist (which in this example would be [1672,40,15].
Any help in this regard would be much appreciated.
Answer: You can groupby "StudyNo", "Condition1" and "Condition2" and transform count of "ResultVal" to create column "Frequency".
Then create a boolean mask for rows where "Frequency" is less than or equal to 1 and filter the rows that satisfy it.
cols = ['StudyNo','Condition1','Condition2']
df['Frequency'] = df.groupby(cols)['ResultVal'].transform('count')
appears_only_once = df.loc[df['Frequency'] <= 1, cols].to_numpy().tolist()

Output:
   StudyNo  Condition1  Condition2  ResultVal  Frequency
0     1222          25          30       0.50          2
1     1245          30          45       0.12          3
2     1672          40          15       0.46          1
3     1222          25          30       0.95          2
4     1245          30          45       0.88          3
5     1245          30          45       0.23          3

The list:
[[1672, 40, 15]]


Does the Mandelbrot Set with a power of -1 produce a Farey Sequence, and if so, can this be connected to the Riemann Hypothesis?

Question: I'm by no means an expert in Farey Sequences nor understanding the Riemann Hypothesis - but I do know there is some relationship between them, as alluded to in this question. As such, if the Mandelbrot Set with a -1 power (see image below) produces a Farey Sequence along the imaginary axis, could this be used to help solve/prove the non-trivial zeros for the Riemann Hypothesis? Has something like this already been attempted?
Note that the radii of the following circles will be reduced if either the bailout/threshold or the maximum iterations are increased, I don't know if they converge or not. The Escape-Time algorithm is used, so more detail might be revealed with a different algorithm.

Edit: On the subject, I noticed that as the Mandelbrot's power approaches zero, what would correspond to the first elements to the Farey Sequence move slower to the left:

I'm pretty sure that this is the Farey Sequence at this point, but all I have to show for it is just by looking at it. I wonder if algebraically solving for the boundary of this fractal will yield interesting insight...
Answer: Here is pixels $c$ coloured by iteration index $p$ where $|z_p|$ is minimized under iterations of $z_{n+1} = \frac{1}{z_n} + c$.  The right hand side is clamped to $\Re(c) = 0.01$ to make the structure clearer.  The Farey sequence seems to be visible (but this is no mathematical proof).


Static map with route in Image in windows phone 8.1

Question: I am working with windows phone 8.1 [RT] map application , I want to show Map Image with route like Google Static Map
Is there any way create Image in Windows phone map ?
I have tried with Bing map , with I have no Bing map key ,So I can not find anything
Thank you
Answer: check https://msdn.microsoft.com/en-us/library/ff701724.aspx#
You will still need to have a Bing map key, but creating one for a mobile app is free.


Set xml header with XmlSerializer

Question: My xml looks like that...
I have this fixed header I need to append to any xml file I am writing, an idea how do I do that?
**<?xml version="1.0"?>
<!DOCTYPE profile SYSTEM "criteria_profile.dtd">**
<profile type="INTERC" id="6 " description="MushonTest" state="" lastchuser="MUSHON" lastchtmstmp="20130903132018 " createuser="MUSHON">
    <root>
        <node type="A">
            <item description="crite3">
                <field>AUTHCKMAN<criterion sign="I" opt="EQ" low="cl" high=""/>
                </field>
                <field>JOBCLASS<criterion sign="I" opt="EQ" low="clas" high=""/>
                </field>
                <field>JOBNAME<criterion sign="I" opt="EQ" low="nam" high=""/>
                </field>
                <field>SDLUNAME<criterion sign="I" opt="EQ" low="creat" high=""/>
                </field>
            </item>

Answer: You can only do that via XmlWriter - not directly as part of the XmlSerializer API; but you can still use XmlSerializer here, for example:
var ser = new XmlSerializer(typeof(Foo));
using (var xw = XmlWriter.Create({any output device here}))
{
    xw.WriteDocType("profile", null, "criteria_profile.dtd", null);
    ser.Serialize(xw, new Foo());
}

which generates:
<?xml version="1.0"?><!DOCTYPE profile SYSTEM "criteria_profile.dtd"><Foo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />

Comment: For some reason, this removes `````` from my XML

Set xml header with XmlSerializer


outputStream escrevendo um byteArray - XSS validação

Question: Estou trabalhando com um software que passa por uma "Aplicação de Segurança" que indica as linhas de codigo que são potencialmente inseguras (teoricamente).
Tendo como base o código abaixo, a aplicação sinaliza a linha do outputStream.write() acusando de Improper Neutralization of Script-Related HTML Tags in a Web Page (Neutralização imprópria de codigo relacionado com tags html em uma página web)
response.addHeader("Content-Disposition","attachment; filename=" + Util.NeutralizeFileName(filename));
byte[] bytes = obj_Data.getBytes("File");
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
ouputStream.close();

Na verdade não estou escrevendo um html mas sim um arquivo para download. Além do mais, todos os dados "não confiáveis" provenientes do usuário estão sendo validados e neutralizados antes de serem convertidos para o array de bytes.
Então, minha pergunta é: Isso é um algum tipo de false warning (Alerta falso)? Caso não, o que posso fazer para produzir uma validação apropriada?
Answer: Sem saber o critério usado pela ferramenta é complicado especular.
Entretanto, o código acima pode gerar problemas de segurança pois o arquivo enviado via download poderia, em tese, ter conteúdo malicioso, desde HTML até um executável com vírus que seria baixado por um usuário.
Não sei qual a inteligência da ferramenta, mas talvez o aviso não seja inibido se os cabeçalhos Content-type, Content-transfer-encoding e Content-length forem adequadamente definidos para representar o arquivo binário.
O problema é que sem os cabeçalhos, o navegador teria que "adivinhar" qual o tipo do arquivo e isso pode ser causa de alerta.
Porém, em última análise, consulte o manual ou suporte da ferramenta em questão.
Comment: Sua resposta foi bastante útil, principalmente a parte em que diz `consulte o manual ou suporte da ferramenta em questão`. O problema é que a ferramenta não entende o **contexto** em que o software está escrevendo (ou seja, ele não distingue se é um HTML ou um arquivo para download). Então não é necessariamente um **false warning** mas sim um comportamento proposital da aplicação de análise.


Could it happen that XmlSerializer returns a String which is too long to be a string in Java?

Question: I am currently building an android application and decided to use the Xml implementation rather than a database to store data.
I'm loading the xml file into a list at application startup and when i want to save it back i format it to xml using XmlSerializer which then outputs to a StringWriter.
I then call .toString() on the StringWriter object and write that string back into a file.
I noticed however that the applications xml files grow quite rapidly and was wondering what would happen if it's length exceded the maximum string length.
Is there any way to get an array of strings from StringWriter?
Here's my Serializer Method.
public String articlesAsXml() {
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try {
        serializer.setOutput(writer);
        serializer.startDocument("UTF-8", true);
        serializer.startTag("", "articles");
        for (Articles art: AllArticles){

            serializer.startTag("", "art");

            serializer.startTag("", "id");
            serializer.text(art.Article_Id);
            serializer.endTag("", "id");

            serializer.startTag("", "title");
            serializer.text(art.Article_Title);
            serializer.endTag("", "title");

            serializer.startTag("", "body");
            serializer.text(art.Article_Body);
            serializer.endTag("", "body");

            serializer.endTag("", "art");
        }
        serializer.endTag("", "articles");
        serializer.endDocument();
        return writer.toString();
    }
    catch (Exception e) { return "Failed"; }
    return null;
}

Thanks in advance
Comment: Not sure if you'd welcome critiques on the design, but if you're worried about the size of the XML exceeding the maximum length of a string, you have to imagine that the performance of the application over time will degrade significantly.  Keeping in mind parsing/memory usage, you're quickly going to run into trouble. I'd consider using a database or at the very least, split the XML into multiple files.  Regarding your question, this might give some insight http://stackoverflow.com/questions/816142/strings-maximum-length-in-java-calling-length-method
Comment: Yes, of course i welcome critiques. I'm here to learn.
My only problem is that i ignorantly didn't about this problem earlier so i built my whole application relying on this system because it has to load other things a side from articles.
Thanks alot for your answer :)
So i think the best way to move would be to implement Natixs solution for the first version of my application and then start working with a data base for the other versions.
Answer: A string can be potentially as long as how much free heap memory you have. If you use it up, you'll get an OutOfMemoryError.
A solution would be not to use a StringWriter (which temporarily allocates memory for data that will be written into a file just afterwards), but to write the data into the file directly.
BufferedWriter writer = null;
try {
    writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
    serializer.setOutput(writer);
    ...
} catch (IOException e) {
    Log.e(tag, "cannot write to file " + file, e);
} finally {
    if (writer != null) {
        try {
            writer.close();
        } catch (IOException e) {
            Log.e(tag, "cannot close file " + file, e);
        }
    }
}

Comment: Thank you for your answer! I will start working on it :)


Edit node link in view redirects to false URL

Question: I have a view with a list of nodes and their associated edit links. The nodes can be categorised/filtered so I use an argument* in the view that I set manually on the content template of the pages to display the view (different pages should show different sets) -- there is no correlation between this argument and the path to the pages containing the view. This works fine except that every edit link in the view redirects to a path that is a combination of the page's internal path and some string identifier that depends on the page being shown but isn't the page's title. On node/6 the link looks like edit?destination=nodeIdentifierF6. I've confirmed the number at the end corresponds to the node's ID and it is always preceeded by a capital F. My guess is that Identifier is really meant to be % and that Views substitutes some argument I'm not sure where comes from.
Is there a way to fix this, or a different approach altogether (e.g. using filters in a way that allows me to control the node sets dynamically), short of creating a whole template for this minor annoyance?

*Actually there are two arguments plus the three from the Views Or module, but I'm assuming it doesn't consume arguments, and the other argument has a default value and shouldn't be used. Using filters would be more appropriate, as users shouldn't have control over what set of nodes to display anyway, but I couldn't find a way to adjust filters dynamically, and the alternative seems to be to create n idental views but for this filter. I am mentioning this in case it's important.

22/9 Update:
This appears to be related to drupal_get_destination(), which returns an encoded path (/ => %2F). For the view in question the %2 part must then be interpreted as an argument placeholder and substituted. I am no closer to a solution to the problem, unfortunately.
Answer: I ended up including the node ID and generating the edit link myself, with the catch that I can't hide the field for underprivileged users because it can never be empty (just prints an empty string in that case). It's an acceptable solution but I'd prefer to se the built-in method.


Prove $f$ is unique

Question: Let $A$ be a simply connected region in $\mathbb{C}$
Let $\Delta=\{z : |z|\lt 1 \}$
Prove that if $f$ is a conformal and bijective map, so that it sends a point $z_0 \in A$ to the origin and $f'(z_0 )\gt 0$ , then $f$ is unique.
Any hints on how to prove this? I'm new to complex analyisis (using Marsden's Book) and I'm a bit lost.
Answer: Hint. Let $g:A\to \Delta$ be another function which satisfies this property.
Then
$h:=g\circ f^{-1}:\Delta\to \Delta$ is a conformal and bijective map such that $h(0)=0$ and  $h'(0)=g'(z_0)/f'(z_0)>0$.
Then use Schwarz Lemma.

Prove $f$ is unique


How can I avoid the "Bad value language for attribute name on element meta" HTML validation error?

Question: I'm getting this error when I validate my HTML using the W3C validator:
Bad value language for attribute name on element meta: Keyword language is not registered.

<meta name="language" content="en" />

How can I solve this?
Comment: "How can I solve this?" By *not* using `language` as a value for the `name` attribute on the `meta` tag.
Comment: http://stackoverflow.com/questions/2874947/recommended-meta-elements here is the questions which gives good description
Answer: Use

Source
Answer: You should specify the language on the HTML tag, like so:

You can also ues the lang attribute on any element, so if you have just one div with French in it, you could do:

    ...

        ...

        ...

Answer: I think you're looking for content-language
<meta http-equiv="Content-Language" content="en" />

Comment: I used that. Now i'm getting error as:
Using the meta element to specify the document-wide default language is obsolete. Consider specifying the language on the root element instead.
Comment: In this case you have to use ```` as already replied by several other persons.
Comment: @Veena: see [@AshBurlaczenko's answer](http://stackoverflow.com/a/15969876/20578)
Comment: `Bad value Content-Language for attribute name on element meta: Keyword content-language is not registered.`

The Content-Language value for an http-equiv attribute on a meta element should no longer be used. You should use a language attribute on the html tag to declare the default language of the actual text in the page.