Q:

how to pass value from NavigationDrawerFragment.java to MainActivity.java then pass to AnotherFragment page

in my NavigationDrawerFragment.java
i have this code
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
    @Override
    public boolean onChildClick(ExpandableListView parent, View v,
                                int groupPosition, int childPosition, long id) {
        String header = listDataHeader.get(groupPosition);
        Category child = listDataChild.get(header).get(childPosition);

        // child.name to get the name
        // child.id to get the id
        //Toast.makeText(getActivity(),"ChildNme: "+child.name+" ChildId: "+child.id, Toast.LENGTH_SHORT).show();

        selectItem(1);

        return false;
    }
});

after i click the child, i set selectItem to 1
the selectItem(1) will go to MainActivity.java
public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments

        FragmentManager fragmentManager = getFragmentManager();

        // NEW STUFF
        if(position == 1){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, CategoryFragment.newInstance())
                    .commit();
        }

}

my question is how to pass the child.name and child.id from NavigationDrawerFragment.java to MainActivity.java then pass to CategoryFragment?
or any other solution to pass the child.name and child.id to CategoryFragment.
COMPLETE CODE
NavigationDrawerFragment.java
package com.example.administrator.mosbeau;

import android.app.FragmentManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Fragment used for managing interactions for and presentation of a navigation drawer.
 * See the
 * design guidelines for a complete explanation of the behaviors implemented here.
 */
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;

    String myJSON;
    private static final String TAG_RESULTS="result";
    private static final String TAG_ID = "categories_id";
    private static final String TAG_NAME = "categories_name";
    JSONArray categories = null;

    public NavigationDrawerFragment() {
    }

    Boolean InternetAvailable = false;
    Seocnd detectconnection;

    @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);
    }

    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<Category>> listDataChild;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View fragmentView =  inflater.inflate(
                R.layout.fragment_navigation_drawer, container, false);
        /*mDrawerListView = (ListView) fragmentView.findViewById(R.id.listView);

        //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);
            }
        });
        mDrawerListView.setAdapter(new ArrayAdapter<String>(
                getActionBar().getThemedContext(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1,
                new String[]{
                        getString(R.string.title_home),
                        getString(R.string.title_category),
                        getString(R.string.title_myaccount),
                        getString(R.string.title_referafriend),
                        getString(R.string.title_about),
                        getString(R.string.title_privacypocity),
                        getString(R.string.title_shippingterms),
                        getString(R.string.title_contactus),
                }));
        mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);*/

        // get the listview
        expListView = (ExpandableListView) fragmentView.findViewById(R.id.lvExp);

        // preparing list data
        //prepareListData();

        detectconnection = new Seocnd(getActivity());
        InternetAvailable = detectconnection.InternetConnecting();
        if (InternetAvailable) {
            getData();
        } else {
            selectItem(100);
        }
        return fragmentView;
    }

    public void getData(){
        class GetDataJSON extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/categories.php");

                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                myJSON=result;
                prepareListData();

                listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);

                // setting list adapter
                expListView.setAdapter(listAdapter);

                // Listview Group click listener
                expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

                    @Override
                    public boolean onGroupClick(ExpandableListView parent, View v,
                                                int groupPosition, long id) {
            /*Toast.makeText(getActivity(),
            "Group Clicked " + listDataHeader.get(groupPosition),
            Toast.LENGTH_SHORT).show();*/
                        if(groupPosition == 1){
                            return false;
                        } else {
                            selectItem(groupPosition);
                            return true;
                        }
                    }
                });

                // Listview on child click listener
                expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

                    @Override
                    public boolean onChildClick(ExpandableListView parent, View v,
                                                int groupPosition, int childPosition, long id) {
                        // TODO Auto-generated method stub

                        String header = listDataHeader.get(groupPosition);
                        Category child = listDataChild.get(header).get(childPosition);

                        // child.name to get the name
                        // child.id to get the id
                        Toast.makeText(getActivity(),"ChildNme: "+child.name+" ChildId: "+child.id, Toast.LENGTH_SHORT).show();
                        //selectItem(1);

                        return false;
                    }
                });
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }

    protected void prepareListData(){
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            categories = jsonObj.getJSONArray(TAG_RESULTS);

            listDataHeader = new ArrayList<String>();
            listDataChild = new HashMap<String, List<Category>>();

            // Adding group data
            listDataHeader.add("HOME");
            listDataHeader.add("CATEGORY");
            listDataHeader.add("MY ACCOUNT");
            listDataHeader.add("REFER A FRIEND");
            listDataHeader.add("ABOUT");
            listDataHeader.add("PRIVACY POLICY");
            listDataHeader.add("SHIPPING TERMS");
            listDataHeader.add("CONTACT US");

            List<Category> CATEGORY = new ArrayList<Category>();
            for(int i=0;i<categories.length();i++){
                JSONObject c = categories.getJSONObject(i);
                Category category = new Category();
                category.name = c.getString(TAG_NAME);
                category.id = c.getString(TAG_ID);

                CATEGORY.add(category);
            }

            listDataChild.put(listDataHeader.get(1), CATEGORY); // Header, Child data

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

    }

    /*
     * Preparing the list data
     */
    /*private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();

        // Adding group data
        listDataHeader.add("HOME");
        listDataHeader.add("CATEGORY");
        listDataHeader.add("MY ACCOUNT");
        listDataHeader.add("REFER A FRIEND");
        listDataHeader.add("ABOUT");
        listDataHeader.add("PRIVACY POLICY");
        listDataHeader.add("SHIPPING TERMS");
        listDataHeader.add("CONTACT US");

        // Adding child data
        List<String> CATEGORY = new ArrayList<String>();
        CATEGORY.add("Category 1");
        CATEGORY.add("Category 2");
        CATEGORY.add("Category 3");
        CATEGORY.add("Category 4");
        CATEGORY.add("Category 5");

        listDataChild.put(listDataHeader.get(1), CATEGORY); // Header, Child data
}*/

    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.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();
    }

    /**
     * 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);
    }
}

MainActivity.java
package com.example.administrator.mosbeau;

import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;

public class MainActivity 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;

    Boolean InternetAvailable = false;
    Seocnd detectconnection;

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

        detectconnection = new Seocnd(this);
        InternetAvailable = detectconnection.InternetConnecting();
        if (InternetAvailable) {
        } else {
            NointernetFragment fragment = new NointernetFragment();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, fragment)
                    .commit();
        }

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().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();

        // NEW STUFF
        if(position == 0){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, HomeFragment.newInstance())
                    .commit();
        }
        else if (position == 1){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, CategoryFragment.newInstance())
                    .commit();
        }
        else if (position == 2){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, AccountFragment.newInstance())
                    .commit();
        }
        else if (position == 3){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, ReferFragment.newInstance())
                    .commit();
        }
        else if (position == 4){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, AboutFragment.newInstance())
                    .commit();
        }
        else if (position == 5){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, PolicyFragment.newInstance())
                    .commit();
        }
        else if (position == 6){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, TermsFragment.newInstance())
                    .commit();
        }
        else if (position == 7){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, ContactusFragment.newInstance())
                    .commit();
        }
        else if (position == 100){
            fragmentManager.beginTransaction()
                    .replace(R.id.container, NointernetFragment.newInstance())
                    .commit();
        }
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.title_home);
                break;
            case 2:
                mTitle = getString(R.string.title_category);
                break;
            case 3:
                mTitle = getString(R.string.title_login);
                break;
            case 4:
                mTitle = getString(R.string.title_register);
                break;
            case 5:
                mTitle = getString(R.string.title_myaccount);
                break;
            case 6:
                mTitle = getString(R.string.title_referafriend);
                break;
            case 7:
                mTitle = getString(R.string.title_about);
                break;
            case 8:
                mTitle = getString(R.string.title_privacypocity);
                break;
            case 9:
                mTitle = getString(R.string.title_shippingterms);
                break;
            case 10:
                mTitle = getString(R.string.title_contactus);
                break;
            case 100:
                mTitle = getString(R.string.title_nointernet);
                break;
        }
    }

    @SuppressWarnings("deprecation")
    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 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();

        //noinspection SimplifiableIfStatement
        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_main, container, false);
            return rootView;
        }

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

    }

}

CategoryFragment.java
package com.example.administrator.mosbeau;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

/**
 * Created by Administrator on 9/18/2015.
 */
public class CategoryFragment extends Fragment {

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

    public CategoryFragment () {
    }

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

        getActivity().invalidateOptionsMenu();

        return rootView;
    }

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

A:

update your selectitem() and onNavigationDrawerItemSelected methods to accept two more arguments i.e child.id and child.name
private void selectItem(int position,String id,String name) {
    mCurrentSelectedPosition = position;
    if (mDrawerListView != null) {
        mDrawerListView.setItemChecked(position, true);
    }
    if (mDrawerLayout != null) {
        mDrawerLayout.closeDrawer(mFragmentContainerView);
    }
    if (mCallbacks != null) {
        mCallbacks.onNavigationDrawerItemSelected(position,id,name);
    }
}

pass child.id and child.name in selectItem() method so which in turn will call onNavigationDrawerItemSelected() method implemented in MainActivity.
Now in MainActivity, pass the values to the fragment using Bundle
here
fragmentManager.beginTransaction()
                .replace(R.id.container, CategoryFragment.newInstance(id,name))
                .commit();

you will also need to update to CategoryFragment.newInstance(String,String) to accept the arguments
Updating code to 'setText' in 'edittext'
In your 'CategoryFragment' 'newInstance' method pass data in bundle like below
CategoryFragment categoryfragment = new CategoryFragment()
Bundle bundle = new Bundle()
bundle.putStringExtra("id",id)
bundle.putStringExtra("name",name)
categoryfragment.setArguements(bundle)

return categoryfragment

Now in onCreateView of  Categoryfragment get this data like below
if(getArguments().getExtras != null) {
    String catid = getArguments.getStringExtra("id");
    String catname = getArguments.getStringExtra("name");

    yourEditText.setText(catname);
}

Hope you got my point


Q:

Why isn't a StopIteration raised here?

Take a look at this, the crux of the question is at the bottom:
>>> scan = iter('FHUR203459')
>>> while True:
        print(next(scan))

F
H
U
R
2
0
3
4
5
9
Traceback (most recent call last):
  File "<pyshell#11>", line 2, in <module>
    print(next(scan))
StopIteration
>>> scan = iter('FHUR203459')
>>> for i in range(12):  # 12 * 2 for each join is 24, much longer than the string; should raise error.
        print(''.join(next(scan) for i in range(2)))

FH
UR
20
34
59

>>>

In other words, we can see that the iterator reaches its end in both situations, however it only raises a StopIteration in the first, even though next() is used in both situations after it reached the end. Why does using it in join seem to evade the error? Or is this a bug?

A:

In the first case, the StopIteration is not handled anywhere. But in the second case,
''.join(next(scan) for i in range(2))

we pass a generator expression to the ''.join, which handles the StopIteration raised by next(scan) and exits every time. That is why ''.join produces empty strings.
You can slightly modify the same, and pass a list to ''.join and see the exception being raised, yourself, like this
>>> scan = iter('FHUR203459')
>>> for i in range(12):
...     print(''.join([next(scan) for i in range(2)]))
...
FH
UR
20
34
59
Traceback (most recent call last):
  File "<input>", line 2, in <module>
  File "<input>", line 2, in <listcomp>
StopIteration

It shows that the StopIteration is actually raised, and List Comprehension takes the hit, this time.


Q:

Does the AFP Service ACL still exist in 10.9 Server.app?

All I'm really trying to do is set up my wife's laptop to use my Mac Pro as a network Time Machine server. We both recently upgraded to Mavericks and I just installed Server.app.
Problem is all connection attempts from her account fail, and I can't work out why (after lots of time and effort diagnosing the problem).
One ars forum post describes a similar problem, and one of the suggestions is that the connection is being blocked by a SACL. This theory is validated by the fact that I can connect with my own (admin) account.
More searching, and it seems that the suggestion is to edit the SACL using the Server Admin app. I guess this has now been rolled into Server.app?
Can someone please enlighten me, where are Service ACLs configured?

A:

You can enable individual access to services for users and groups inside of Server.app 3.0. Select the Users or Groups section from the sidebar, and then click on the user or group that you'd like to configure access for. Click on the action (gear) icon below the list of users or groups, and choose "Edit Access to Services...":

You'll be presented with a list of services that allow access to be enabled and disabled for this user/group. If the list is disabled, you may need to choose to "Manage Service Access":

The software may prompt you to confirm your choice to enable management of Service Access:

Some information on how to configure these checkboxes using dseditgroup is available. It should also be noted that users from external directories are denied access to services by default.
If you're just trying to confirm that the user is inside of the group that's allowed to access the AFP service, you can perform this command:
dscl localhost read /Local/Default/Groups/com.apple.access_afp GroupMembership

If the command reports that the record is not found (-14136), you probably don't have an ACL applied to the AFP service.


Q:

after git push not changing the permission of a directory?

I am also use the .gitignore to exclude it from the project but it will change the permission of a directory as /Public/example/
So how to ignore a file or directory from a git while pushing not changing the permission of a specific folder.
Thanks in advance!!
In laravel 5

A:

This will tell git to ignore permissions:
git config core.filemode false

http://www.ivankristianto.com/git-ignore-file-permission/


Q:

Should I be talking to HR about my struggles with stress and depression at my workplace?

I've been really, really struggling with workplace related stress and depression. Recently, my companies HR department sent out a survey to check the mental health of the company. I decided to respond honestly, that I was struggling. This resulted in a meeting with HR where I described the reasons I was getting stressed and depressed.
Whilst they were nice, they only really offered to follow up one thing to change with my work load (in a very indirect way). They kind of implied - nicely - the rest was my own problem and that I should be seeking professional help for the stress and depression.
Today I had an overwhelming amount of work to do and a huge amount of pressure, which ultimately lead to a panic attack. I'm really at the point where I need things to change for my own health.
I'm kind of in two minds about this - I'm at the point where I almost no longer care if I lose the job, but at the same time something is telling me not to rock the boat to much and to not tell HR about mental health issues.
What's the correct thing to do? Should I tell HR that I am having a very tough time or just shut up and deal with it?
Edit with clarifications:
Country is Australia. The survey was voluntary and you could be anonymous if you wished. The survey came after a national mental health awareness day.
I also feel I should make a clarification on a point as maybe I worded things wrongly: It is my belief the the stress and depression I mentioned is due to the work environment and load, not a personal problem I already have that I bring to work. Perhaps I was wrong to do so but I initially contacted HR with the same mindset someone would contact them about an OHAS concern.

A:

What's the correct thing to do?

Do not continue talking to HR about this, they are not your friend.  HR exists to protect the company.

Should I tell HR that I am having a very, very tough time, or just
  shut up, deal with it and work poorly?

At this point, you have already shined the HR spot light on you, I would not draw further attention from them.  I would, however, seek out professional help from your doctor.  You are way past the point, in my opinion, of dealing with it yourself since you have already had a panic attack.
In the meantime continue doing your best, follow your doctor's advise, up to and including leaving the job.  Your health is number one, all else is second.
Hopefully with your doctors help, you will be able to cope with your job and be productive.

A:

Human Resources can't help you with this. That isn't their role. HR's job is to look out for the interests of the company and make sure the employees aren't causing problems. They aren't counselors and are not able to help you with your mental health issues.
If your workload is giving you problems, you need to talk to your manager and work with them to find a balance you can handle. The pace you are going is not sustainable and you cannot keep taking on everything that you have been doing. You need to figure what parts of your job are essential, and what can be left for another day. You don't need to take it all on (you can't, and shouldn't try), but work with your manager to figure out what actually needs to be done. You're already burning out, if they keep pushing you they will lose you, and that won't be good for anyone.
Secondly, take HR's advice and seek professional help. A good therapist will help you find ways to deal with the stress. This is really important, especially if you are also having trouble with depression. Do this today.
Your health is too important to let this slide. You are right that you should talk to someone, but that someone should be a professional trained to help you with these issues. Not the HR department.

A:

They kind of implied - nicely - the rest was my own problem and that I
  should be seeking professional help for the stress and depression.

They are correct.
While HR can help adjust a few things in your workplace to help you, they are not mental health professionals.
Your health is your responsibility. And if you don't handle this, your work will suffer and you will put your job in jeopardy. If you consistently find that you have panic attacks when the workload gets high, this job and perhaps this profession might not be for you. But don't jump to that conclusion without a professional assessment!
You need to get yourself to your doctor and seek help. Do it now. This is not a workplace issue - this is a mental health issue.


Q:

Deletions don't show up in the profile's activity tab

I just deleted an answer of my own that should have been a comment. I would have expected a deletion action to show up in the activity tab of my profile, but there isn't.
What's the rationale to ignore deletions in the activity?
PS: I know now that I also could have flagged the answer for conversion into a comment, but it was an old and inactive question, so no need.

A:

No deleted content appears in user profiles, not even for 10k users. Only diamond mods can see those posts right in the profile. (Not saying this is necessarily the behaviour we'd like, but that's what happens.)
The reason why it's done this way is because deleted content is considered as "never having been created in the first place." This is also why a reputation recalc does not count reputation earned or lost on deleted content.


Q:

Method for optionally nested models in Django

I am creating a simple internal asset tracking app for my company.  Currently we do this through excel (terrible).  I'm breaking this down to:
Asset/Item - The tool, hardware, part etc.
Site - The overall location it's at: Facility A, Site Location B
Bin - A sublocation an asset is located, this could be a building, a toolbox, a crate.
The Bin is causing me problems because an Item can be location at a Site without a Bin, or a Bin can be located inside another Bin, I am not yet sure the best way to structure this database.
I have tried having multiple foreign keys but that gets messy or atleast feels so.  I have also tried using the alternatives to Django's GenericForeign Keys as listed here  I have used them before with subtly different apps but the self referencing is confusing me.  In the end I want to be able to gather a list of items at a site and then have indented lines for each toolbox and the items inside, is there a good method for setting up the models so this can happen?

A:

There are two points of view you might want to consider: 1. whether the model is easy to read, non redundant and consistent with your problem, 2. what kind of queries you are ging to run on the model.
You have already thought about the first aspect. regarding the second I believe some of the queries you want to execute are:
1. listing the assets and link their location.
2. count the assets at a location
3. navigate the location hierarchy and list all the assets at each location
The above suggest that you create a single model for the locations that includes buildings, bins, etc. and differentiate them through a field location_type that could be foreign key to a dictionary table (id, name). then you would need a self referencing foreign_key to the parent location, to create the hierarchy.
This way you would have a single foreign key to the location from the asset and given the location you could query asset_set directly. Any other model would be less transparent. Any difference can be addressed using @property methods, e.g. to save a field that is specific for building you can create a method that first checks if the type is correct and then saves the value into a dynamic field like char_field_1
A variation of the above. If the attributes for Bin, Building etc. are too many and different to be consolidated in one table. Then you can create separate models for each and have a nullable one-to-one field from Location to each. On save you can check that no more than one has been populated.


Q:

Oracle apex 5.1 change user password with pl/sql

I'm wondering how you change user passwords in oracle apex. Currently I'm trying to use this pl/sql code in a process when the user exists and the reset password field is filled in.
if APEX_UTIL.GET_USERNAME(p_userid => :P5_ID) IS NOT NULL AND :P5_WACHTWOORD IS NOT NULL
then
    apex_util.edit_user(
        p_user_id => &P5_ID.,
        p_new_password => '&P5_WACHTWOORD.'
    );
end if;

But apex keeps giving me this error: PLS-00306: wrong number or types of arguments in call to 'EDIT_USER'.
I tried adding the old password in the p_web_password param incase apex needed this. I still got the same error.
Just incase I'm doing it completely wrong. I just started using apex and I'm trying to use the default authentication, but I also want to store more stuff about the same user in my own database.
I decided to use the userid my database generates as the apex userid so I can keep track which user is logged in. Is this the right way or are there better options out there?

A:

A cursory glance at the documentation for the API shows the p_user_name is also a mandatory input.
    APEX_UTIL.EDIT_USER (
        p_user_id                      IN                   NUMBER,
        p_user_name                    IN                   VARCHAR2,
        p_first_name                   IN                   VARCHAR2    DEFAULT NULL,
        p_last_name                    IN                   VARCHAR2    DEFAULT NULL,
        p_web_password                 IN                   VARCHAR2    DEFAULT NULL,
...

http://docs.oracle.com/database/apex-5.1/AEAPI/EDIT_USER-Procedure.htm#AEAPI117
Is there any reason you aren't using bind variables for the actual parameter values?
p_user_id => :P5_ID


Q:

XNA 2D Camera loosing precision

I have created a 2D camera (code below) for a top down game. Everything works fine when the players position is close to 0.0x and 0.0y.
Unfortunately as distance increases the transform seems to have problems, at around 0.0x 30e7y (yup that's 30 million y) the camera starts to shudder when the player moves (the camera gets updated with the player position at the end of each update) At really big distances, a billion + the camera wont even track the player, as I'm guessing what ever error is in the matrix is amplified by too much.
My question is: Is there either a problem in the matrix, or is this standard behavior for extreme numbers.
Camera Transform Method:
public Matrix getTransform()
{
    Matrix transform;

    transform = (Matrix.CreateTranslation(new Vector3(-position.X, -position.Y, 0)) *
            Matrix.CreateRotationZ(rotation) * Matrix.CreateScale(new Vector3(zoom, zoom, 1.0f)) *
    Matrix.CreateTranslation(new Vector3((viewport.Width / 2.0f), (viewport.Height / 2.0f), 0)));

    return transform;
}

Camera Update Method:
This requests the objects position given it's ID, it returns a basic Vector2 which is then set as the cameras position.
if (camera.CameraMode == Camera2D.Mode.Track && cameraTrackObject != Guid.Empty)
{
    camera.setFocus(quadTree.getObjectPosition(cameraTrackObject));
}

If any one can see an error or enlighten me as to why the matrix struggles I would be most grateful.

A:

I have actually found the reason for this, it was something I should have thought of.
I'm using single precision floating points, which only have precision to 7 digits. That's fine for smaller numbers (up to around the 2.5 million mark I have found). Anything over this and the multiplication functions in the matrix start to gain precision errors as the floats start to truncate.
The best solution for my particular problem is to introduce some artificial scaling (I need the very large numbers as the simulation is set in space). I have limited my worlds to 5 million units squared (+/- 2.5 million units) and will come up with another way of granulating the world.
I also found a good answer about this here:
Vertices shaking with large camera position values
And a good article that discusses floating points in more detail:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Thank you for the views and comments!!


Q:

How to use quotation marks in a text string in Flutter?

How do I write quotation marks in a text inside do:
ex:  child: Text ("One fine day I woke up from" Bad Mood "was Monday"),
Container(
    color: Colors.white,
    height: 50,
    width: 390,
    margin: EdgeInsets.only(left: 15.0, top: 15.0, right: 15.0, bottom: 5.0 ),
    alignment: Alignment.topRight,
    child: Text ("2 لا تتطلب النية قول أي شيء بصوت عال، ولكن التركيز على عبارة "بسم الله".", textDirection: TextDirection.rtl,
      style: TextStyle(
        decoration: TextDecoration.none,
        fontSize: 25.0,
        fontFamily: 'Poppins',
        fontWeight: FontWeight.w600,
        color: Colors.black,
      ),),

  ),

A:

child:  Text ('One fine day I woke up from" Bad Mood "was Monday'),

Reference : Difference between single and double quotes in Flutter/Dart


Q:

deleting in tables in a specific order

Hy,my question is how can i use a procedure in which i can delete data from one table and then from the other to avoid the problem with the REFERENTIAL INTEGRITY, I tried it like this
 create procedure usp_Testovi_Delete
 (
 @TestoviID int
 )
 as
 delete from Testovi
  where TestoviID=@TestoviID
  delete from RezultatiTesta
  where TestoviID=@TestoviID

but I need to execute it twice to delete data from both tables , ty for your time and help , I'm using SQL server.

A:

There are a variety of ways to handle this:

Delete from the table with the foreign key first.
Wrap the first delete in a blank exception handler, then delete from the second table, and finally delete from the first table again.
Disable the foreign keys while you perform the delete, and re-enable them afterward.

They each have advantages and disadvantages :-/


Q:

Python os.path.dirname and os.path.sep in Java?

Python has os.path.dirname and os.path.sep.  How can I get these values in Java?

A:

Did a bit of googling on what os.path.dirname and os.path.sep actually are
os.path.dirname(path) would be filePath.split(System.getProperty("path.separator"))[0]
os.path.sep would be System.getProperty("file.separator")


Q:

H.264 encoded MP4 presented in HTML5 plays on Safari but not iOS devices

I'm using Adobe Media Encoder CS5 to encode a FLV file to H.264 to present on the web via HTML5 and the video file plays just fine in Safari in OS X (and in Firefox encoded to OGG) but on any iOS device (iPad, iPhone) I get the play icon with the slash running through it.
Has anyone encountered this before and if so, any ideas as to why?
Thanks.

A:

We had this problem and found that encoding the files in accordance with iPhone's webview's standards created files that played fine.
Not all H.264 encoded Mp4 files are supported by iPhone (or Chrome for that matter) and slight differences in the encoding process can produce videos that do not work. Even if the EXACT same encoding settings were used, H.264 is a variable bit-rate encoder, so different videos may exceed bitrate limits, causing some to work and other not.
The encoding settings that were successful for us were:

Only use the H.264 Baseline Profile Level 3.0
Resolution below 640 x 480 and framerate up to 30 fps
B frames are not supported in the Baseline profile.
bitrate limit of 900kb.

Here is the reference we used to arrive at those settings.

A:

I know this has a marked answer, but we had the exact same issue.
The problem ended up being a setting on our internal network.
After turning on the safari console on the iPad, we saw that when trying to load the video we were getting a "byte_range_error_message" being logged. It seems the mobile devices request this content differently than desktop devices, by requesting certain bytes at a time. We managed to find out that the video played fine when the phones used their 3G networks, but not when they loaded the video through the internal wifi.  A lot of research later led us to this MSDN article:
http://support.microsoft.com/kb/922330
Which explained how to find the setting in our firewall to allow the devices to request the video properly. We also found a similar setting on one of our D-Link routers for a separate wifi network that was also having the problem.


Q:

Como instalar PyQt5 en Windows

intente instalar PyQt5 pero me dio el siguiente error
¿Alguien sabe como arreglar esto, como puedo instalarlo?

A:

Puedes utilizar pip install PyQt5 y si necesitas instalar el QtDesigner utiliza pip install pyqt5-tools
y el QtDesigner estara en una ruta similar a esta:
C:\Users\tu-usuario\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\pyqt5-tools


Q:

Same width containers with flex-grow not working

I'm trying to use flex to create flex-items of same width, but they keep changing width depending on number of children in flex-item
fiddle
As you can see, the right green container is much smaller, even though both have flex-grow:1
How can I fix this? Thanks!
span {
    display: inline-block;
    width: 10px;
    height: 30px;
    border: 1px solid red;
}
.container {
    display: flex;
    display: -webkit-flex;
    border: 1px solid blue;
    width: 200px;
    padding: 2px;

}
.item {
    flex-grow: 1;
    -webkit-flex-grow: 1;
    border: 1px solid green;
}

A:

using flex:1 instead of flex-grow:1 seems to fix the issue.

A:

This is because flex-basis defaults to auto, which factors in the width of the element. To keep your elements the same with, you need to explicitly set flex-basis: 0:
.item {
  flex-basis: 0;
  flex-grow: 1;
}

See: https://jsfiddle.net/Wexcode/Lgqhcr07/


Q:

Unable to boot from USB flash drive

I have a image of ubuntu that I have used before on a USB flash drive. On my laptop, a MSI GE72 6QD Apache Pro, I am unable to boot from it. When I reboot into the recovery tools, no option to boot from external media is available. I am unsure how to do this. Thank you!

A:

The boot issue from other devices is usually in the wrong BIOS setting. Go to the BIOS configuration. When you turn on your computer and when you see the BIOS-POST tests (white text on the screen), press the DEL key on the keyboard (a different keyboard shortcut on each computer - in your case, the DEL key), and then check the BIOS settings for booting from different devices. Check the boot device order and set up as the first USB device.
Simply search for the "boot" text in your manual for your motherboard or your notebook. The problem may also be the UEFI mode, not all boot devices are formatted to work with the new UEFI mode, so it may be better to activate the "UEFI with CSM" instead of the "UEFI" mode.
English manual (including the BIOS configuration) for your notebook:
http://download.msi.com/archive/mnu_exe/1795+1794+16J5+16J4_G_English.zip
You can also use the Quick Boot Menu, but instead of pressing the DEL key to enter the BIOS configuration, press the F11 key. In a fast BOOT-MENU, you select the USB device. But first you may need to switch from "UEFI" to "UEFI with CSM" to make the USB device visible in BOOT-MENU.


Q:

OpenGL Accumulation Buffer in SFML?

How would I enable the glAccum buffer in SFML? It doesn't appear to exist by default (glGet(GL_ACCUM_BLUE_BIT) returns 0). Is this even possible?

A:

Not with SFML 1.6 or 2.0. And I wouldn't hold my breath on them adding such a feature anytime soon. They were incredibly resistant to the simple suggestion of allowing sRGB framebuffers.
I'd suggest switching to Allegro 5, as they provide accumulation buffer support.


Q:

Define parameters to be used in a web page as an input

I'm trying to submit two parameters to be used in a javascript function. The code is as follows:
<!DOCTYPE html>

<form >
first input:

<input type="text" y="Y" value=85>

second input:

<input type="text" x="X" value=15>

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

<button type="button" onclick="func1(x,y)">Try it</button>

The error I get is Uncaught ReferenceError: x is not defined How should I define x and y as an input to be put in js function?

A:

https://jsfiddle.net/hmfcLsf2/1/

<form >
first input:

<input id="y_field" type="text" y="Y" value=85>

second input:

 <input id="x_field" type="text" x="X" value=15>

</form>

<button type="button" onclick="func1(document.getElementById('x_field').value,document.getElementBy    Id('y_field').value)">Try it</button>

Use getElementById. See the jsfiddle above.


Q:

Retain URL in browser with Flask redirect

I have a Bokeh server application deployed on Heroku, with multiple styles that result in cumbersome URLs. For example: https://invlabs-bokehserver.herokuapp.com/avyview?style=snowpacktracker
I am using Flask deployed on Heroku to take extensions from a simple custom domain (www.snowpacktracker.com) and redirect to a second Heroku app that runs a Bokeh server and returns the html content. The relevant Flask app code:
from flask import Flask, redirect

app = Flask(__name__)
@app.route('/')
def index():
  return redirect(url_for("btac"), code=302)

@app.route('/btac')
def func1():
  return redirect("https://invlabs-bokehserver.herokuapp.com/avyview?style=snowpacktracker", code=302)

@app.route('/btac/historic')
def btac_historic():
  return redirect("https://invlabs-bokehserver.herokuapp.com/avyview", code=302)

if __name__ == '__main__':
  app.run()

I would like the original URL to remain the same while the Flask redirect occurs. Is there an option within Flask to do this? Or can I configure the web server to accomplish this?
UPDATE and further details:
I cannot get the nginx proxying to work correctly. My current situation:
www.snowpacktracker.com is setup as a custom domain (using a Heroku-provided DNS target) for my Heroku app that is running nginx + gunicorn + Flask (this is a working link you can use to see the current behavior). The underlying URL for this Heroku app is https://snowpacktracker.herokuapp.com.
When this first Heroku app receives a request, the Flask app redirects to a second Heroku app running a Bokeh server. As currently implemented, you can see the URL switch in the browser to https://invlabs-bokehserver.herokuapp.com/avyview?style=snowpacktracker.
Both www.snowpacktracker.com and www.snowpacktracker.com/btac redirect to the same URL. I have a second style defined with www.snowpacktracker.com/btac/historic that redirects to https://invlabs-bokehserver.herokuapp.com/avyview.
My goal is for a page load of www.snowpacktracker.com (and any extensions: /btac or /btac/historic) to redirect via Flask as is currently implemented, but for the original URL to remain unchanged.
I have been trying to edit the location block in the nginx.conf.erb config file according to the link in the answer from @Fian, but I am having no luck.
What are the correct statements for proxy_pass or proxy_redirect (or rewrite?) in the location block to accomplish this desired behavior?
My current nginx config file (provided in the Heroku nginx build pack):
daemon off;
#Heroku dynos have at least 4 cores.
worker_processes <%= ENV['NGINX_WORKERS'] || 4 %>;

events {
    use epoll;
    accept_mutex on;
    worker_connections 1024;
}

http {
        gzip on;
        gzip_comp_level 2;
        gzip_min_length 512;

    server_tokens off;

    log_format l2met 'measure#nginx.service=$request_time request_id=$http_x_request_id';
    access_log logs/nginx/access.log l2met;
    error_log logs/nginx/error.log;

    include mime.types;
    default_type application/octet-stream;
    sendfile on;

    #Must read the body in 5 seconds.
    client_body_timeout 5;

    upstream app_server {
        server unix:/tmp/nginx.socket fail_timeout=0;
    }

    server {
        listen <%= ENV["PORT"] %>;
        server_name _;
        keepalive_timeout 5;

        location / {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
        }
    }
}

A:

I think your "relevant flask code" looks a bit redundant, as the whole thing can easily be implemented in nginx alone, without the need for the flask code you provide.
Something like this may work:
server_name .snowpacktracker.com;
location = / {
    return 302 /btac;
}
location / {
    return 404;
}
location /static {
    proxy_pass http://invlabs-bokehserver.herokuapp.com;
}
location /avyview {
    proxy_pass http://invlabs-bokehserver.herokuapp.com;
}
location = /btac {
    proxy_pass http://invlabs-bokehserver.herokuapp.com/avyview?style=snowpacktracker;
}
location = /btac/historic {
    proxy_pass http://invlabs-bokehserver.herokuapp.com/avyview;
}

Note that your underlying app, at invlabs-bokehserver.herokuapp.com/avyview, explicitly mentions its own full URL in several instances, including for automatic JavaScript-based redirect to the mobile version (i.e., window.location = 'https://btac-web-plots.herokuapp.com/avyview?style=snowpacktracker-mobile';); this will obviously interfere with your desire to "hide" the underlying URL of the application.


Q:

How to substitute variable contents in a Windows batch file

I'm writing a simple script to substitute text in an environment variable with other text. The trouble I get is with the substituted or substituted text being pulled from other variables
SET a=The fat cat
ECHO %a%
REM Results in 'The fat cat'
ECHO %a:fat=thin%
REM Results in 'The thin cat'

Works fine (output is 'The fat cat' and 'The thin cat'
However, if 'fat' or 'thin' are in variables, it doesn't work
SET b=fat
ECHO %a:%c%=thin%
REM _Should_ give 'The thin cat'.
REM _Actually_ gives '%a:fat=thin%' (the %c% is evaluated, but no further).

REM using delayed evaluation doesn't make any difference either
ECHO !a:%c%=thin!
REM Actual output is now '!a:fat=thin!'

I know this can be done as I've seen it in blogs before, but I never saved the link to the blogs.
Anyone have any ideas?
PS. I'm running the scripts on Windows 7
PPS. I know this is easier in Perl/Python/other script language of choice, but I just want to know why something that should be easy is not immediately obvious.
PPPS. I've also tried the scripts with delayed expansion explicitly turned on
SETLOCAL enabledelayedexpansion

This makes no difference.

A:

Please try the following:
Copy and paste the code into Notepad and save it as a batch file.
   @echo off
   setlocal enabledelayedexpansion

   set str=The fat cat
   set f=fat

   echo.
   echo          f = [%f%]

   echo.
   echo        str = [%str%]

   set str=!str:%f%=thin!

   echo str:f=thin = [%str%]

I hope you're convinced!

A:

Use CALL. Put the following in a batch script and run it:
set a=The fat cat
set b=fat
set c=thin

REM To replace "%b%" with "%c%" in "%a%", we can do:
call set a=%%a:%b%^=%c%%%
echo %a%
pause

As stated here, we use the fact that:

CALL internal_cmd
...
internal_cmd Run an internal command, first expanding any variables in the argument.

In our case internal_cmd is initially set a=%%a:%b%^=%c%%%.
After expansion internal_cmd becomes set a=%a:fat=thin%.
Thus, in our case running

call set a=%%a:%b%^=%c%%%

is equivalent to running:

set a=%a:fat=thin%.


Q:

Десереализация Json в REST запросе

Всем привет! У меня такая проблема
@RequestMapping(value = "/createrobot", method = RequestMethod.POST)
public Robot createRobot(
        @RequestParam(value="id", required = false, defaultValue = "-") String id,
        @RequestParam(value="name", required = false, defaultValue = "-") String name,
        @RequestParam(value="age", required = false, defaultValue = "-") String age,
        @RequestBody Robot robot){

    return new Robot(1, "Maks", "456");

}

выполняю запрос в POSTMAN http://localhost:8081/supercontroller/createrobot
передаю Json
{
    "id": 78,
    "name": "-",
    "age": "-"
}

возникает ошибка:
{
    "timestamp": "2018-06-18T11:57:02.825+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Type definition error: [simple type, class ru.asdf.Robot]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `ru.asdf.Robot` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)\n at [Source: (PushbackInputStream); line: 2, column: 5]",
    "path": "/supercontroller/createrobot"
}

Вижу что проблема в десериализации, как мне её решить?
имеется сущность Robot
public class Robot {

    Integer id;
    String name;
    String age;

    public Robot(int id, String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

Какие аннотации использовать?

A:

Проблема скрывалась в отсутсвии конструктора без параметров. После его добавления ошибка пропала.
public Robot() {
}


Q:

working with nested arrays hashes ruby

I'm having a hard time with nested hashes
 Restaurant = {:name=>"McDonalds",
 :location=>"NYC",
 :chefs=>
  [{:name=>"Sunny", :food=>"fries"},
   {:name=>"Brooklyn", :food=>"burgers"},
   {:name=>"Mac", :food=>"burgers"}],
 :waiters=>
  [{:name=>"Jess", :role=>"senior manager"},
   {:name=>"Sam", :role=>"manager"},
   {:name=>"Jack", :role=>"server"},
   {:name=>"Mary", :role=>"server"}]}

how would I delete the waiter hash with Jack as a value for example?
or return all waiter's names with the role of server?

A:

Restaurant[:waiters].reject!{|h| h[:name] == "Jack"}
Restaurant # => {
  :name=>"McDonalds", :location=>"NYC",
  :chefs=>[{:name=>"Sunny", :food=>"fries"}, {:name=>"Brooklyn", :food=>"burgers"}, {:name=>"Mac", :food=>"burgers"}],
  :waiters=>[{:name=>"Jess", :role=>"senior manager"}, {:name=>"Sam", :role=>"manager"}, {:name=>"Mary", :role=>"server"}]
}

Restaurant[:waiters].select{|h| h[:role] == "server"}
# => [{:name=>"Mary", :role=>"server"}]


Q:

Why is the standard deviation defined as sqrt of the variance and not as the sqrt of sum of squares over N?

Today I taught an introductory class of statistics and a student came up to me with a question, which I rephrase here as: "Why is the standard deviation defined as sqrt of variance and not as the sqrt of sum of squares over N?"
We define population variance: $\sigma^2=\frac{1}{N}\sum{(x_i-\mu)^2}$
And standard deviation: $\sigma=\sqrt{\sigma^2}=\frac{1}{\sqrt{N}}\sqrt{\sum{(x_i-\mu)^2}}$.
The interpretation we may give to $\sigma$ is that it gives the average deviation of units in the population from the population mean of $X$.
However, in the definition of the s.d. we divide the sqrt of the sum of squares through $\sqrt{N}$. The question the student raises is why we do not divide the sqrt of the sume of squares by $N$ instead. Thus we come to competing formula: $$\sigma_{new}=\frac{1}{N}\sqrt{\sum{(x_i-\mu)^2}}.$$ The student argued that this formula looks more like an "average" deviation from the mean than when dividing through $\sqrt{N}$ as in $\sigma$.
I thought this question is not stupid. I would like to give an answer to the student that goes further than saying that the s.d. is defined as sqrt of the variance which is the average squared deviaton. Put differently, why should the student use the correct formula and not follow her idea?
This question relates to an older thread and answers provided here. Answers there go in three directions:

$\sigma$ is the root-mean-squared (RMS) deviation, not the "typical"
deviation from the mean (i.e., $\sigma_{new}$). Thus, it is defined differently.
It has nice mathematical properties.
Furthermore, the sqrt would bring back "units" to their original scale. However, this would also be the case for $\sigma_{new}$, which divides by $N$ instead.

Both of points 1 and 2 are arguments in favour of the s.d. as RMS, but I do not see an argument against the use of $\sigma_{new}$. What would be the good arguments to convince introductory level students of the use of the average RMS distance $\sigma$ from the mean?

A:

There are at least three basic problems which can readily be explained to beginners:

The "new" SD is not even defined for infinite populations.  (One could declare it always to equal zero in such cases, but that would not make it any more useful.)

The new SD does not behave the way an average should do under random sampling.

Although the new SD can be used with all mathematical rigor to assess deviations from a mean (in samples and finite populations), its interpretation is unnecessarily complicated.

1. The applicability of the new SD is limited
Point (1) could be brought home, even to those not versed in integration, by pointing out that because the variance clearly is an arithmetic mean (of squared deviations), it has a useful extension to models of "infinite" populations for which the intuition of the existence of an arithmetic mean still holds.  Therefore its square root--the usual SD--is perfectly well defined in such cases, too, and just as useful in its role as a (nonlinear reexpression of) a variance.  However, the new SD divides that average by the arbitrarily large $\sqrt{N}$, rendering problematic its generalization beyond finite populations and finite samples: what should $1/\sqrt{N}$ be taken to equal in such cases?
2. The new SD is not an average
Any statistic worthy of the name "average" should have the property that it converges to the population value as the size of a random sample from the population increases.  Any fixed multiple of the SD would have this property, because the multiplier would apply both to computing the sample SD and the population SD. (Although not directly contradicting the argument offered by Alecos Papadopoulos, this observation suggests that argument is only tangential to the real issues.)  However, the "new" SD, being equal to $1/\sqrt{N}$ times the usual one, obviously converges to $0$ in all circumstances as the sample size $N$ grows large.  Therefore, although for any fixed sample size $N$ the new SD (suitably interpreted) is a perfectly adequate measure of variation around the mean, it cannot justifiably be considered a universal measure applicable, with the same interpretation, for all sample sizes, nor can it correctly be called an "average" in any useful sense.
3. The new SD is complicated to interpret and use
Consider taking samples of (say) size $N=4$.  The new SD in these cases is $1/\sqrt{N}=1/2$ times the usual SD.  It therefore enjoys comparable interpretations, such as an analog of the 68-95-99 rule (about 68% of the data should lie within two new SDs of the mean, 95% of them within four new SDs of the mean, etc.; and versions of classical inequalities such as Chebychev's will hold (no more than $1/k^2$ of the data can lie more than $2k$ new SDs away from their mean); and the Central Limit Theorem can be analogously restated in terms of the new SD (one divides by $\sqrt{N}$ times the new SD in order to standardize the variable). Thus, in this specific and clearly constrained sense, there is nothing wrong with the student's proposal. The difficulty, though, is that these statements all contain--quite explicitly--factors of $\sqrt{N}=2$.  Although there is no inherent mathematical problem with this, it certainly complicates the statements and interpretation of the most fundamental laws of statistics.

It is of note that Gauss and others originally parameterized the Gaussian distribution by $\sqrt{2}\sigma$, effectively using $\sqrt{2}$ times the SD to quantify the spread of a Normal random variable.  This historical use demonstrates the propriety and effectiveness of using other fixed multiples of the SD in its stead.

A:

Assume that your sample contains only two realizations. I guess an intuitive measure of dispersion would be the average absolute deviation (AAD)
$$AAD = \frac 12 (|x_1-\bar x| + |x_2-\bar x|) = ...= \frac {|x_1-x_2|}{2}$$
So we would want other measures of dispersion at the same level of units of measurement to be "close" to the above.
The sample variance is defined as
$$\sigma^2=\frac{1}{2}[(x_1-\bar x)^2 + (x_2-\bar x)^2] = \frac 12 \left[\left(\frac {x_1-x_2}{2}\right)^2 + \left(\frac {x_2-x_1}{2}\right)^2\right]$$
$$=\frac 12 \left[\frac {(x_1-x_2)^2}{4} + \frac {(x_1-x_2)^2}{4}\right]=\frac 12 \frac {(x_1-x_2)^2}{2}$$
$$=\frac 12\cdot  \frac {|x_1-x_2|^2}{2}$$
To return to the original units of measurement, if we did as the student wondered/suggested,we would obtain the measure, call it $q$
$$ q \equiv  \frac 12\cdot  \sqrt {\frac {|x_1-x_2|^2}{2}} = \frac 12 \frac {|x_1-x_2|}{\sqrt 2} = \frac 1{\sqrt 2} AAD < AAD$$
i.e. we would have "downplayed" the "intuitive" measure of dispersion, while if we have considered the standard deviation as defined,
$$SD \equiv \sqrt {\sigma^2} = \frac {|x_1-x_2|}{2} =AAD$$
Since we want to "stay as close as possible" to the intuitive measure, we should use $SD$.
ADDENDUM
Let's consider now a sample of size $n$ We have
$$n\cdot AAD = \sum_{i=1}^n |x_i-\bar x|$$
and
$$n \cdot \text{Var}(X) = \sum_{i=1}^n (x_i-\bar x)^2 = \sum_{i=1}^n |x_i-\bar x|^2$$
we can write the right-hand side of the variance expression as
$$\sum_{i=1}^n |x_i-\bar x|^2 = \left(\sum_{i=1}^n |x_i-\bar x|\right)^2 - \sum_{j\neq i} |x_i-\bar x||x_j-\bar x|$$
$$ = \left (n\cdot AAD\right)^2 - \sum_{j\neq i} |x_i-\bar x||x_j-\bar x|$$
Then the dispersion measure $q_n$ will be
$$q_n \equiv \frac 1n \left[n^2\cdot AAD^2 - \sum_{j\neq i} |x_i-\bar x||x_j-\bar x|\right]^{1/2}$$
$$= \left[AAD^2 - \frac 1{n^2} \sum_{j\neq i} |x_i-\bar x||x_j-\bar x|\right]^{1/2}$$
Now think informally: note that $\sum_{j\neq i} |x_i-\bar x||x_j-\bar x|$ contains $n^2-n$ terms, and so divided by $n^2$ will left us with "one term in the second power". But also "one term in the 2nd power" is what we have in $AAD^2$: this is a primitive way to "sense" why $q_n$ will tend to zero as $n$ grows large. On the other hand the Standard Deviation as defined would be
$$SD \equiv \frac 1{\sqrt n} \left[n^2\cdot AAD^2 -  \sum_{j\neq i} |x_i-\bar x||x_j-\bar x|\right]^{1/2}$$
$$= \left[n\cdot AAD^2 - \frac 1{n} \sum_{j\neq i} |x_i-\bar x||x_j-\bar x|\right]^{1/2}$$
Continuing are informal thinking, the first term gives us $n$ "terms in the 2nd power", while the second term gives us $n-1$ "terms in the second power" . So we will be left eventually with one such term, as $n$ grows large, and then we will take its square root.
This does not mean that the Standard Deviation as defined will equal the Average Absolute Deviation in general (it doesn't), but it does show that it is suitably defined so as to be "on a par" with it for any $n$, as well as for the case when $n\rightarrow \infty$.


Q:

Nulling Out Managed Resources on Dispose

Possible Duplicate:
Any sense to set obj = null(Nothing) in Dispose()?

I understand if this question is closed as a duplicate, but I'm having some trouble reconciling some posts on this topic.
First a little background.  I have a class Foo as follows
public class Foo : IDisposable
{
    private Dictionary<int, string> _reallyBigDictionary =
            new Dictionary<int, string>();

    public void Dispose()
    {
        _reallyBigDictionary = null;
    }
}

Instances of Foo are known to have a limited scope (i.e. I know we're not keeping it around forever).  Given it's instance's limited scope, I don't see how nulling out _reallyBigDictionary actually frees up memory sooner than the dispose.  The way I understand it, these objects won't ever get cleaned up until garbage collection is run.  At that time, references to the given instance of Foo will be null regardless, so I expect GC to reclaim that memory regardless.
These posts lead me to believe that there is no point in setting member variables to null:
Memory leak problems: dispose or not to dispose managed resources?
Is it better to destroy all objects or just let the garbage collector do the job?
This post makes me question otherwise:
Proper use of the IDisposable interface
Can anyone clarify this point for me?  Is the IDisposable implementation really necessary here? Because I just can't convince myself it is.

A:

You don't need IDisposable; here's why. In summary, you need to follow Rule 1: Don't implement IDisposable unless you need to.
There are only two situations when IDisposable does need to be implemented:

The class owns unmanaged resources.
The class owns managed (IDisposable) resources.

Since Dictionary<int, string> is not IDisposable, your class shouldn't be either.


Q:

How to delete part of a character value column of a data frame in R

  [1] NA                         NA
  [3] NA                         NA
  [5] "kilo130.9"            "kilo5075.69"
  [7] "kilo465"              "kilo34.8"
  [9] "kilo607.195"          "kilo1362.7"

Above is the column of a dataframe that I have copy pasted from R
I ran the code below to delete the word kilo from the column but it does not work. I don't get an error but it does not delete the word kilo. I used the code below
stopwords = readLines('stopwords.txt') #I put the word kilo in this txt file
x  = df$Dist
x  =  removeWords(x,stopwords)
df$newdist<-x

What could be the reson?

A:

removeWords() is only going to remove words that exactly match "kilo" (with no other characters):
x <- c("kilo", "kilo2", "pound")
tm::removeWords(x, "kilo")
#> [1] ""      "kilo2" "pound"

Here's another option:
library("stringr")
x <- c(NA, NA, NA, NA, "kilo130.9", "kilo5075.69", "kilo465", "kilo34.8", "kilo607.195", "kilo1362.7")
str_replace(x, "kilo", "")
#>  [1] NA        NA        NA        NA        "130.9"   "5075.69" "465"
#>  [8] "34.8"    "607.195" "1362.7"


Q:

execute bashscript in background?

I have a bash script that runs a backup command. The script runs great. However because its backups up everything, it takes a while for the script to execute successfully.
Can you execute a script from terminal and have it execute in a background of the terminal?
Right now I have to open up a new terminal window because the script takes a couple hours because I cannot enter a command in the same terminal that I executed the bash script until the bash script is finished.
I would think that this is possible seeing if I ran the bashscript on system startup, the script would run in the background.

A:

If you close the terminal it will closes the process of script execution. If you want to run the script in the background and don't want the current window to be the parent of the process execute this:
./bash_script &

And the important part is to run next
exit

This will reparent the process to the OS and the process will run really in the background. So you can quit terminal.


Q:

New member with performance question

Just loaded Ubuntu on an older PC and it seems to be running very slow and “choppy”.
I am running ubuntu 14.04 LTS on my 2003 Compaq Presario S4000NX.

RAM = 993MB
Processor = Intel Celeron 2.40GHz
Graphics = on board Intel 845Gx86/MMX/SSE2
OS = 32bit
Hard Disk = 156GB

Am I under powered for this version? Would I be better off trying to install a graphics card or using a different version of Linix? I appreciate any suggestions.

A:

Try LXDE I installed LXDE on an older laptop with similar specs. as yours, and it flys. Ubuntu was my 1st choice, but the machine, esp. the graphics wasn't man enough...


Q:

$\lim_{x\to\infty} \frac{5\cdot5^x+3^x-4^x}{5^x +2^x+27\cdot9^x}$

How can I solve this limit.  (Here $x$ belongs to natural numbers $\Bbb{N}$.)
$$
\lim_{x\to\infty} \dfrac{5\cdot5^x+3^x-4^x}{5^x +2^x+27\cdot9^x}$$
My try:  I tried using L'Hospital, expansions of all terms using Taylor's series, and did work out.  I was just thinking if there is any simpler method?

A:

Dividing by $9^x$ will give you the limit value


Q:

Call jQuery from ColdFusion

Is it possible to call a jQuery function from within a ColdFusion switch statement?  If so, how?

A:

You do know that you are mixing client and server side code?  That said it is really not an issue to do:
<script language="javascript">
    <cfswitch expression="#n#">
      <cfcase value="test1">
        $.something1()
      </cfcase>

      <cfcase value="test2">
        $.something2()
      </cfcase>
    </cfswitch>
</script>

A:

No.  ColdFusion runs on the server.  jQuery runs on the client (the browser).  You can conditionally output (depending on which case you hit) JavaScript code that will call the jQuery function.


Q:

12.04 Unity capable, but still stuck with no loader/dash/

I ran
/usr/lib/nux/unity_support_test -p

And it seems I pass all tests, I'm using the latest proprietary drivers, Unity 2D/Gnome works just fine, just not Unity 3D
I already tried Unity doesn't load, no Launcher, no Dash appears logged in using 2D, activate the plugin but still no dice.
Is there a dump I can provide to get help?

A:

If you've upgraded, or are using the same home partition/directory with old config files, it's possible for some old compiz configuration to break the Unity panel and launcher.  Open a terminal window and try:
unity --reset
Chris


Q:

Sort list by string field of class

I have a list of objects, each with time data, id numbers, and a string descriptor in the type field. I wish to pull all the values to the front of the list with a certain string type, while keeping the order of those list elements the same, and the order of the rest of the list elements the same, just attached to the back of those with my desired string.
I've tried, after looking for similar SE questions,
list.OrderBy(x => x.type.Equals("Auto"));

which has no effect, though all other examples I could find sorted by number rather than by a string.
List Objects class definition:
public class WorkLoad
{
    public long id;
    public DateTime timestamp;
    ...
    public String type;
}

...create various workload objects...
schedule.Add(taskX)

schedule.OrderBy(x => x.type.Equals("Manual"));
//has no effect currently

A:

If you already have a sorted list I think the fastest way to resort it by "having a type of auto or not" without losing the original order (and without having to resort all over again) could be this:
var result = list.Where(x => x.type.Equals("Auto"))
                 .Concat(list.Where(x => !x.type.Equals("Auto")))
                 .ToList();

Update:
You commented that "everyting else should be sorted by time", so you can simply do this:
var result = list.OrderByDescending(x => x.type.Equals("Auto"))
                 .ThenBy(x => x.Time).ToList();


Q:

Single Instance Application in C++/CLI using Mutex

I am developing a tray icon based application in C++ CLI. I am using Mutex to ensure single instance of my application running at a time. But each time a new instance starts, the current instance's window should go active.
I am sending a message to the window using PostMessage(Pinvoke). But after 3 or 4 successive run, my application crashes.
Any ideas why that happen. please help!!
The code I have written in the main() function is,
Mutex ^mutex = gcnew Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}");
if (mutex->WaitOne(TimeSpan::Zero, true))
{
    // New Instance. Proceed......................
}
else// An instance is already running. Activate it and return
{
    // send our Win32 message to make the currently running instance
    // jump on top of all the other windows
    try
    {

        HWND hWindow = FindWindow( nullptr, "MyWindow" );
        if(hWindow)
            PostMessage(hWindow, WM_ACTIVATE_APP, nullptr,nullptr);
    }
    catch(Exception^ Ex)
    {
    }
    return -1;
}

Thanks & Regards,
Rohini

A:

Try this instead of PostMessage():
ShowWindowAsync(hWindow, 1); // SW_SHOWNORMAL
SetForegroundWindow(hWindow);


Q:

What caused the mass blindness in The Day of the Triffids?

In John Wyndham's classic apocalyptic novel The Day of the Triffids, events are put into motion by a double catastrophe: the mass blindness of nearly everyone on Earth, apparently caused by a meteor shower, coincides with the appearance of carnivorous plants which can kill people and which proceed, in the near absence of sighted people, to take over much of the world.
The triffids are perhaps the best known aspect of this story in popular culture, and their origins and nature are covered in detail in the novel, the main narrator character being something of an expert on them. They are a massive danger but at least well understood. But the mass blindness, although it's the main catastrophe that puts everything into motion, is more of a mystery. Why would a meteor shower make everyone blind? I recall one conversation between Bill and Jo where they speculate about what might really have caused it, but that's all.
What is the cause of the blindness catastrophe? Or rather, what evidence do we have to support the different options here? Was it caused by extraterrestrial material in the meteors, or by human-manufactured weapons, either a deliberate attack or something accidentally triggered by the meteor shower? What evidence can we draw on either from the novel itself, from other Wyndham novels and his general style, or from other things he wrote about this novel?

A:

Some "shooting stars" have made everyone blind, as mentioned in the first chapters:

You'll find it in the records that on Tuesday, May 7, the Earth's
  orbit passed through a cloud of comet debris.
"D'you know what? I'm blind. Thash what I am- blind's a bat.
  Everybody's blind's a bat. 'Cept you. Why aren't you blind's a bat?"
  "I don't know," I told him. "'S that bloody comet. Thash what done it.
  Green shootin' shtarsh-an' now everyone's blind's a hat. D'ju shee
  green shootin' shtarsh?" "No," I admitted. "There you are. Proves it.
  You didn't see 'em: you aren't blind. Everyone else saw 'em"-he waved
  an expressive arm -"all's blind's bats. Bloody comets, I say." I
  poured myself a third brandy, wondering whether there might not be
  something in what he was saying. "Everyone blind?" I repeated. "Thash
  it. All of 'em. Prob'ly everyone in th'world-'cept you,' he added as
  an afterthought.

So what's wrong with those comets, or meteors, or shooting stars? There are some hints that they are human-made:

Sustained research in rocketry had at last succeeded in attaining one
  of its objectives. It had sent up a missile which stayed up. It was,
  in fact, possible to fire a rocket far enough up for it to fall into
  an orbit. Once there, it would continue to circle like a tiny moon,
  quite inactive and innocuous until the pressure on a button should
  give it the impulse to drop back, with devastating effect. Great as
  was the public concern which followed the triumphant announcement of
  the first nation to establish a satellite weapon satisfactorily, a
  still greater concern was felt over the failure of others to make any
  announcement at all, even when they were known to have had similar
  successes. It was by no means pleasant to realize that there was an
  unknown number of menaces up there over your head, quietly circling
  and circling until someone should arrange for them to drop-and that
  there was nothing to be done about them. Still, life has to go on-and
  novelty is a wonderfully short-lived thing. One became used to the
  idea perforce. From time to time there would be a panicky flare-up of
  expostulation when reports circulated that as well as satellites with
  atomic heads there were others with such things as crop diseases,
  cattle diseases, radioactive dusts, viruses, and infections not only
  of familiar kinds but brand-new sorts recently thought up in
  laboratories, all floating around up there.

Later on, the satellites are shown to be used for biological warfare:

A virulent organism, unstable enough to become harmless in the course
  of a few days (and who is to say that such could not be bred?), could
  be considered to have strategic uses if dropped in suitable spots.

And that's all that I could find in this (luckily not too long) book about what happens in space before the flash that blinds everyone.


Q:

Reverse models relationship in mongoose?

I have two schemas (Portfolio and Projects that relate to portfolios):
portfolioSchema = new Schema({
    name: {type: String, required: true, unique: true},
    isActive: {type: Boolean, default: true}
});

projectSchema = new Schema({
    name: {type: String, required: true, unique: true},
    isActive: {type: Boolean, required: true, default: true},
    portfolio: {type: mongoose.Schema.Types.ObjectId, ref: 'portfolioSchema', required: true},
    isCodeBaseFullyOwned: {type: Boolean, required: true, default: false}
});

Is there a way to select all portfolios and 'populate' their relevant projects? I can group projects by portfolio but then if there are no projects in a portfolio I would have to figure a way to additionally pull this information, too.

A:

There are 2 ways you could do this.
One would be adding an array of projectIds on the portfolio which you could then populate but could become messy if you are not careful with cleaning up/managing references on updates.
This can be done by updating the portfolioSchema to
portfolioSchema = new Schema({
    name: {type: String, required: true, unique: true},
    isActive: {type: Boolean, default: true},
    projects: [{type: mongoose.Schema.Types.ObjectId, ref: 'projectSchema', required: true}]
});

The other option would require grouping projects by portfolio as you have said and then collecting all portfolio ids that return, and running a second query to get portfolios with
{_id: {$nin: <array of already returned portfolio ids>}}

Both options have pros and cons but currently these are the only two options that I can think of.


Q:

Integrate Flare3D into a Flex application

I'm building an application with the Flex framework and the 3D graphics library Flare3D.
I want to be able to embed my 3D scene into an MXML application and still have the mouse events dispatched to the 3D scene.
Here is my code:
- The MXML app:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               xmlns:views="views.*"
               minWidth="955" minHeight="600"
               backgroundAlpha="0">

<s:HGroup width="100%" height="100%">

    <s:Panel width="250" height="100%">
    </s:Panel>
    <views:MyView
        id="myView"
        width="100%" height="100%" />

</s:HGroup>
</s:Application>

The UIComponent responsible of the 3D rendering (just a cube).
package views
{

import flare.basic.Scene3D;
import flare.basic.Viewer3D;
import flare.core.Camera3D;
import flare.primitives.Cube;

import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;

import mx.controls.Alert;
import mx.core.UIComponent;

public class MyView extends UIComponent
{

    private var scene:Scene3D;
    private var stage3D:Stage3D;

    private var cube:Cube;

    public function MyView()
    {
        super();
        this.addEventListener(Event.ADDED_TO_STAGE, init);
    }

    public function init(event:Event):void
    {
        stage.scaleMode = StageScaleMode.NO_SCALE;
        stage.align = StageAlign.TOP_LEFT;
        //stage.focus = null;
        //stage.getChildAt(0).visible = false;

        scene = new Viewer3D(stage);
        scene.setViewport(250, 0);
        scene.addEventListener(Scene3D.PROGRESS_EVENT, progressEvent);
        scene.addEventListener(Scene3D.COMPLETE_EVENT, completeEvent);

        scene.camera = new Camera3D();
        scene.camera.setPosition(150, 150, -300);
        scene.camera.lookAt(0, 0, 0);

        cube = new Cube("cube");
        scene.addChild(cube);
    }

    protected function progressEvent(e:Event):void {}
    protected function completeEvent(e:Event):void {}

}
}

The problem is that the 3D rendering is done by default in a "layer" that is behind the 2D layer (where we can put MXML components).
By default, if we mix 3D and 2D elements, we can't see 3D elements.
So I added backgroundAlpha="0". This solved the problem of showing the 3D view.
But now I have another problem, I can't move the cube (which is the default behaviour) when I click on the scene and move the mouse.
I understand that this is because the 3D view is behind the 2D view.
Is it possible to give the 3D view the focus for mouse events (when it's needed) ?
Or is there a different way of doing what I want ?
The only hack I figured out is to uncomment this //stage.getChildAt(0).visible = false; which make the 2D view invisible. But I want to mix 2D elements and 3D view, so it's not a solution.
Thanks for any help.

A:

I had the exact same issue working with Alternativa3D and Flex 4.6. What I tried was to add the UIComponent in the application tag instead of the Panel tag and both my Flex and Stage3D mouse events worked.
So the code looks like this:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               xmlns:views="views.*"
               minWidth="955" minHeight="600"
               backgroundAlpha="0">

    <views:MyView
        id="myView"
        width="100%" height="100%" />

<s:HGroup width="100%" height="100%">

    <s:Panel width="250" height="100%">
    </s:Panel>

</s:HGroup>
</s:Application>


Q:

How can I separate css files from public and admin area components?

I am new to Angular and I need to separate bootstrap (v3 and v4) files for Public area and Admin dashboard.
I am using bootstrap 4 based theme in public area and bootstrap 3 based theme in admin dashboard (AdminLTE).
I created this app using angular CLI tool.
Now all css file placed in angular-cli.js
and two folders called admin (all admin dashboard components) and site (all public area components) in app folder.
How can I separate these asset files for both admin area components?
Is it possible?

A:

Use Shadow DOM encapsulation for your components
doc


Q:

Was Joseph Smith (founder of Mormonism) a convicted con-man?

I frequently hear claims that Joseph Smith was a convicted con artist. While looking into this, the claim is usually in reference to being driven from New York for taking money to find some treasures supposedly hidden in some native american trove, which he then never found.
When this claim is brought up to mormons, they categorically dismiss that Joseph Smith was a con-man, etc.
Does any record of this exist? Was he convicted? Where's the evidence?

A:

This is an urban legend. No reputable source claims Joseph Smith was ever convicted of fraud.
Edit: I have removed my elaboration as it appears that this issue has now become controversial.
https://byustudies.byu.edu/showtitle.aspx?title=5004 :

Peter Bridgeman, a nephew of the wife of Josiah Stowell, presented a written complaint against Joseph Smith at South Bainbridge, New York, which led to his arrest and trial as a “disorderly person.”

http://en.fairmormon.org/Joseph_Smith/Legal_issues/Trials/1826_glasslooking_trial :

It was likely that the court hearing was initiated not so much from a concern about Joseph being a money digger, as concern that Joseph was having an influence on Josiah Stowell. Josiah Stowell was one of the first believers in Joseph Smith. His nephew was probably very concerned about that and was anxious to disrupt their relationship if possible. He did not succeed. The court hearing failed in its purpose, and was only resurrected decades later to accuse Joseph Smith of different crimes to a different people and culture.

http://www.omninerd.com/articles/The_1826_Trial_of_Joseph_Smith_Jr :

Fawn Brodie’s biography of JS provides perhaps the most famous allegation concerning the 1826 event. She claimed, "On the basis of the testimony presented, including Joseph’s own admission of indulging in magic arts and organizing hunts for buried gold, the court ruled him guilty of disturbing the peace."4

http://www.lightplanet.com/response/1826Trial/1826Trial_Hill.html :


Q:

Update a row(entity) in a table only if a change detected(automatically)

Sorry for my bad english :(
I'm using the CAKEPHP 3 framework and i want to update a row(entity) in a table only if a change detected(automatically).
Eg.:
$id = 1;
// debug($this->request->data)
$this->request->data = ['id' => 1, 'name' => "My Name", 'content' => "My Content"];
// Inside the ArticlesController
$article = $this->Articles->get($id);
// debug($article)
object(Cake\ORM\Entity) {
    'id' => (int) 1,
    'name' => "My Name",
    'content' => "My Content",
    '[new]' => false,
    '[accessible]' => [
        '*' => true
    ],
    '[dirty]' => [],
    '[original]' => [],
    '[virtual]' => [],
    '[errors]' => [],
    '[repository]' => 'Articles'
}

There is no difference between the request data and the original data so i have to reject the update query and return a warning to the user "No changes detected !"
What i have to do ?
Thanks

A:

Each entity has a field 'dirty' which shows if the entity has been updated.
You could use something like :
if($article->dirty()) {
    // send a flash message
}

Check the book here : http://book.cakephp.org/3.0/en/orm/entities.html#checking-if-an-entity-has-been-modified


Q:

PHP While Loop Slowdown over time

I have seemingly harmless while loop that goes through the result-set of a mysql query and compares the id returned from mysql, to one in a very large multidimensional array:
//mysqli query here
while($row = fetch_assoc())
{
    if(!in_array($row['id'], $multiDArray['dimensionOne']))
    {
        //do something
    }
}

When the script first executes, it is running through the results at about 2-5k per second. Sometimes more, rarely less. The result set brings back 7million rows, and the script peaks at 2.8GB of memory.
In terms of big data, this is not a lot.
The problem is, around the 600k mark, the loop starts to slow down, and by 800k, it is processing a few records a second.
In terms of server load and memory use, there are no issues.
This is behaviour I have noticed before in other scripts dealing with large data sets.
Is array seek time progressively slower as the internal pointer moves deeper?

A:

That really depends on what happens inside the loop. I know you are convinced it's not a memory issue but it looks like one. Program usually get very slow when system tries to get extra RAM by using SWAP. Using hard drive is obviously very slow and that's what you might be experiencing. It's very easy to benchmark it.
In one terminal run
vmstat 3 100

Run you scrip and observe vmstat. Look into IO and SWAP. If that is really not the case then profile execution with XDEBUG. It might be tricky because you do many iterations and this will also cause major IO.