How to show Sliding Menu Bar in every activity?

Question: Im making a android app with a sliding menu, but I want it to be avaliable for all activities.
Here is a example of my problem:
I have 7 main options (Home, Translator, Tour, Settings etc) named fragment1 to fragment7,
but I also have a horizontalscrollview inside Tour with other activities,
I want these 'other activities' to show the Sliding Menu aswell..
Heres my codes

AndroidManifest.xml

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gnirt69.slidingmenuexample">

    <application android:allowBackup="true" android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher" android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Hotels" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Hotspots" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Leisure" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Nightlife" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>

        <activity android:name=".touring.Resteraunts" android:label="Tour Guide with Translator">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.TAB" />
            </intent-filter>
        </activity>

    </application>

</manifest>

ItemSlideMenu.java

    package com.gnirt69.slidingmenuexample.model;

public class ItemSlideMenu {

    private int imgId;
    private String title;

    public ItemSlideMenu(int imgId, String title) {
        this.imgId = imgId;
        this.title = title;
    }

    public int getImgId() {
        return imgId;
    }

    public void setImgId(int imgId) {
        this.imgId = imgId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

MainActivity.java

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.gnirt69.slidingmenuexample.adapter.SlidingMenuAdapter;
import com.gnirt69.slidingmenuexample.fragment.Fragment1;
import com.gnirt69.slidingmenuexample.fragment.Fragment2;
import com.gnirt69.slidingmenuexample.fragment.Fragment3;
import com.gnirt69.slidingmenuexample.fragment.Fragment4;
import com.gnirt69.slidingmenuexample.fragment.Fragment5;
import com.gnirt69.slidingmenuexample.fragment.Fragment6;
import com.gnirt69.slidingmenuexample.fragment.Fragment7;
import com.gnirt69.slidingmenuexample.touring.Hotels;
import com.gnirt69.slidingmenuexample.model.ItemSlideMenu;
import com.gnirt69.slidingmenuexample.touring.Hotspots;
import com.gnirt69.slidingmenuexample.touring.Leisure;
import com.gnirt69.slidingmenuexample.touring.Nightlife;
import com.gnirt69.slidingmenuexample.touring.Resteraunts;

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

/**
 * Created by User on 10/18/2015.
 */
public class MainActivity extends ActionBarActivity {

    private List<ItemSlideMenu> listSliding;
    private SlidingMenuAdapter adapter;
    private ListView listViewSliding;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;

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

        //Init component
        listViewSliding = (ListView) findViewById(R.id.lv_sliding_menu);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        listSliding = new ArrayList<>();
        //Add item for sliding list
        listSliding.add(new ItemSlideMenu(R.drawable.homeeee, "Home"));
        listSliding.add(new ItemSlideMenu(R.drawable.tourrrr, "Tour Guide"));
        listSliding.add(new ItemSlideMenu(R.drawable.trrravel, "Translator"));
        listSliding.add(new ItemSlideMenu(R.drawable.settings_black, "Settings"));
        listSliding.add(new ItemSlideMenu(R.mipmap.ic_launcher, "Help"));
        listSliding.add(new ItemSlideMenu(R.mipmap.ic_launcher, "About"));
        listSliding.add(new ItemSlideMenu(R.mipmap.ic_launcher, "Exit App"));
        adapter = new SlidingMenuAdapter(this, listSliding);
        listViewSliding.setAdapter(adapter);

        //Display icon to open/ close sliding list
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //Set title
        setTitle(listSliding.get(0).getTitle());
        //item selected
        listViewSliding.setItemChecked(0, true);
        //Close menu
        drawerLayout.closeDrawer(listViewSliding);

        //Display fragment 1 when start
        replaceFragment(0);
        //Hanlde on item click

        listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Set title
                setTitle(listSliding.get(position).getTitle());
                //item selected
                listViewSliding.setItemChecked(position, true);
                //Replace fragment
                replaceFragment(position);
                //Close menu
                drawerLayout.closeDrawer(listViewSliding);
            }
        });

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed){

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                invalidateOptionsMenu();
            }
        };

        drawerLayout.setDrawerListener(actionBarDrawerToggle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

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

    //Create method replace fragment

    private void replaceFragment(int pos) {
        Fragment fragment = null;
        switch (pos) {
            case 0:
                fragment = new Fragment1();
                break;
            case 1:
                fragment = new Fragment2();
                break;
            case 2:
                fragment = new Fragment3();
                break;
            case 3:
                fragment = new Fragment4();
                break;
            case 4:
                fragment = new Fragment5();
                break;
            case 5:
                fragment = new Fragment6();
                break;
            case 6:
                fragment = new Fragment7();
                break;

            default:
                fragment = new Fragment1();
                break;
        }

        if(null!=fragment) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.main_content, fragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }

    }

    public void sendHotels(View view) {
        Intent startNewActivity = new Intent(this, Hotels.class);
        startActivity(startNewActivity);
    }
    public void sendHotspots(View view) {
        Intent startNewActivity = new Intent(this, Hotspots.class);
        startActivity(startNewActivity);
    }
    public void sendLeisure(View view) {
        Intent startNewActivity = new Intent(this, Leisure.class);
        startActivity(startNewActivity);
    }
    public void sendNightlife(View view) {
        Intent startNewActivity = new Intent(this, Nightlife.class);
        startActivity(startNewActivity);

    }
    public void sendResteraunt(View view) {
        Intent startNewActivity = new Intent(this, Resteraunts.class);
        startActivity(startNewActivity);
    }

}

> main_activity.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/main_content"></RelativeLayout>

    <ListView
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:id="@+id/lv_sliding_menu"
        android:background="#FFFFFF"
        android:choiceMode="singleChoice"
        android:layout_gravity="start"></ListView>
</android.support.v4.widget.DrawerLayout>

> Fragment1.xml

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

> fragment1.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home"
        android:textSize="30dp"
        android:layout_gravity="center"/>
</LinearLayout>

and here is my problem, I want the slidingmenu to show here also (a activity inside fragment1)

Hotels.java

       package com.gnirt69.slidingmenuexample.touring;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;

import com.gnirt69.slidingmenuexample.R;

/**
 * Created by User on 12/14/2015.
 */
public class Hotels extends FragmentActivity {

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

    public void sendHotels(View view) {
        Intent startNewActivity = new Intent(this, Hotels.class);
        startActivity(startNewActivity);
    }
    public void sendHotspots(View view) {
        Intent startNewActivity = new Intent(this, Hotspots.class);
        startActivity(startNewActivity);
    }
    public void sendLeisure(View view) {
        Intent startNewActivity = new Intent(this, Leisure.class);
        startActivity(startNewActivity);
    }
    public void sendNightlife(View view) {
        Intent startNewActivity = new Intent(this, Nightlife.class);
        startActivity(startNewActivity);

    }
    public void sendResteraunt(View view) {
        Intent startNewActivity = new Intent(this, Resteraunts.class);
        startActivity(startNewActivity);
    }

}

tourhotels.xml

     <LinearLayout
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android" >
        <HorizontalScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/hotelss"
                    android:id="@+id/Hotelio"
                    android:onClick="sendHotels"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/resteraunts"
                    android:onClick="sendResteraunt"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/hotspotss"
                    android:onClick="sendHotspots"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/leisure"
                    android:onClick="sendLeisure"/>
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/nightlife"
                    android:onClick="sendNightlife"/>

            </LinearLayout>
        </HorizontalScrollView>
    </LinearLayout>

Comment: you added  sliding menu in one activity?
Comment: yes, in MainActivity.java , i want the sliding menu to be in Hotels.java and any other activities i add, but i dont know how to implement it into them
Comment: Why don't you use Fragments instead of Activity's ?
Comment: I am using fragments for the sliding menu, but inside a fragment i have other activities shown in tourhotels.xml
here are some pictures to try and help u get what im saying
http://tmasstrey.imgur.com/all/
so if i click on Hotels or Resteraunt etc to next activity, the sliding menu will still be implemented in that activity
Answer: Solved! for any others who wanted to add a TabHost into a Fragment this is how i did it..
Dont forget to import all your fragments here included in the Navigation Drawer

MainActivity.java

DrawerLayout drawerLayout;
RelativeLayout drawerPane;
ListView lvNav;

List<NavItem> listNavItems;
List<Fragment> listFragments;

ActionBarDrawerToggle actionBarDrawerToggle;

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

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerPane = (RelativeLayout) findViewById(R.id.drawer_pane);
    lvNav = (ListView) findViewById(R.id.nav_list);

    listNavItems = new ArrayList<NavItem>();
    listNavItems.add(new NavItem("Home", "MyHome page",
            R.drawable.ic_action_home));
    listNavItems.add(new NavItem("Translator", "English Cebuano",
            R.drawable.ic_action_home));
    listNavItems.add(new NavItem("Settings", "Change something",
            R.drawable.ic_action_settings));
    listNavItems.add(new NavItem("About", "Author's information",
            R.drawable.ic_action_about));

    NavListAdapter navListAdapter = new NavListAdapter(
            getApplicationContext(), R.layout.item_nav_list, listNavItems);

    lvNav.setAdapter(navListAdapter);

    listFragments = new ArrayList<Fragment>();
    listFragments.add(new MyHome());
    listFragments.add(new MyTrans());
    listFragments.add(new MySettings());
    listFragments.add(new MyAbout());

    // load first fragment as default:
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.main_content, listFragments.get(0)).commit();

    setTitle(listNavItems.get(0).getTitle());
    lvNav.setItemChecked(0, true);
    drawerLayout.closeDrawer(drawerPane);

    // set listener for navigation items:
    lvNav.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            // replace the fragment with the selection correspondingly:
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager
                    .beginTransaction()
                    .replace(R.id.main_content, listFragments.get(position))
                    .commit();

            setTitle(listNavItems.get(position).getTitle());
            lvNav.setItemChecked(position, true);
            drawerLayout.closeDrawer(drawerPane);

        }
    });

    // create listener for drawer layout
    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
            R.string.drawer_opened, R.string.drawer_closed) {

        @Override
        public void onDrawerOpened(View drawerView) {
            // TODO Auto-generated method stub
            invalidateOptionsMenu();
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            // TODO Auto-generated method stub
            invalidateOptionsMenu();
            super.onDrawerClosed(drawerView);
        }

    };

    drawerLayout.setDrawerListener(actionBarDrawerToggle);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the MyHome/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    if (actionBarDrawerToggle.onOptionsItemSelected(item))
        return true;

    return super.onOptionsItemSelected(item);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onPostCreate(savedInstanceState);
    actionBarDrawerToggle.syncState();
}

Next is where i went wrong, import TabHost directly into the fragment.java class, aswell as the onpagelistener (extend Fragment implements OnTabChangeListener)

MyTrans.java

    OnPageChangeListener {

private TabHost tabHost;
private ViewPager viewPager;
private MyFragmentPagerAdapter myViewPagerAdapter;
int i = 0;
View v;

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

    v = inflater.inflate(R.layout.tabs_viewpager_layout, container, false);

    i++;

    // init tabhost
    this.initializeTabHost(savedInstanceState);

    // init ViewPager
    this.initializeViewPager();

    return v;
}

// fake content for tabhost
class FakeContent implements TabContentFactory {
    private final Context mContext;

    public FakeContent(Context context) {
        mContext = context;
    }

    @Override
    public View createTabContent(String tag) {
        View v = new View(mContext);
        v.setMinimumHeight(0);
        v.setMinimumWidth(0);
        return v;
    }
}

private void initializeViewPager() {
    List<Fragment> fragments = new Vector<Fragment>();

    fragments.add(new Tab1Fragment());
    fragments.add(new Tab2Fragment());
    fragments.add(new Tab3Fragment());

    this.myViewPagerAdapter = new MyFragmentPagerAdapter(
            getChildFragmentManager(), fragments);
    this.viewPager = (ViewPager) v.findViewById(R.id.viewPager);
    this.viewPager.setAdapter(this.myViewPagerAdapter);
    this.viewPager.setOnPageChangeListener(this);

}

private void initializeTabHost(Bundle args) {

    tabHost = (TabHost) v.findViewById(android.R.id.tabhost);
    tabHost.setup();

    for (int i = 1; i <= 3; i++) {

        TabHost.TabSpec tabSpec;
        tabSpec = tabHost.newTabSpec("Tab " + i);
        tabSpec.setIndicator("Tab " + i);
        tabSpec.setContent(new FakeContent(getActivity()));
        tabHost.addTab(tabSpec);
    }
    tabHost.setOnTabChangedListener(this);
}

@Override
public void onTabChanged(String tabId) {
    int pos = this.tabHost.getCurrentTab();
    this.viewPager.setCurrentItem(pos);

    HorizontalScrollView hScrollView = (HorizontalScrollView) v
            .findViewById(R.id.hScrollView);
    View tabView = tabHost.getCurrentTabView();
    int scrollPos = tabView.getLeft()
            - (hScrollView.getWidth() - tabView.getWidth()) / 2;
    hScrollView.smoothScrollTo(scrollPos, 0);

}

@Override
public void onPageScrollStateChanged(int arg0) {
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}

@Override
public void onPageSelected(int position) {
    this.tabHost.setCurrentTab(position);
}

Next, create classes for your Tabs depending howmany you need, using inflater
@Override
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.tab1fragment, container, false);

    return v;
}

Then you have to make a layout.xml file to implement scrollview, size etc.

tabs_viewpager_layout.xml

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

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <HorizontalScrollView
                android:id="@+id/hScrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fillViewport="true"
                android:scrollbars="none" >

                <TabWidget
                    android:id="@android:id/tabs"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" >
                </TabWidget>
            </HorizontalScrollView>

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <android.support.v4.view.ViewPager
                    android:id="@+id/viewPager"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
            </FrameLayout>
        </LinearLayout>
    </TabHost>

</LinearLayout>

Next, make a .xml for each of your tabs

tab1fragment.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="Fragment 1" />

finally, dont forget to make a .xml file for each of your navigation drawers (ofcourse..)

fragment_tour.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tour"
        android:textColor="#000"
        android:textSize="18sp"
        android:textStyle="bold" />

</LinearLayout>

So basically, make the tabhost in the fragment u want it in <,<
sounds so simple now..
happy new year everyone .


Pyqt Highlight table row

Question: How to highlight a row in pyqt table widget. I dont know the exact word for this but i want to manually higlight the row as it happens clicking over the row.
Comment: Do you mean you want to highlight the row as your *mouse hovers over*?
Answer: In PyQt, to select and highlight a row of a QTableWidget, you need to know the row index.
Using:
tableWidget.selectRow(rowID)

should achieve this for you. However, if you mean to highlight a row on mouseover/hover, you will need to catch a signal ( I believe it is itemActivated ) and manipulate the styling of the QTableView item.
Answer: Your model (a QAbstractTableModel derived) class should return a proper value for Qt::BackgroundColorRole, Qt::ForegroundRole, etc. roles in the method
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const = 0

based on the actual content of the model row you want to highlight.

Pyqt Highlight table row


Why does the Augmented Dickey fuller test not use the F-test for checking stationarity

Question: As I understand the F-test is much better suited for analyzing linear regression models, so why does the ADF test not use the F-test rather using the T-test for hypothesis testing.
Answer: The T-test is actually a special case of the F-test.  If you examine the tables (or computer return for F and T) and compare the F distribution with one numerator degree of freedom to the T distribution (2-sided) with d.f. equal to the denominator d.f. of the F, you will see that the F values are the squares of the T values (or the p-values are the same when comparing T-squared to F).
So for the two-tailed case with 1 d.f. (1 coefficient, comparing 2 groups, ...) they are the same, the T-test has the advantage of being able to do a one-tailed comparison where the standard F is always testing any difference (though there are ways to do it directionally, but that takes more work than using the T).
Answer: In ADF test, neither T-test nor the F-test is used. T-statistic is calculated but unlike in normal linear models with standard assumptions it doesn't follow the t-distribution. Same goes for the F-statistic.
Critical values for these statistics are taken from DF table.


Using a module controller to create a page that is more than just a div from the twig template?

Question: I am using a custom module to create a new page on my Drupal 8 site.
My routing.yml file is configured like this:
mymodule.print:
  path: '/print-mymodule'
  defaults:
    _controller: \Drupal\mymodule\Controller\MymodulePrintController::content
  requirements:
    _permission: 'view mymodule entity'
  options:
    _auth: ['basic_auth']

MymodulePrintController::content is as follows:
public function content() {
    return array(
        '#type' => 'page',
        '#theme' => 'mytheme'
    );
}

mytheme is used everywhere else on my site.
In mytheme.theme, I also have a mytheme_preprocess() function which is adding some blocks to the page. I am guessing the theme is being detected properly because this function is executing just fine. The template I am using is named according to twig's suggestions and is loading fine.
The problem is that the content() function is not really outputting a "page". Using Postman, I see that the entire contents of the response is just a div, there is no  tag, no , no , nothing else except what is defined in the one twig file and mytheme_preprocess. I need this page to be using this theme's css styles like the rest of my pages are.
How can I accomplish this? Every guide/question I've seen on the topic so far either is just returning a render array in the content() function like I already am doing, or is suggesting to use Response classes without enough detail for me to really understand.
Comment: I think you're conceptually doing something wrong here. What is it that you actually want to achieve? Your controller shouldn't return #type page, usually a controller just provides the main content which is then surrounded by the blocks and all of that makes up the page, but that's then automatically built for you.
Comment: Not sure I 100% understand what you want. Try just a singe #markup => 'hello world' in your controller. And then combine that with either a page--print-mymodule.html.twig (see suggetsions) where you don't print the regions you don't want or by implementing hook_block_access() and deny view access to all blocks that you don't want to see (probably by only allowing certain blocks) or configure them with path based settings by hand. Does that go in the right direction?
Comment: @Berdir I'm trying to make a page that just contains a few paragraphs and a series of predefined blocks that a wkhtmltopdf function can see (it for whatever reason ignores blocks inserted via the block structure interface so I don't have the option of doing this through the drupal GUI), which is supposed to be very stripped down and printer-friendly, but this still needs some table styles and such. The content has to be restricted to only certain users and accessible with either a session cookie or a basic auth header. The cookie didn't work, so I'm going with basic auth.
Comment: (ran out of space in my last comment) Basically how I want to accomplish this is similar to adding standalone forms to routing.yml files, which I've done before, the page templates seems to work with that since form classes have a buildForm function. I just want to do something similar except just a static page and not a form.
Comment: @Berdir I have tried that, but a template with "page" in the name isn't detected by twig's template suggestions. It is only picking up a template that starts with "html--"
Comment: I really just want a page that uses a particular template and is affected by hook_preprocess, but is also only accessible by Basic Auth for users with a particular permission (I tried doing it with a session cookie, which worked great in testing and allowed me to do this with a page & node type I defined in the Drupal interface w/o using any code, but this didn't work nicely since I'm trying to automate access to this page via wkhtmltopdf with a cron task). Basic Auth is not enabled for my entire site, only for those specified by routing.yml files, so I wanted to accomplish it this way.
Answer: When you generate an entity with drupal console you get a twig template for the content of the entity. This is not a page and not a theme. If you want to use a page template, that is specific to the entity, then you use a template name suggestion, for exampe page--myentity.html.twig. The content from the entity controller will end up like any other content inside of this page in the region content if you use the standard block layout, where the block "Main page content" is placed in this region.
You can remove anything else from the page template what you don't need and replace this with static html.
Comment: Sorry if I'm not fully understanding, are you saying I would have to create a new entity type to accomplish what I want?
Comment: No, the name for the page template is an example. Use twig debug to see what name suggestions are available for page.html.twig.
Comment: Oh ok, that's what I am doing, it is picking up my template but that template is not a "page" template.
Comment: This is the page template: http://cgit.drupalcode.org/drupal/tree/core/themes/stable/templates/layout/page.html.twig. You only need the region "page.content". You can remove anything else, like the menus, if you don't want them in the pdf.


Behavior with C bitwise operations

Question: I am currently experimenting with bitwise operations in C and I am trying to understand why this code prints a different value for variable a and variable b.
I know that a 32 bit shift overflows the 1 variable (that is a normal int), but my understanding is that it should print 0 in both cases.
Instead, it prints what seems like a random number with the unsigned int a and a  0 value with the unsigned long int b.
#include <stdio.h>

int main(){
  printf("%lu %lu\n",sizeof(int), sizeof(long int));
  unsigned int a = 1 << 32;
  unsigned long int b = 1 << 32;
  printf("%u %lu\n", a, b);
  return 0;
}

Sample output:
4 8
374588997 0

What am I missing?
EDIT
Now I am trying only with a 31 bit shift, the compiler gives me NO warning.
Source:
#include <stdio.h>

int main(){
  int shift = 31;
  unsigned long int b = 1 << shift;
  printf("%lu\n", b);
  return 0;
}

And it outputs 18446744071562067968, that is really not 2^31. Any clue?
Comment: If is [undefined behavior is the shift size is greater or equal to the bit length](https://stackoverflow.com/questions/19636539/arithmetic-right-shift-gives-bogus-result/19636588#19636588).
Comment: Ok, but why does it give a different result between the two operations? The expression is still the same: 1 << 32, the LHS changes but the expression should be already evaluated.
Comment: Because nasal demons. http://www.catb.org/jargon/html/N/nasal-demons.html
Comment: Mmmmm... where did you get your hands on a compiler that yields `sizeof(long int) == 8`?
Comment: Also see: http://stackoverflow.com/questions/7401888/why-doesnt-left-bit-shift-for-32-bit-integers-work-as-expected-when-used
Comment: Check the disassembly of the line `unsigned int a = 1 << 32`, and you'll get an answer to your question. Microsoft Visual C++ 2010 compiler yields `mov dword ptr [a],0`, which means that variable `a` is set to 0. I cannot check it on your `OS X - llvm/clang` platform, since I don't have it installed. Based on your print results, my guess is that the compiler ignores this assignment, leaving variable `a` uninitialized.
Answer: First a is random because the shift count is greater than the length of the type. This is undefined behavior:
/tmp/test.c: In function 'main':
/tmp/test.c:5:6: warning: left shift count >= width of type [enabled by default]
      unsigned int a = 1 << 32;
      ^

Now b is declared as long int, but its value is computed with 32 bit logic, since by default 1 is int:
/tmp/test.c:6:8: warning: left shift count >= width of type [enabled by default]
      unsigned long int b = 1 << 32;
      ^

The correct expression for b would be:
unsigned long int b = 1L << 32;

EDIT to answer your new question:
In C, 1 is by default signed int therefore 1 << 31 is the negative number -2147483648. Now this number gets converted to 64 bits, it becomes 0xffffffff80000000 (-2147483648 as signed long int) and finally its signedness is discarded. That's why you get 18446744071562067968 which is 0xffffffff80000000.
Comment: If I change the declaration of `b` as `unsigned long int b = 1L << 32;`, the second error disappears and I get the output:
`4 8`
`0 4294967296`
Comment: since 4294967296 is 0b100000000000000000000000000000000, you're good :)
Answer: Change your code as below
#include <stdio.h>

int main(){
  int shift = 31;
  unsigned long int b = 1LU << shift; /* or 1U << shift */
  printf("%lu\n", b);
  return 0;
}

It seems on your system long int is 64 bit.
You are getting int result which is negative and trying to store it into 64 bit unsigned leading to the strange number.
p.s. 18446744071562067968 = FFFFFFFF80000000
Comment: @ShafikYaghmour Thank you for your expert comment. Can you please shed more light why it is undefined? I have read many knowledge sharing posts from you. And a brief comment/explanation here would benefit both OP and me.
Comment: Your explanation of the problem is incomplete, I linked an explanation in my [comment above](http://stackoverflow.com/questions/23424985/behavior-with-c-bitwise-operations/23425138#comment35898968_23424985). Your example code is ok since you are only shifting by `31` but you need to explain that the results of undefined behavior are unreliable and although they can be explain on a specific instance it is not a general explanation.
Comment: Note that `clang` generates some useful error message for the OPs code, see a [live example](http://coliru.stacked-crooked.com/a/5af1d78f92469aef) using the following flags: `-Wall -Wextra  -Wconversion -pedantic -fsanitize=undefined`.
Comment: By the time I read the question, OP understood the problem in his question and edited the question. I answered only the edited part. You said **this is still undefined behavious**. I tried my [piece of code](http://coliru.stacked-crooked.com/a/bf2a456981ae73d8) and it doesn't exhibit a warning. Or may be I missed something you want to convey.
Answer: Your code works as expected for me (gcc 4.6.3 on 12.04LTS). But it produces couple of warnings about shift count being greater than the width of type.
Compilation gives:
Test.c: In function 'main':
Test.c:5:5: warning: left shift count >= width of type [enabled by default]
Test.c:6:4: warning: left shift count >= width of type [enabled by default]
Output of run:
4 8
0 0
Good Luck!

Behavior with C bitwise operations


Evaluating negative infinite tetration: $\lim\limits_{n\to-\infty}\,^n x=\lim_{n\to\infty}\underbrace{\log_x\left(…\log_x(0)\right)}_n=\,^{-\infty} x$

Question: One can learn that for a power tower of height $n$:
$$y=n\big\{x^{x^{x^…}}=\,^nx\implies \log_x(y)=\boxed{\log_x(\,^nx)=\,^{n-1}x}$$
giving a recursive relation. One might see that $n<-2$ cases are undefined, but using the extended real numbers or limits, one can actually use the principal branch for the logarithm function for $x\ne0$:
$$\log_x(\,^1x)=\frac{\ln(\,^1 x)}{\ln(x)}=\,^{1-1}x=\,^0x=1\implies  \frac{\ln(1)}{\ln(x)}=\,^{0-1}x=\,^{-1}x =0$$
Here is when problems occur. We can define $\ln(-\infty)=\infty$ or $\ln(-\infty)=\ln(-1)+\ln(\infty)=\pi i+\infty$, but to stick with real values, like in

Does this limit exist or is undefined $$\lim_{x\to -\infty}\ln\left(\frac{x^2+1}{x-3}\right)=\ln(-\infty)=\infty,$$

let us consider the simpler version of $\boxed{\ln(-\infty)=\infty}$. Note that I will not simplify the logarithms into the infinity to keep the domain as large as possible:
$$\frac{\ln(\,^{-1} x)}{\ln(x)}=\frac{\ln(0)}{\ln(x)}=\,^{{-1}-1}x=\,^{-2}x =-\frac{\infty}{\ln(x)}\\\implies \frac{\ln(\,^{-2} x)}{\ln(x)}= \frac{\ln\left(\frac{-\infty}{\ln(x)}\right)}{\ln(x)}=\,^{{-2}-1}x=\,^{-3}x = \frac{\ln\left(\frac{-\infty}{\ln(x)}\right)}{\ln(x)} = \frac{\infty-\ln(\ln(x))}{\ln(x)}\\\implies \frac{\ln(\,^{-3} x)}{\ln(x)}=\frac{\ln\left(\frac{\infty-\ln(\ln(x))}{\ln(x)}\right)}{\ln(x)}=\,^{{-3}-1}x=\,^{-4}x = \frac{\ln\left(\frac{\infty-\ln(\ln(x))}{\ln(x)}\right)}{\ln(x)}=\log_x\left(\infty-\ln(\ln(x))\right)-\log_x(\ln(x)) $$
and so on. This creates a couple questions using our aforementioned assumptions and these Wolfram Functions conventions. The question here is what would happen if we calculated:
$$\lim_{n\to-\infty}\,^n x=\lim_{n\to\infty}\underbrace{\log_x\left(…\log_x(0)\right)}_n=\,^{-\infty} x$$
which looks like a W-Lambert function:
$$-\frac{\text W_{-1}(-\ln(x))}{\ln(x)}= \lim_{n\to\infty}\underbrace{\log_x\left(…\log_x(e)\right)}_n $$
using the same process and the recursive definition of:
$$\log_x(\,^nx)=\frac{\ln(\,^nx)}{\ln(x)}=\,^{n-1}x $$ Also, what is the range of this new experimental $\ \,^{-\infty} x\ $ function? I have listed the conventions that will be used, so there should be no confusion. Please correct me and give me feedback!
Comment: What is $^n x$? You want me to watch the video to find out? The video is $>40$ min long and the guy there has a bad haircut.
Comment: First we might try to find $^{-2}x$. There may be a problem. See the discussion of extensions [here](https://en.wikipedia.org/wiki/Tetration).
Comment: @markvs The video is just a link, the goal is to use the reduction formula in the question.
Comment: **What is** $^n x$???
Comment: @markvs Did you see " where one can learn that for a [**power tower of height $n$**](https://en.m.wikipedia.org/wiki/Tetration):

$$y=n\big\{x^{x^{x^…}}\\=\,^nx\implies \log_x(y)=\log_x(\,^nx)=\,^{n-1}x$$"? It is one of many notations for tetration.
Comment: @TymaGaidash: The second equality there is a definition??
Comment: @markvs I am confused by what you want to know. That is the definition at the start of the question. It is an exponential tower with $n$ amount of $x$ in it.
Comment: No, the start of the question is this "The question is inspired from this video where one can learn that for a..."
Comment: @markvs I suggest you watch from 6 minutes to 13 minutes into the video to get the definitions. Let me edit.
Comment: As I said, the guy has a bad haircut. It is repulsive.  Make him change it (or change the guy altogether) and remake the video. Then I perhaps will have a few minutes to watch it.
Comment: If you would take the other definition of the iterated logarithm $\log°^h(z_0)=\log(\log°^{h-1}(z_0))$ with $\log°^0(z_0)=z_0$ *(and using the principal branch of the logarithm)* then the exceptional values for which your iterated logarithm runs into singularities are exactly that of $z_0 \in \{0,1,e,e^e,e^{e^e},\,^4e,\,^5e,...\}$. But when you use different $z_0$ as starting values you can apply that iterated logarithm when you allow logarithm of complex values. Then beginning with (complex) $z_0 $ near $0+0î$ or near $1+0î$ you get a hint what your wished limit goes to. (...)
Comment: (...)  I've once computed the iterates of the line $z_0 \in \{0+\varepsilon \ldots 1-\varepsilon\}$ and plotted the lines for the iterated logarithms as far as I could manage $\varepsilon \to 0$ with Pari/GP and got an interesting set of plots. Similarly with small imaginary parts of that $z_0$ . Anyway, one can see how this iterates to the complex fixpoint for base $e$; and can analoguously made with other bases. Don't know, though, whether this is trivial to you and so didn't compose an answer showing such plots.
Comment: (...) And the sequence of plots suggest, that once you define $\log(-\infty):= \pm \pi î+ \infty$ then the limit of this for the first three iterates is $+\infty \pm 0 î $ and all further iterates should have the same form. (Sorry, I didn't catch your question correctly at the beginning)
Comment: @markvs. Never watch people with bad haircut, bruhhhhhhhhhh
Comment: @TymaGaidash. I know about the channel. I was just joking that how markvs didn't watch the video because his hairstyle was repulsive to him or maybe he was just trolling.
Answer: (Not an answer, only an extension of my 2.nd comment)
I show some iterates of the $\log()$ with base=$e$. Using my proposed definition for the
notation we see some initial values $z_0$ between $0$ and $1$ and their $h$'th iterates
$z_h$. I think it is easily extrapolatable, where the $h$'th iterates tend to, when
$z_0$ approaches either the initial value $0$ (or $1$, which is implied by your notation).
This is a q&d-computation with Pari/GP with internal precision of 200 dec digits.
<code>               z_0                 z_0                z_0               z_0               z_0               z_0               z_0               z_0               z_0               z_0               z_0               z_0
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
z_0           5.000E-26         5.000E-17   0.0000000005000        0.00005000            0.05000            0.5000  |            0.5000           0.9500             1.000             1.000             1.000             1.000
z_1              -58.26            -37.53            -21.42            -9.903             -2.996           -0.6931  |           -0.6931         -0.05129       -0.00005000  -0.0000000005000        -5.000E-17        -5.000E-26
z_2       4.065+3.142*I     3.625+3.142*I     3.064+3.142*I     2.293+3.142*I      1.097+3.142*I   -0.3665+3.142*I  |   -0.3665+3.142*I   -2.970+3.142*I    -9.903+3.142*I    -21.42+3.142*I    -37.53+3.142*I    -58.26+3.142*I
z_3      1.637+0.6580*I    1.568+0.7140*I    1.479+0.7979*I    1.358+0.9403*I      1.202+1.235*I     1.151+1.687*I  |     1.151+1.687*I    1.464+2.328*I     2.341+2.834*I     3.075+2.996*I     3.629+3.058*I     4.066+3.088*I
z_4     0.5675+0.3823*I   0.5440+0.4273*I   0.5191+0.4947*I   0.5020+0.6055*I    0.5443+0.7987*I   0.7142+0.9718*I  |   0.7142+0.9718*I    1.012+1.009*I    1.302+0.8805*I    1.457+0.7724*I    1.557+0.7003*I    1.630+0.6495*I
z_5    -0.3794+0.5928*I  -0.3685+0.6658*I  -0.3326+0.7614*I  -0.2401+0.8786*I  -0.03400+0.9726*I   0.1873+0.9371*I  |   0.1873+0.9371*I  0.3571+0.7843*I   0.4521+0.5947*I   0.5002+0.4875*I   0.5350+0.4226*I   0.5624+0.3791*I
z_6     -0.3512+2.140*I   -0.2732+2.076*I   -0.1853+1.983*I  -0.09336+1.838*I   -0.02715+1.606*I  -0.04541+1.373*I  |  -0.04541+1.373*I  -0.1488+1.144*I  -0.2917+0.9207*I  -0.3589+0.7725*I  -0.3831+0.6686*I  -0.3882+0.5930*I
z_7      0.7742+1.733*I    0.7391+1.702*I    0.6888+1.664*I    0.6097+1.622*I     0.4737+1.588*I    0.3179+1.604*I  |    0.3179+1.604*I   0.1425+1.700*I  -0.03476+1.878*I   -0.1604+2.006*I   -0.2606+2.091*I   -0.3442+2.150*I
z_8      0.6411+1.151*I    0.6180+1.161*I    0.5883+1.178*I    0.5495+1.211*I     0.5049+1.281*I    0.4917+1.375*I  |    0.4917+1.375*I   0.5342+1.487*I    0.6301+1.589*I    0.6992+1.651*I    0.7454+1.695*I    0.7783+1.729*I
z_9      0.2756+1.063*I    0.2740+1.082*I    0.2754+1.108*I    0.2852+1.145*I     0.3197+1.195*I    0.3787+1.227*I  |    0.3787+1.227*I   0.4576+1.226*I    0.5363+1.193*I    0.5837+1.170*I    0.6160+1.156*I    0.6400+1.148*I
                 .                 .                 .                 .                  .                 .                    .                .                 .                 .                 .                 .
                 .                 .                 .                 .                  .                 .                    .                .                 .                 .                 .                 .
                 .                 .                 .                 .                  .                 .                    .                .                 .                 .                 .                 .
z_oo        <fixpoint>        <fixpoint>        <fixpoint>        <fixpoint>         <fixpoint>        <fixpoint>   |       <fixpoint>       <fixpoint>        <fixpoint>        <fixpoint>        <fixpoint>        <fixpoint>

</code>
Below there is a plot of the iterates $z_h = \log°^h(z_0)$ of the line $z_0 \in \varepsilon \ldots 1-\varepsilon$
The lines $z_0 , z_1=\log°^1(z_0),z_2 =\log°^2(z_0)$ are not displayed. The line for $z_3$ is the red curve in the right half looking roughly like a $\sqrt x $ curve, the line for $z_4$ is the green curve most neighboured at the $z_3$ curve and the positive real axis, whose both ends tend to $+ \infty + 0 \pi î$.
This plot should work as a suggestion how -if at all- that infinite iteration could be defined most meaningfully.

Additional remark: the curves could not have been drawn out to the values $x \approx 9$ by the iteration of logarithms alone; two times iterated back we had a real value of $\exp(\exp(9.4)) \approx 2.1 E 4750$ which gives then a limit for $z_0$ near $0$ which I wouldn't have used from the beginning . But there is a functional relation between the real- and the imaginary value in the $z_3$ curve which allows to compute (and plot) the curve to arbitrary real-argument larger than this roughly 1.2-value. From that the iterated logarithms for a far wider interval of the $z_3$ can be computed. (Sorry, don't have that functional relation at hand at the moment, but was simply derived from the trigonometric formula for the complex logarithm).
Comment: (+1) @Gottfried Thanks for the insights, but the goal is to have $$\log_x^{\circ h}(0)$$ which may diverge, but has interesting behavior for complex values. A limit as $h\to 0$ may also work if that is what you did here.
Comment: Tyma, thanks for the comment and the upvote! The point of the introducing table is surely away from your question (I got it obviously not correct immediately). But the point of the plot is indeed to give suggestions for the locus of the endpoints $\log_x^{\circ h}(1-\varepsilon)$ and $\log_x^{\circ h}(0+\varepsilon)$ for some small $h =1 \ldots 8$ to deduce the limit for $h \to \infty$ - of course if I'm not messing again ... ;)
Answer: With some rough experimentation, one has the following result for the "experimental $-\infty$ tetration" using this computation and the sign function:
$$\log_{a+bi}\left(\log_{a+bi}\left(\log_{a+bi}\left(0\right)\right)\right)=\frac{\infty}{\text{sgn}(\ln(a+bi))}$$
It does not matter if you define $\ln(-\infty)=\infty+\pi i$ or $\ln(-\infty)=\infty$, for any amount $n>2$ logarithms nestings, you get the following:
$$\,^{-\infty}x\mathop=^\text{def}\lim_{n\to\infty}\underbrace{\log_x\left(…\log_x(0)\right)}_n= \frac{\infty}{\text{sgn}(\ln(x))}=\frac{\sqrt{\text{Re}^2(\ln(x))+\text{Im}^2(\ln(x))}}{\ln(x)}\infty$$
You may think that this is useless because it diverges, but the rate of divergence is proportional and is called the Directed Infinity function:
$$\text{DirectedInfinity}(x)\mathop=^\text{def} \infty x\implies \,^{-\infty}x = \text{DirectedInfinity}\left(\frac{1}{\text{sgn}(\ln(x))}\right) $$
which is a complex number times infinity.
One property of $\infty x$ is that:
$$\infty x=\infty \text{sgn}(x)\implies \infty\text{sgn}\left(\frac{1}{\text{sgn}(\ln(x))}\right)= \frac{\infty}{\text{sgn}(\ln(x))} $$
Here is a complex plot of $$\frac{1}{\text{sgn}(\ln(x+yi))} :$$

Here are some values of this function:
$$\frac{\infty}{\text{sgn}(\ln(2))}=\infty$$
$$\frac{\infty}{\text{sgn}(\ln(-2))}=\frac{\sqrt{\pi^2+\ln^2(2)}}{\ln(2)+\pi i}\infty$$
$$\frac{\infty}{\text{sgn}(\ln(i))}=-\infty i$$
$$\frac{\infty}{\text{sgn}(\ln(2))}=\infty$$
$$\frac{\infty}{\text{sgn}(\ln(2-3i))}=\frac{i\sqrt{\ln^2(13)+4\tan^{-1}\left(\frac32\right)^2}}{2\tan^{-1}\left(\frac32\right)+i\ln(13)}\infty$$
Please correct me and give me feedback!
Comment: If you have a better answer, then I will probably accept it.


Probability: Continuous Random Variables and Transforming from One PDF to another PDF

Question: Problem:
Let $X$ be a random variable with the probability density function given by
$$f(x) = \begin{cases}
e^{-x} & \text{if } x\geq 0\\
0 & \text{elsewhere.}
\end{cases}$$
Let
$$Y = \left\{\begin{matrix}
X & \text{if } X\leq 1\\
1/X & \text{if } X>1.
\end{matrix}\right.$$
Find the probability density function of $Y$.

My Attempted Solution:
So, to begin, we know that $f(x)$ is continuous so we can integrate to get $F_{x}(t)$. We only need to integrate from $0$ to $t$ because that is when $f(x)$ is non-zero. So:
$$F_{X}(t) = \int_{-\infty}^t f_{X}(x)\,dx = \left\{\begin{matrix}
\int_0^t e^{-x} \,dx & \text{if } t\geq 0\\
0 & \text{otherwise.}
\end{matrix}\right. = \left\{\begin{matrix}
1 - \frac{1}{e^t} & \text{if } t\geq 0\\
0 & \text{otherwise.}
\end{matrix}\right.$$
Now, we know by definition that $F_y(t) = P(Y \leq t)$. However, given the piecewise definition of $Y$, we know $Y = X$ when $X \leq 1$ and $Y = \frac{1}{X}$ when $X > 1$. So, we get the following distribution function for $Y$:
$$F_Y(t)=P(Y\leq t) = \left\{\begin{matrix}
P(X\leq t) & \text{if } X\leq 1\\
P(\frac{1}{X}\leq t) & \text{if } X> 1.
\end{matrix}\right.$$
Typically, I see CDFs bounded in terms of $t$ so I unsure where to go from here. What is the process for converting the bounds to $t$? If I get that part, then I will be able to derive the PDF of $Y$.
Comment: You've got $F_x(t)$ where you should have $F_X(t)$ and $f_x(x)$ where you should have $f_X(x).$
Comment: @DominikKutek I don't quite understand how you can use the fact that t lies in (0,1] to determine that X also is less than or equal to 1. Can you elaborate more?
Comment: Oops, dumb things, sorry.
Answer: Given the definition of $Y$, we can tell that $Y$ is either $\leq 1$ when $X$ is $\leq 1$, or $Y$ is $1/X$ when $X > 1$. Regardless of the case, we see have $Y < 1$. So, we now know that the range of $Y$ is $(-\infty,1]$. Looking closer, we can see $-\infty < Y < 0$ is only when $X < 0$ based on the definition of $Y$. So, we know that $f(x)$ in that case would be $0$ given the definition of $X$.
Now, suppose $0\le y\le 1.$ Then
\begin{align}
f_Y(y) & = \frac d {dy} F_Y(y) = \frac d{dy} \Pr(Y\le y) \\[8pt]
& = \frac d {dy} \Pr(X\le y \text{ or } 1/X\le y).
\end{align}
The two events between which you see "or" are mutually exclusive, so this is
\begin{align}
& \frac d {dy} \big( \Pr(X\le y) + \Pr(1/X\le y) \big) \\[8pt]
= {} & \frac d {dy} \big( (1-e^{-y}) + \Pr(X\ge 1/y) \big) \\[8pt]
= {} & \frac d {dy} \big( (1-e^{-y}) + e^{-1/y} \big) \\[8pt]
= {} & e^{-y} + e^{-1/y}\cdot \frac 1 {y^2}.
\end{align}
And if $y<0$ or $y>1$ then $f_Y(y)=0.$
Comment: You are given $X\ge0$ and either $Y=X$ or $Y=1/X.$ That tells you that $\Pr(Y<0) = 0,$ i.e. $Y$ cannot be negative. Then you say if $X\le1$ then $Y=X,$ and that tells you that at least in that event, $Y$ cannot be more than $1.$ You also say that if $X>1,$ then $Y=1/X,$ and the reciprocal of something more than $1$ is less than $1.$ So $Y$ is never more than $1$ nor less than $0. \qquad$
Comment: Your solution makes since given $0 \leq Y \leq 1$, but how do you come up with those bounds? Why is it that $Y < 0$ and $Y > 1$ are probability of $0$?


Evaluating the sum $\sum\limits_{k=0}^{15} (-1)^k \cos^{560} (k\pi/16).$

Question: To eliminate the pesky $(-1)^k$ term, I have rewritten this as
$ S = -\sum\limits_{k=0}^{15} \cos^{560} (k\pi/16) + 2\sum\limits_{k=0}^{7} \cos^{560} (k\pi/8).$
However, neither of these sums are easy to evaluate. I think that the next step would be finding the minimal polynomial of $1, \cos(\pi/8), \dots, \cos(7\pi/8).$ However, this is just a factor of $T_{16}(x)-1$ where $T_n(x)$ is the $n$th degree Chebyshev Polynomial. This route is clearly messy before we even start factoring. The other sum would be even worse to handle.
I'm wondering if there are any other approaches for computing $S.$
Comment: This looks like it's related to https://math.stackexchange.com/q/2879650/5676
Comment: Seems De Moivre is applicable, but the computation is still "gruesome"…
Comment: I can't accurately tell but I sense some use of Binomial theorem and complex numbers (Using De'Moivre's formula) to solve. But still it's just a guess :-))
Comment: @xbh I have already thought about this. Unfortunately, $\Re(z)^{560} \ne \Re(z^{560}),$ so I cannot just perform calculations with complex numbers and take the real part to finish off.
Comment: On second thought, I now see what you meant, and I agree that it will be ugly.
Comment: By the way, would it help if I knew that $2^{560}S$ is an integer (due to how the problem was asked)?
Comment: Looks like $S\approx \cos\left(\frac\pi{180}\right)$
Answer: Let us compute the number using sage, the needed two lines
K.<z> = CyclotomicField( 32 )
print sum( [ (-1)^k * ( (z^k + z^-k) / 2 )^560 for k in [0..15] ] )

will be slightly expanded, so that the human eye can easily digest them, above z is $\zeta_{32}\sim\exp(2\pi i/32)$ a primitive root of unity of order $32$, sage works algebraically (exactly), the (also by sage) preferred  embedding in $\Bbb C$ can be easily changed:
sage: K.<z> = CyclotomicField( 32 )
sage: z.complex_embedding()
0.980785280403230 + 0.195090322016128*I
sage: cos(2*pi/32).n()
0.980785280403230
sage: A = sum( [ (-1)^k * ( (z^k + z^-k) / 2 )^560 for k in [0..15] ] )
sage: A = QQ(A)
sage: A.denom().factor()
2^487
sage: A.numer()
399568537235075894687625168713672502385259077051830433046200439695346621697198388130048600447044762506823601999970295738124406324872353832659479279

This writes the given sum as a rational number with denominator $2^{487}$ and a numerator as above. (Do we expect something special about this number, expected to be rational with a two-power as denominator?!)
Comment: I knew that $2^{560}S$ had to be an integer before I started solving the problem, which explains your result.


Query information about my app's user in twitter

Question: I want to query information about my app's user Info (name, id...)
In twitter (PHP).
What I want to know how I can reuse the token credentials of user???
I have done that but with my Twitter session. It means I must login with my twitter account, after that I can query information about my app's user (That's not correct!!!!!).
Answer: Please read this, this will be useful for your query :-
http://mikerogers.io/2013/02/25/how-use-twitter-oauth-1-1-javascriptjquery.html


Exibir apenas segundo campo do field choises

Question: Na minha model possuo uma lista de opção e quando exibo ela no template aparece assim: "("D", "Devagar",)" e gostaria que fosse exibido apenas "("Devagar")".
Atualmente

Como deve ficar

Model.py
class Perfil(models.Model):
    vel = (
        ("D", "Devagar",),
        ("N", "Normal"),
        ("R", "Rápido "),
        ("S", "Super Rapido (Cuidado!)"),
    )

    velocidade = models.CharField(max_length=1, choices=vel, null=True, blank=True, verbose_name='Velocidade')

views.py
from django.shortcuts import render
from .models import Perfil

def account(request):
    user_id = request.user.id
    perfil = Perfil.objects.get(usuario_id=user_id)

    return render(request, 'core/account.html', {'nome': user_id, 'dados':perfil })

home.html
<select class="form-control select2 select2-hidden-accessible" style="width: 100%;" data-select2-id="1" tabindex="-1" aria-hidden="true">
    {% for opcao in dados.vel %}
        <option data-select2-id="{{opcao}}">{{ opcao }}</option>
    {% endfor %}
</select>

Answer: Como demonstrado na documentação da template tag for você pode desempacotar (unpacking) os items que você está iterando sobre.
Como no seu caso, cada item é uma tupla, você poderia desempacotar a tupla em dois valores e usá-los:
<select class="form-control select2 select2-hidden-accessible" style="width: 100%;" data-select2-id="1" tabindex="-1" aria-hidden="true">
    {% for opcao_id, opcao_valor in dados.vel %}
        <option data-select2-id="{{ opcao_id }}">{{ opcao_valor }}</option>
    {% endfor %}
</select>

Answer: Quando você faz o for na opção você está iterando dentro de uma tupla de tuplas, sendo assim eu imagino que você queira fazer assim:
{% for opcao in dados.vel %}
    <option data-select2-id="{{opcao.0 }}">{{ opcao.1 }}</option>
{% endfor %}

O opcao.0 pega o primeiro item da tupla então no caso da tupla ("D","Devagar") ele vai pegar o "D" e o 1 pega o segundo item da tupla, no caso o "Devagar".


Commerce Allows User to Edit Cart After Completion of Checkout

Question: I recently found a problem where a customer can edit their cart and re-checkout after checkout has been completed and payment has been made. This results in a single order record (the latter one) and two payments.
Re-creation of this issue:
1. Start a cart
2. Open the cart in a second window (You should have two windows/tabs open with the same cart)
3. Checkout on the first screen
4. Once checkout is completed and payment has been made, remove or update an item in your cart using the second screen
This places the cart back in a Shopping Cart status (per Drupal Commerce rules) and you have the same order/cart number since they share a table (which is another problem for another day). You can now checkout again and you will have two order confirmation emails with the same order number. Drupal Commerce will show only one order (the second order) but two payments. There is no way to recover the first order.
This only happens when the customer leaves the shopping cart open in multiple window(s) and tries to edit it after checkout.
Is there a fix to dis-allow editing of a cart after it changes over to an order? I would like it to throw an error and force a refresh of the page causing it to create a new shopping cart.
Answer: Hmmm, this is definitely something that deserves to be fixed in Commerce itself. I'm going to open an issue there and outline a strategy that essentially adds a form alter hook to the Cart module to redirect back to /cart in the event that the shopping cart form is being built / submitted for an order that is in an unsupported status. I can't say exactly how I'd do it yet, but I suppose it would involve iterating through the checkout pages to allow shopping cart form submissions for any order that hasn't yet passed a checkout page that doesn't have back buttons (e.g. the Payment and Completed pages).
Comment: Thanks for your help. I have added the issue to the commerce guys site as well:
[Commerce Guys Issue](https://drupalcommerce.org/discussions/31858/commerce-allows-user-edit-cart-after-completion-checkout)

Look forward to a resolution to this
Comment: Ok, fwiw the issue was filed and will be resolved here: https://www.drupal.org/node/2410391


What is the fastest way to convert a large volume of documents (.html) to drupal nodes

Question: How would you go about creating a large number of nodes from a large number of html documents?
I am trying to create something similar to a book and have a lot of .docx files on my computer. I am aware I should use a wysiwyg editor to clean up the formatting and make it look like I want saving it as HTML.
However there is the issue of getting all the .html files uploaded as nodes without having to copy-paste 200+ times.
Any ideas?
Answer: The module that appears as most suitable for you is called HTML import. This module will divide one single large HTML document into a structured Drupal book where the heading level hierarchy is respected. This module works with HTML exported from Word; HTML document converted from PDF as well as HTML document exported from Adobe InDesign.
This makes it possible to use a single HTML page, created in a word processing program and saved as HTML, or other structured HTML, to create a multipage Drupal book in a single step.  You actually need to collate the output from all your <code>.docx</code> files into a single HTML-file before converting to HTML to use HTML import in a single step.
In case your requirements are beyond what HTML import is capable of, below is a list of all the (usable) Drupal modules I am aware of that can be used to bulk import HTML (and some other formats) into a Drupal site:

HTML import  - Import a single HTML page created from MS Word and split it up into an hierarchical Drupal book structure consisting of a set of interlinked Drupal nodes.
HTML2Book - This also imports a single HTML page and split it up into an hierarchical Drupal book structure consisting of a set of interlinked Drupal nodes, but requires you to clean up the tagsoup created by MS Word first.
Import HTML - Import all of an existing, static HTML-site into a Drupal site as nodes.
Feeds - Import or aggregate data as nodes, users, taxonomy terms or simple database records.
Migrate - Provides a flexible framework for migrating content into Drupal from other sources, including HTML.
Node import - Allows users to import content (node, user, taxonomy) from CSV or TSV files. Requires you to convert from HTML to CSV. (no Drupal 7 version)

Of these, the simplest to use are HTML import and HTML2Book. However, both can only handle a single HTML page. For more complex conversion tasks, where you need to convert a large static HTML-site made up of several interlinked pages, one of the other modules may be more suitable.
Also: Whatever tool you use, never experiment with bulk import on a production site. Unless you're a lot more clever than me, there are going to be false starts and botched imports. Cleaning up thousands of nodes damaged by an import gone wrong is not fun.  Always experiment with bulk import on a throwaway staging site that just can be discarded wholesale when things go wrong. Transfer the settings and do the import on the production site when you're sure you have a working set-up.
Comment: @Ithxi, I've used **Feeds** for a number of bulk import projects and to import HTML. make sure you tick  "Allow all HTML tags". I am not aware of any tutorials describing the process in detail. This site is for basic Q&A, not detailed tutorials (nor do I have the time to write one). Feeds is indeed a beast that has rather rough edges. On the other hand, installing a throwaway Drupal 6 on localhost is (IMHO) quick and simple. If I had to choose between configuring **Feeds** to import HTML, and to set up a throwaway Drupal 6, I would opt for the latter.
Comment: Thank you for the thorough answer!
However I am using drupal 7 and already have a site set up (took quite a while to configure it.. so I am very much against creating a new drupal site).

Feeds seems to be the only real option, however it seems very complex to use. Could you possibly elaborate on its use or are there any tutorials that are easy to read for a time-pressed fellow?
Comment: I suppose it is an answer. But jeez it is horrible that there isn't a better way to do this? Someone must have faced the same issue and created a solution...

Thanks for the answer though - I will mark it as answered in a couple of hours if no other answers show
Answer: If you have a lot of docx files(which you do), then it is really worth the effort to write a custom migration class using the migrate module. Something similar has been done before and documented.
Answer: Here is a nice tutorial for learning how to use feeds. It is really quite straightforward.  http://mustardseedmedia.com/podcast/episode55
Please note that it doesn't cover how to import html docs but it should get you pretty far down the road.
Also, you really should learn how to use backup and migrate module ( https://drupal.org/project/backup_migrate) so you can easily backup and restore your database if you break something.  I would also recommend you take the time to setup an extra copy of your site that you can experiment on.  It is very frustrating when you break something and can't find your way back.
Selwyn


If $f: \mathbb R^2 \rightarrow \mathbb R$ is a continuous function such that $f(x)=0$ for only finitely many values of $x$,

Question: If $f: \mathbb R^2 \rightarrow \mathbb R$ is a continuous function such that $f(x)=0$ for only finitely many values of $x$, then prove/disprove the following :
$(a)$ Either $f(x) \geq 0 ~~\forall x\in  \mathbb R^2  $ or $f(x) \leq 0 ~~\forall x\in  \mathbb R^2  $
$(b)f $ is onto
$(c)$ $f$ is one-one
Attempt: I have an intuition that the continuous nature of function $f$ would play a part in this problem. however, unfortunately, I am not able to decipher how to move ahead.
Any directions on this problem shall be really great.
Thank you.
Comment: $\;f(x,y)=x^2+y^2\;$ already disproves (2)-(3).
Comment: @VHP I thought I explained why (a) is always true in my last comment? You can easily draw an infinite number of nonintersecting continuous paths between those two points (where $f$ has opposite signs), and $f$ has at least one zero on each of those paths, so $f$ has an infinite number of zeros.
Comment: Suppose $f(a)\gt0$ and $f(b)\lt0$. Now suppose you draw a continuous path from $a$ to $b$. Does $f(x)$ have to be $0$ for some $x$ on that path? Now, how many nonintersecting continuous paths can you draw from $a$ to $b$?
Comment: The function $f$ is defined on the whole plane, right? There are **lots** of continuous paths from $a$ to $b$. Let $d$ be the distance between $a$ and $b$. For each $D\ge d$ you can draw a circle (two circles if $D\gt d$) of diameter $D$ which passes through $a$ and $b$, and those circles have no other point in common, so you get a continuum of nonintersecting continuous paths (circle arcs) from $a$ to $b$.
Comment: Thanks. Any hints on $(1)$ please..
Comment: @bof yeah, :-) $f(x)$ would need to be $0$ for some $x$ on that path if $f(a)>0,f(b)<0$. However, there can still be a single only continuous path from $a$ to $b$?
Comment: (a) is always true, and so (b) is always false.  (c) is false for *any* continuous function from $\mathbb{R}^2$ to $\mathbb{R}$, even without the other condition; it's false even when the domain is restricted to the boundary of the unit circle, $\{ x\in\mathbb{R}^2 \;|\; |x|=1 \}$.
Comment: @mjqxxxx Could you please tell me why $(a)$ is always true?
Comment: @bof :-) I was just curious to know if mjqxxxx was also suggesting another approach as well. I understand that there are infinite continuous non intersecting paths between $a$ and $b$ . But, the function $f$ would be well defined and take only one path ..
Answer: $f^{-1}\left(0\right)$ has a finite number of elements let's say $(x_1,y_1),(x_2,y_2),\ldots,(x_N,y_N)$.
Let $$R=\frac{1}{3}\min_{1\leq i < j\leq N}\sqrt{\left(x_j-x_i\right)^2+\left(y_j-y_i\right)^2}$$
and $$B_k=\{(x,y):\sqrt{(x-x_k)^2+(y-y_k)^2}<R\}\quad\text{for}\;k=1,2, \ldots,N$$
It follows $f$ vanishes at $(x_k,y_k)$ and for no other point of $B_k$. Since $f$ is continuous $f$ have the same sign for all $(x,y)\in B_k\backslash(x_k,y_k)$.
Let's suppose there are two points $(x_a,y_a)\in B_a$ and $(x_c,y_c)\in B_c$ such that $f(x_a,y_a)$ and $f(x_c,y_c)$ has opposite sign, let's say $f(x_a,y_a)<0<f(x_c,y_c)$. Let $g:[0,1]\longrightarrow \mathbb{R}$ be the function defined by $$g(t)=f(tx_c+(1-t)x_a,ty_c+(1-t)y_a)$$ $g$ is a continuous function, Mean Value Theorem implies there is $t_0\in [0,1]$ with $g(t)<0$ for $t<t_0$ (in some neighborhood around $t_0$) and $g(t)>0$ for $t>t_0$ (in some neighborhood around $t_0$). Then $f$ vanishes at $(t_0x_c+(1-t_0)x_a,t_0y_c+(1-t_0)y_a)$ and this point is not in $\{(x_1,y_1),(x_2,y_2),\ldots,(x_N,y_N)\}$. Hence $f$ have the same sign for all $(x,y)\in B_k\backslash(x_k,y_k)$ for  $k=1,2,\ldots,N$.
By continuity of $f$ we conclude $f$ has the same sign for all $(x,y)\in\mathbb{R}^2\backslash f^{-1}\left(0\right)$.


How to use the Match Redirect module

Question: I'm trying to use the Match redirect module and follow the basic description I've tried the following:
/my-path-1/my-path-2/*

to
/my-path-2/*

OR
/ma-path-2/

And it doesn't work. I do have pages like:
www.example.com/ma-path-2/page-title

that works fine as expected, but when I visit
www.example.com/my-path-1/my-path-2/page-title

I was expecting to be redirected to:
www.example.com/my-path-2/page-title

Which did not happen. Why? What am I missing here?
Thanks in advance
Answer: From reading the module description, I get the impression that the Match redirect module module only replaces wildcards and cannot remove them.
I suggest you try redirect module with pathauto. After you change the path in pathauto, remember to use the BULK UPDATE tab to update the urls. Redirect will automatically do it's thing.
Comment: But the reason I was looking into Match Redirect was that I could batch change those. Your recommendation seems to be for me to change each of of those individually. Am I correct? or is there a way to batch change all pages under `/my-path-1/my-path-2/` to `/my=path-2/`?
Comment: Using Pathauto bulk update will batch them for you. As redirect will auto add them.
Comment: Just to make it clear, I do want to keep both paths as in: `/my-path-1/my-path-2/page-title` AND `/my-path-2/page-title` for about 800 odd pages. How can I use Pathauto for that?
Comment: pathauto + redirect. Backup your db, try my answer, and get back to me.

How to use the Match Redirect module


webform save draft after each field update - ajax error for anonymous user

Question: I wanted to save webform's draft after each field's update, and i did it with help of this post: Webform save draft after each field update .
But it is only working for logged in user, if i try it with anonymous i get ajax error
"An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /system/ajax
StatusText: n/a"
Does anybody have any idea why is this happening? thank you ..
Answer: The save draft functionality has not yet been committed for webform for anonymous users.
According to the post you mentioned, @Stefan in his answer claims he added the functioanlity by incorporating my patch from this issue. (We are testing an updated patch which will be posted to the issue cue within the next couple of days.)
Comment: But is this why i am getting ajax error? My request doesn't reach the part of the code you are talking about.
Comment: @gregab - how do you know your request doesn't reach it? xdebug? If so, where exactly does it fail?
Comment: yes, i set a breakpoint in server-side function, called by ajax and it doesn't reach it. I don't know where it fails, becouse there is no good error message. Javascript ajax function gets called and that's it.
Comment: Nobody knows what it could be?


Erro ao executar função pela segunda vez

Question: Dentro do controller tenho está função:
public void salvaEncaminhamento() {
    Integer qtdEncaminhamento = 0;

    if (manifestacao.getTbEncaminhamentoCollection() != null) {
        qtdEncaminhamento = manifestacao.getTbEncaminhamentoCollection().size();
    }

    TbUsuario usuario = securityService.getUser();
    for(String idUnidadeStr : idOrgaoDestino) {
        try {
            int idUnidade = Integer.parseInt(idUnidadeStr);

            //atualiza data de modificacao da manifestacao
            manifestacao.setDtUltimaAtualizacao(new Date());
            //atualiza status da manifestacao caso ela ainda esteja como nova
            if (manifestacao.getStStatusManifestacao().equals(StatusManifestacaoEnum.EM_ANALISE.getId()) || manifestacao.getStStatusManifestacao().equals(StatusManifestacaoEnum.SOLICITACAO_RESPONDIDA.getId())) {
                manifestacao.setStStatusManifestacao(StatusManifestacaoEnum.EM_ANDAMENTO.getId());
                dao.edit(manifestacao);
            }

            /*-----------------------------------------------------*/
            /*------- inicio - gravando encaminhamento ------------*/
            /*-----------------------------------------------------*/
            TbEncaminhamento encaminhamento = new TbEncaminhamento();
            encaminhamento.setDsDescricao(dsEncaminhamento);
            encaminhamento.setDtCriacaoEncaminhamento(new Date());
            encaminhamento.setDtEnvioTramite(new Date());
            encaminhamento.setIdManifestacao(manifestacao);
            encaminhamento.setIdUsuarioEnviou(usuario);
            encaminhamento.setIdUnidadeEnviou(usuario.getIdUnidade());
            encaminhamento.setStEncaminhamento(StatusEncaminhamentoEnum.ENCAMINHADA.getId());

            TbUnidade unidade = unidadeDAO.find(idUnidade);
            encaminhamento.setIdUnidadeRecebeu(unidade);

            encaminhamentoDAO.create(encaminhamento);
            qtdEncaminhamento++;
            /*------- fim - gravando encaminhamento ------------*/

            /*-----------------------------------------------------*/
            /*------- inicio - gravando tramite -------------------*/
            /*-----------------------------------------------------*/
            TbTramite tramite = new TbTramite();
            tramite.setDsDescricao(dsEncaminhamento);
            tramite.setDtTramite(new Date());
            tramite.setIdEncaminhamento(encaminhamento);
            tramite.setIdUnidadeEnvio(unidade);
            tramite.setIdUsuarioEmissor(usuario);
            tramite.setStRetornada(BooleanEnum.NAO.getId());
            tramite.setStNotificacao(BooleanEnum.NAO.getId());
            tramite.setStTramitePublico(BooleanEnum.NAO.getId());

            TbUsuario usuarioReceptor = null;
            if (ValidacaoHelper.isNotEmpty(idUsuarioEncaminhamento)) {
                usuarioReceptor = usuarioDAO.find(idUsuarioEncaminhamento);
                tramite.setIdUsuarioReceptor(usuarioReceptor);
            }
            tramiteDAO.create(tramite);

            //----- gravando anexos ---------//
            ArrayList<TbTramitexAnexo> anexosTramite = new ArrayList<>();
            for (TbAnexo anexo : arquivosEncaminhamento) {
                anexoDAO.create(anexo);
                TbTramitexAnexo tbTramitexAnexo = new TbTramitexAnexo();
                tbTramitexAnexo.setIdAnexo(anexo);
                tbTramitexAnexo.setIdTramite(tramite);
                anexosTramite.add(tbTramitexAnexo);
            }
            tramite.setTbTramitexAnexoCollection(anexosTramite);
            tramiteDAO.edit(tramite);
            /*------- fim - gravando tramite ------------*/

            try {
                enviarEmailsEncaminhamento(unidade, usuarioReceptor);
                //----- enviando e-mail ao MANIFESTANTE ---------//
                if (qtdEncaminhamento == 1) {
                    EmailService.Email emailManifestante = emailService.newEmail();
                    if ((manifestacao.getEeEmailUsuario() != null) && "1".equals(manifestacao.getStResposta())) {

                        String nomeManifestante = (manifestacao.getNmPessoa() != null) ? manifestacao.getNmPessoa() : "Manifestante";
                        emailManifestante.addDestinatario(nomeManifestante, manifestacao.getEeEmailUsuario());

                        TbEmailAutomatizado emailAutomatizado = emailAutomatizadoDAO.findByTipo(EmailAutomatizadoEnum.PRIMEIRO_TRAMITE);

                        //adiciona texto e assunto de email padrao
                        StringBuilder emailTextoHtml = new StringBuilder();
                        StringBuilder emailTexto = new StringBuilder();

                        emailManifestante.setAssunto(PalavrasChavesHelper.converterPalavrasChaves(emailAutomatizado.getNmTituloEmail(), manifestacao, false));
                        emailTextoHtml.append(PalavrasChavesHelper.converterPalavrasChaves(emailAutomatizado.getDsEmail(), manifestacao, false));
                        emailTexto.append(PalavrasChavesHelper.converterPalavrasChaves(emailAutomatizado.getDsEmail(), manifestacao, false));

                        emailManifestante.setTextoHtml(emailTextoHtml.toString());
                        emailManifestante.setTextoSemFormatacao(emailTexto.toString());
                        emailService.envia(emailManifestante);
                    }
                }
                MensagemFaceUtil.info("Manifestação encaminhada com sucesso.", "Manifestação encaminhada com sucesso.");
            } catch (Exception e) {
                e.printStackTrace();
                MensagemFaceUtil.alerta("Manifestação encaminhada mas não possível notiticar por e-mail.", "O seu encaminhamento foi realizado com sucesso porém, não foi possível notificar os envolvidos por e-mail.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            MensagemFaceUtil.erro("Erro ao encaminhar Manifestação.", e.getMessage());
        }
    }

    ajustaListaStatusManifestacao();
    preparaListaAreasSolucionadoras();
    mountTabs();
    //zerando variaveis
    idUnidadeEncaminhamento = null;
    idUsuarioEncaminhamento = null;
    mensagemEncaminhamento = null;
    dsEncaminhamento = null;
    idEncaminhamentoPadronizado = null;
    arquivosEncaminhamento = new ArrayList<>();

    showRedirectPageModal();
}

Ela é chamada quando uma manifestação é encaminhada para uma unidade, porém no primeiro encaminhamento ocorre tudo ok, mas se tento encaminhar uma segunda manifestação para o mesmo órgão este retorna a mensagem do catch de "Erro ao encaminhar Manifestação.".
No log imprime o seguinte erro:
13:50:46,298 WARN  [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--127.0.0.1-8080-2) SQL Error: 0, SQLState: 23505
13:50:46,298 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--127.0.0.1-8080-2) ERROR: duplicate key value violates unique constraint "uk_6w9ft31ycpj6j9pf1b17k8nw2"
  Detalhe: Key (tbclassificacao_idclassificacao)=(2177) already exists.
13:50:46,300 ERROR [stderr] (http--127.0.0.1-8080-2) javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
13:50:46,300 ERROR [stderr] (http--127.0.0.1-8080-2)    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)

E após estes segue com um monte de mensagens genéricas que nem cabem aqui na caixa de texto, mas pode ser visto aqui: https://pastebin.com/6Lfs8Z6F
A tbClassificacao que está no log é essa:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.xti.ouvidoria.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 *
 * @author samuel.guimaraes
 */
@Entity
@Table(name = "tbClassificacao")
@NamedQueries({
    @NamedQuery(name = "TbClassificacao.findAll", query = "SELECT t FROM TbClassificacao t"),
    @NamedQuery(name = "TbClassificacao.findByIdClassificacao", query = "SELECT t FROM TbClassificacao t WHERE t.idClassificacao = :idClassificacao"),
    @NamedQuery(name = "TbClassificacao.findByUnidade", query = "SELECT t FROM TbClassificacao t WHERE :idUnidade MEMBER OF t.tbUnidadeCollection"),
    @NamedQuery(name = "TbClassificacao.findByDsClassificacao", query = "SELECT t FROM TbClassificacao t WHERE t.dsClassificacao = :dsClassificacao")})
public class TbClassificacao implements Serializable, Comparable<TbClassificacao> {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idClassificacao")
    private Integer idClassificacao;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 180)
    @Column(name = "dsClassificacao")
    private String dsClassificacao;
    @OneToMany
    private Collection<TbUnidade> tbUnidadeCollection = new ArrayList<>();
    @OneToMany
    @JoinTable(
            name="tbClassificacao_tbSubClassificacao",
            joinColumns={@JoinColumn(name="TbClassificacao_idClassificacao", referencedColumnName="idClassificacao")},
            inverseJoinColumns={@JoinColumn(name="tbSubClassificacaoCollection_idSubClassificacao", referencedColumnName="idSubClassificacao")})
    private Collection<TbSubClassificacao> tbSubClassificacaoCollection = new ArrayList<>();
    @OneToMany
    @JoinTable(
            name="tbManifestacao_tbClassificacao",
            joinColumns={@JoinColumn(name="tbClassificacao_idClassificacao", referencedColumnName="idClassificacao")},
            inverseJoinColumns={@JoinColumn(name="TbManifestacao_idManifestacao", referencedColumnName="idManifestacao")})
    private Collection<TbManifestacao> tbManifestacaoCollection = new ArrayList<>();

    public Collection<TbUnidade> getTbUnidadeCollection() {
        return tbUnidadeCollection;
    }

    public Collection<TbManifestacao> getTbManifestacaoCollection() {
        return tbManifestacaoCollection;
    }

    public void setTbManifestacaoCollection(Collection<TbManifestacao> tbManifestacaoCollection) {
        this.tbManifestacaoCollection = tbManifestacaoCollection;
    }

    public void setTbUnidadeCollection(Collection<TbUnidade> tbUnidadeCollection) {
        this.tbUnidadeCollection = tbUnidadeCollection;
    }

    public TbClassificacao() {
    }

    public TbClassificacao(Integer idClassificacao) {
        this.idClassificacao = idClassificacao;
    }

    public TbClassificacao(Integer idClassificacao, String dsClassificacao) {
        this.idClassificacao = idClassificacao;
        this.dsClassificacao = dsClassificacao;
    }

    public Integer getIdClassificacao() {
        return idClassificacao;
    }

    public void setIdClassificacao(Integer idClassificacao) {
        this.idClassificacao = idClassificacao;
    }

    public String getDsClassificacao() {
        return dsClassificacao;
    }

    public void setDsClassificacao(String dsClassificacao) {
        this.dsClassificacao = dsClassificacao;
    }

    public Collection<TbSubClassificacao> getTbSubClassificacaoCollection() {
        return tbSubClassificacaoCollection;
    }

    public void setTbSubClassificacaoCollection(Collection<TbSubClassificacao> tbSubClassificacaoCollection) {
        this.tbSubClassificacaoCollection = tbSubClassificacaoCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idClassificacao != null ? idClassificacao.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof TbClassificacao)) {
            return false;
        }
        TbClassificacao other = (TbClassificacao) object;
        if ((this.idClassificacao == null && other.idClassificacao != null) || (this.idClassificacao != null && !this.idClassificacao.equals(other.idClassificacao))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return String.format("%s > %s", getEntidade(), getDescricao());
    }

    private String getEntidade() {
        return "Classificação";
    }

    private String getDescricao() {
        return dsClassificacao;
    }

    @Override
    public int compareTo(TbClassificacao o) {
        return getDsClassificacao().toUpperCase().compareTo(o.getDsClassificacao().toUpperCase());
    }
}

Estou estranhando muito, a principio era para ser um projeto que estão utilizando e deveria ser apenas instalar e utilizar.
Se alguém quiser conferir o projeto é este: https://github.com/culturagovbr/GOG
Atualização!
Através dos comentários e de alguns testes encontrei um código no script de carga inicial de dados encontrado no próprio projeto deles que exclui e então cria de forma manual a tbclassificacao_tbunidade, tabela que realiza um join com a tbclassificacao e onde ocorre o erro.
--Acertos nos mapeamentos gerados

DROP TABLE tbclassificacao_tbunidade;

CREATE TABLE tbclassificacao_tbunidade
(
  tbclassificacao_idclassificacao integer NOT NULL,
  tbunidadecollection_idunidade integer NOT NULL,
  CONSTRAINT fk107ce929d7b9b0e FOREIGN KEY (tbclassificacao_idclassificacao)
      REFERENCES tbclassificacao (idclassificacao) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk107ce92d27d48b9 FOREIGN KEY (tbunidadecollection_idunidade)
      REFERENCES tbunidade (idunidade) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT tbclassificacao_tbunidade_tbclassificacao_idclassificacao_key UNIQUE (tbclassificacao_idclassificacao, tbunidadecollection_idunidade)
)
WITH (
  OIDS=FALSE
);

Obs: Sem rodar este comando ele nem compila.
Comment: Esses nomes... se você olhar com atenção, ele mostra o nome da constraint naquele trecho de erro: "uk_6w9ft31ycpj6j9pf1b17k8nw2". Nesse script, o nome da constraint é outro, "tbclassificacao_tbunidade_tbclassificacao_idclassificacao_key", então não é nessa tabela do script que deu erro.
Comment: Procure esse nome "uk_6w9ft31ycpj6j9pf1b17k8nw2" no script de instalação e veja se está lá. Se não estiver, veja no postgresql se encontra a tabela desse índice.
Comment: @Dudaskank muito obrigado, esse seu ultimo comentário me ajudou a resolver o erro
Comment: Já tentou alterar na `tbClassificacao` a linha `@GeneratedValue(strategy = GenerationType.IDENTITY)` para `@GeneratedValue(strategy = GenerationType.AUTO)` ?
Comment: Tentei aqui @WéllingthonM.deSouza, mas mesma coisa
Comment: Na verdade com esta modificação ao inserir os dados no banco indica um erro `ERROR:  relation "tbclassificacao_idclassificacao_seq" does not exist
********** Error **********`
Comment: E caso eu exclua a linha `ALTER SEQUENCE tbclassificacao_idclassificacao_seq RESTART WITH 5325;` para evitar o erro, então não acessa o cadastro de manifestações
Comment: informe o primeiro `erro` completo.
Comment: veja se essa resposta no [soEN](https://stackoverflow.com/a/11316361/8353154) pode resolver esse problema do primeiro erro.
Comment: Não me ajuda pois o meu problema está na falta de conhecimento de JSP, e a criação é feita pelo hibernate e não diretamente por SQL
Comment: Esse erro não tem relação com JSP. Precisa encontrar onde você está salvando essa `TbClassificacao`, coloque o resto do stack trace que lá deve apontar o local exato. Outra coisa, esse `ALTER SEQUENCE...` parece indicar que na tabela já existam outras linhas nessa tabela. Se você reinicia o contador e tenta inserir de novo o mesmo `idclassificacao`, vai dar erro mesmo.
Comment: Adicionei um script a questão acima pois descobri que o erro não é na `TbClassificacao` e sim na `tbManifestacao_tbClassificacao` a qual realiza um `join` com a `TbClassificacao`
Comment: @Dudaskank a questão é que várias manifestações podem ser enviadas contendo a mesma classificação, por isso que não poderia existir este erro
Comment: Rapaz, esses nomes confundem... Este script da atualização, você rodou ele já? Segundo ele, a chave única é composta por 2 campos, porém o erro indica que a chave única é só no campo `tbclassificacao_idclassificacao`. E sobre o erro de acesso na tela de manifestações, veja se isso ajuda: https://github.com/culturagovbr/GOG/issues/33
Comment: @Dudaskank esse é outro erro que já tive que enfrentar antes e já resolvi
Comment: @Dudaskank sim esse script faz parte do processo de instalação
Comment: O log de erros completo pode ser visto aqui: https://pastebin.com/6Lfs8Z6F
Comment: @Dudaskank apesar de não estar ali no script o SGBD cria, se ver o código de criação atribuido pelo SGBD a tabela `tbManifestacao_tbClassificacao` está lá `CONSTRAINT uk_6w9ft31ycpj6j9pf1b17k8nw2 UNIQUE (tbclassificacao_idclassificacao),`
Comment: @Dudaskank pode ver aqui https://pastebin.com/XswRHjSN
Comment: @Dudaskank erro meu vc estava falando da `tbclassificacao_tbunidade`e eu da `tbmanifestacao_tbclassificacao`
Answer: Bom, com a muita análise e ajuda de todos que comentaram realmente ficou evidente o erro no fato dq na tabela tbmanifestacao_tbclassificacao o campo tbclassificacao_idclassificacao não poderia ter como requisito ser UNIQUE pois mais de uma manifestação com classificação selecionada igual podem ser encaminhadas para a mesma unidade e esta tabela armazena a classificação escolhida com relação a manifestação.
Assim testei a criação da tabela retirando todas estas dependências, e o encaminhamento funcionou.
Como era:
-- Table: public.tbmanifestacao_tbclassificacao

-- DROP TABLE public.tbmanifestacao_tbclassificacao;

CREATE TABLE public.tbmanifestacao_tbclassificacao
(
  tbmanifestacao_idmanifestacao integer NOT NULL,
  tbclassificacao_idclassificacao integer NOT NULL,
  CONSTRAINT fk_6w9ft31ycpj6j9pf1b17k8nw2 FOREIGN KEY (tbclassificacao_idclassificacao)
      REFERENCES public.tbclassificacao (idclassificacao) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_jbkoiljnamdf9icojnuxaskby FOREIGN KEY (tbmanifestacao_idmanifestacao)
      REFERENCES public.tbmanifestacao (idmanifestacao) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT uk_6w9ft31ycpj6j9pf1b17k8nw2 UNIQUE (tbclassificacao_idclassificacao),
  CONSTRAINT uk_jbkoiljnamdf9icojnuxaskby UNIQUE (tbmanifestacao_idmanifestacao)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.tbmanifestacao_tbclassificacao
  OWNER TO postgres;

Como fiz:
-- Table: public.tbmanifestacao_tbclassificacao

-- DROP TABLE public.tbmanifestacao_tbclassificacao;

CREATE TABLE public.tbmanifestacao_tbclassificacao
(
  tbmanifestacao_idmanifestacao integer NOT NULL,
  tbclassificacao_idclassificacao integer NOT NULL,
  CONSTRAINT fk_6w9ft31ycpj6j9pf1b17k8nw2 FOREIGN KEY (tbclassificacao_idclassificacao)
      REFERENCES public.tbclassificacao (idclassificacao) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_jbkoiljnamdf9icojnuxaskby FOREIGN KEY (tbmanifestacao_idmanifestacao)
      REFERENCES public.tbmanifestacao (idmanifestacao) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT uk_jbkoiljnamdf9icojnuxaskby UNIQUE (tbmanifestacao_idmanifestacao)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.tbmanifestacao_tbclassificacao
  OWNER TO postgres;

Comment: Bom que arrumou. Mas note que, se houver uma manifestação com por exemplo 2 classificações, o erro voltará, pois tem uma constraint ali que diz só pode haver um tbmanifestacao_idmanifestacao de cada nessa tabela.
Comment: @Dudaskank quanto a isso está certo pois a classificação serve como um filtro para o encaminhamento, sendo assim só pode ser selecionada uma classificação, e a nível de interface não tem como selecionar mais
Comment: @Dudaskank esses nomes q eles utilizaram confundem muito mesmo, pretendo modificar, mas seria algo como: unidade = Fundação Municipal de Esportes, classificação = Escolinhas, sub-classificação = Escolinha de Volei, e assim o ouvidor encaminha ao responsável mais próximo do alvo dentro desta hierarquia


Iterating over data structure and nested classes

Question: I have some code below for an iterator but I am having trouble understanding how it works. What specifically confuses me is the public Node<T> front; and the for statement.
Front is a reference to the static nested class and in the for loop we have LinkedList.Node<String> ptr = list.front. The left side of that operation is just accessing the outer class to then access the static nested class which we make ptr reference to. The right side of that operation uses the object of our outer class to access the front reference which is the static nested class as well.
So aren't the left and right side the same thing? Why does the code set one side equal to the other? I know the code provided isn't full - I didn't write it. I'm just trying to understand it.
public class LinkedList<T> {
    public static class Node<E> {
        public E data;
        public Node<E> next;
    }
    public Node<T> front;

    ...code omitted...
}

LinkedList<String> list = new LinkedList<String>();

...code omitted...

for (LinkedList.Node<String> ptr = list.front; ptr != null; ptr = ptr.next) {
    System.out.println(ptr.data);
}

Comment: The for statement essentially starts at the beginning of the Linked List, and while each element is not null, prints out its data and moves on to the next element. See @Matt's answer for a more detailed explanation.
Comment: the code that you included in your question does not make use of a Java iterator. It's a simple for loop used to find the next node in a linked list, and then to print its data.
Comment: Isn't that an iterator in a way?
Comment: An iterator is specifically defined in Java like the following: `Iterator it = list.iterator();` and iterates over values by means of methods such as `hasNext()`, `next()`, and `remove()`. More information here: http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
Comment: Okay I get what you are saying but going back to my question, what is the for statement doing?
Answer: To start, "front" is not a reference to the static nested class.  It's a reference to an "instance" of that class, which is an important distinction.  Think of the class as a template for creating instances.
So at some point, someone would have created the object:
LinkedList<String> list = new LinkedList<String>();
list.front = new LinkedList.Node<String>();
list.front.data = "foo";

And then maybe prepends a node to the list (which is typically how you alter a LinkedList, as appending is expensive)
// Create the new node
LinkedList.Node<String> newNode = new LinkedList.Node<String>();
newNode.data = "bar";
// Since we're prepending, the existing front becomes the next for this node.
newNode.next = list.front;
// This node becomes the front of the list
list.front = newNode;

As for the for statement, think of it as a while loop, which reads a bit easier for people
LinkedList.Node<String> ptr = list.front;
while (ptr != null) {
  // do something
  ptr = ptr.next;
}

To answer your question about the "static" class:
An inner class is just like any other class.  It is just namespaced within the outer class.  There are however two flavors of inner classes.  The static flavor:

Can be instantiated on it's own
Is not related to any particular instance of the outer class

Conversely, a non-static inner class:

Must be instantiated via an instance of it's containing class
Has access to all of the fields and methods of the instance of it's containing class.

Take this code example:
public class Outer {
    private int value = 10;

    public static class StaticInner {

    }

    public class Inner {
        public void foo() {
            System.out.println(value);
        }
    }

    public Inner createInner() {
        return new Inner();
    }

    public static void main(String[] args) {
        Outer outer = new Outer();
        StaticInner staticInner = new StaticInner();
        Inner inner = outer.new Inner();
        Inner inner2 = outer.createInner();
    }
}

In reality, the final two calls of the main method are doing the same thing.  It's that you need a little different syntax to create the instance from outside the containing class.  But you'll notice in both cases, you need have previously created an instance of Outer, whereas to get a StaticInner instance, you did not.
You'll also notice that in the non static one, you're able to access the private field "value" of it's containing instance.
You might want to look here:
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Comment: But if the Node class is static how can we create an instance of it?