Low performance of SVM (and neural network) in out-of-sample data with high test accuracy of 10-fold cross validation in a financial time series

Question: I'm using SVM and (neural network) for a time series prediction data-set in MATLAB R2016a with 800 samples. Currently I'm using 10-fold cross validation and grid search to find best SVM parameters. I'm using 90 samples (after this 800 samples) as out-of-sample to check performance of final model using best SVM (and neural network) parameters and training my model on whole first 800 samples.
The test accuracy of final model (10-fold cross validation) is about 98% (sensitivity and specificity of about 98%) but when I check designed model on last 90 out-of-sample data (which trained using whole first 800 samples) I have a poor accuracy (about 55~59% total accuracy, sensitivity and specificity). This is daily forecasting of a financial market. Why I have this behavior? I checked normal k-fold cross validation and sliding window validation (discussed below in comments). I had mentioned behavior (poor out-of-sample accuracies) in two methods.
Comment: accuracy is not a proper scoring rule, so it will select the wrong model with high probability. Use a proper scoring rule like log-likelihood or brier score.
Comment: @C11H17N2O2SNa. I got same results with `bier score` in SVM model. why? any suggestion?
Answer: You need to use time-series cross-validation to tune your models, rather than random cross-validation.
e.g. (borrowing from Rob Hyndman's blog):
<code>library(fpp) # To load the data set a10
plot(a10, ylab="$ million", xlab="Year", main="Antidiabetic drug sales")
plot(log(a10), ylab="", xlab="Year", main="Log Antidiabetic drug sales")

k <- 60 # minimum data length for fitting a model
n <- length(a10)
mae1 <- mae2 <- mae3 <- matrix(NA,n-k,12)
st <- tsp(a10)[1]+(k-2)/12

for(i in 1:(n-k))
{
  xshort <- window(a10, end=st + i/12)
  xnext <- window(a10, start=st + (i+1)/12, end=st + (i+12)/12)
  fit1 <- tslm(xshort ~ trend + season, lambda=0)
  fcast1 <- forecast(fit1, h=12)
  fit2 <- Arima(xshort, order=c(3,0,1), seasonal=list(order=c(0,1,1), period=12),
      include.drift=TRUE, lambda=0, method="ML")
  fcast2 <- forecast(fit2, h=12)
  fit3 <- ets(xshort,model="MMM",damped=TRUE)
  fcast3 <- forecast(fit3, h=12)
  mae1[i,1:length(xnext)] <- abs(fcast1[['mean']]-xnext)
  mae2[i,1:length(xnext)] <- abs(fcast2[['mean']]-xnext)
  mae3[i,1:length(xnext)] <- abs(fcast3[['mean']]-xnext)
}

plot(1:12, colMeans(mae1,na.rm=TRUE), type="l", col=2, xlab="horizon", ylab="MAE",
     ylim=c(0.65,1.05))
lines(1:12, colMeans(mae2,na.rm=TRUE), type="l",col=3)
lines(1:12, colMeans(mae3,na.rm=TRUE), type="l",col=4)
legend("topleft",legend=c("LM","ARIMA","ETS"),col=2:4,lty=1)
</code>
Comment: Thank you for answer. I used both normal and your proposed cross validation techniques but I have same behavior.
Comment: I used this technique: fold 1 : training [1:n-50], test [n-50:n-40] ~~ fold 2 : training [1+10:n-40], test [n-40:n-30] and so on. This is just an example with imaginary numbers. Is this the same method? If not, please describe more about your technique. I'm not familiar with R.
Comment: I checked porposed method in : http://stats.stackexchange.com/questions/14099/using-k-fold-cross-validation-for-time-series-model-selection but I have same problem.


Is it possible to create a calculation field using database abstraction layer?

Question: I am trying to work out if it is possible to write the following using Drupal's database abstraction layer.  The tricky bit is the second field which is a function to calculate distance.  Is it possible to include this calculation field (3959 * acos(cos(radians(:lat)) * cos(radians(field_bluescope_geolocation_lat)) * cos(radians(field_bluescope_geolocation_lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(field_bluescope_geolocation_lat)))) AS distance using the abstraction layer?
  $result = db_query_range('SELECT '
  . 'geo.entity_id, '
  . '(3959 * acos(cos(radians(:lat)) * cos(radians(field_bluescope_geolocation_lat)) * cos(radians(field_bluescope_geolocation_lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(field_bluescope_geolocation_lat)))) AS distance '
  . 'FROM '
  . 'node__field_bluescope_geolocation AS geo '
  . 'INNER JOIN '
  . 'node__field_bluescope_consumer_supp AS consumer_supp '
  . 'ON '
  . 'geo.entity_id = consumer_supp.entity_id '
  . 'WHERE '
  . 'geo.bundle = \'bluescope_business\' '
  . 'AND '
  . 'consumer_supp.field_bluescope_consumer_supp_target_id = 28 '
  . 'ORDER BY distance', 0, 200, [':lat' => $lat, ':lng' => $lng]);

Answer: Yep Haversine should work without a problem. This is slightly modified from a production site which is up and working right now, for example:
$lat = 51.5014;
$lng = 0.1419;

$query = db_select('field_geo_latitude', 'f')
  ->fields('f', array('entity_id'))
  ->orderBy('distance');

$earth_radius = 3959;
$expr = "(
  $earth_radius * acos(
    cos(radians(:lat))
  * cos(radians(field_geo_latitude))
  * cos(radians(field_geo_longitude) - radians(:lng))
  + sin(radians(:lat))
  * sin(radians(field_geo_latitude))
  )
)";
$query->addExpression($expr, 'distance', array(':lat' => $lat, ':lng' => $long));

$query->having('distance <= :radius', array(':radius' => 10));

Resulting query:
SELECT f.entity_id AS entity_id, (
  3959 * acos(
    cos(radians(:lat))
  * cos(radians(field_geo_latitude))
  * cos(radians(field_geo_longitude) - radians(:lng))
  + sin(radians(:lat))
  * sin(radians(field_geo_latitude))
  )
) AS distance
FROM {field_geo_latitude} f
HAVING  (distance <= :radius)
ORDER BY distance ASC

When executed all the parameters are replaced as expected.
Comment: FWIW, that can be optimized by boxing the results to the square made by the radius, then using the trig for the circle on the reduced set.  See https://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL
Comment: Nice @MPD! Will update when I get a chance


Navigation Drawer for multiple Activities not working on item click

Question: Hey Guys I read this thread a while ago and tried to replicate it since i'm using multiple activities within my app.
I copied all my code for the navigation drawer within my new NavigationDrawerActivity.java which looks like this:

package info.androidhive.navigationdrawer.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import info.androidhive.navigationdrawer.R;
import info.androidhive.navigationdrawer.fragment.CameraFragment;
import info.androidhive.navigationdrawer.fragment.ExposeDetailFragment;
import info.androidhive.navigationdrawer.fragment.HomeFragment;
import info.androidhive.navigationdrawer.fragment.MyAccountFragment;
import info.androidhive.navigationdrawer.fragment.SettingsFragment;

public class NavigationDrawerActivity extends AppCompatActivity {

    public DrawerLayout drawerLayout;
    public NavigationView navigationView;
    public DrawerLayout drawer;
    public View navHeader;
    public TextView txtName;
    public TextView txtWebsite;
    public Toolbar toolbar;

    // index to identify current nav menu item
    public static int navItemIndex = 0;

    // tags used to attach the fragments
    public static final String TAG_HOME = "home";
    public static final String TAG_CAMERA = "camera";
    public static final String TAG_MOVIES = "movies";
    public static final String TAG_MY_ACCOUNT = "myaccoount";
    public static final String TAG_SETTINGS = "settings";
    public static String CURRENT_TAG = TAG_HOME;

    // toolbar titles respected to selected nav menu item
    public String[] activityTitles;

    // flag to load home fragment when user presses back key
    public boolean shouldLoadHomeFragOnBackPress = true;
    public Handler mHandler;

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        drawerLayout = (DrawerLayout) getLayoutInflater().inflate(R.layout.activity_navigation_drawer,null);
        getLayoutInflater().inflate(layoutResID,drawerLayout,true);
        super.setContentView(drawerLayout);

        //DrawerContent here
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mHandler = new Handler();

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.nav_view);

        // Navigation view header
        navHeader = navigationView.getHeaderView(0);
        txtName = (TextView) navHeader.findViewById(R.id.name);
        txtWebsite = (TextView) navHeader.findViewById(R.id.webseite);

        // load toolbar titles from string resources
        activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);

        // load nav menu header data
        loadNavHeader();

        // initializing navigation menu
        setUpNavigationView();

    }

    /***
     * Load navigation menu header information
     * like background image, profile image
     * name, website, notifications action view (dot)
     */
    private void loadNavHeader() {
        // name, website
        txtName.setText("Ravi Tamada");
        txtWebsite.setText("www.androidhive.info");

    }

    /***
     * Returns respected fragment that user
     * selected from navigation menu
     */
    public void loadHomeFragment() {
        // selecting appropriate nav menu item
        selectNavMenu();

        // set toolbar title
        setToolbarTitle();

        // if user select the current navigation menu again, don't do anything
        // just close the navigation drawer
        if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
            drawer.closeDrawers();

            return;
        }

        // Sometimes, when fragment has huge data, screen seems hanging
        // when switching between navigation menus
        // So using runnable, the fragment is loaded with cross fade effect
        // This effect can be seen in GMail app
        Runnable mPendingRunnable = new Runnable() {
            @Override
            public void run() {
                // update the main content by replacing fragments
                Fragment fragment = getHomeFragment();
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                        android.R.anim.fade_out);
                fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
                fragmentTransaction.commitAllowingStateLoss();
            }
        };

        // If mPendingRunnable is not null, then add to the message queue
        if (mPendingRunnable != null) {
            mHandler.post(mPendingRunnable);
        }

        /*FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Click action
                Intent intent = new Intent(NavigationDrawerActivity.this, NewExposeActivity.class);
                startActivity(intent);
                Toast.makeText(getApplicationContext(), "Ein neues Exposé erstellen", Toast.LENGTH_LONG).show();
            }
        });*/

        //Closing drawer on item click
        drawer.closeDrawers();

        // refresh toolbar menu
        invalidateOptionsMenu();
    }

    public Fragment getHomeFragment() {
        switch (navItemIndex) {
            case 0:
                // home
                HomeFragment homeFragment = new HomeFragment();
                return homeFragment;
            case 1:
                // expose List
                HomeFragment homeFragment1 = new HomeFragment();
                return homeFragment1;
            case 2:
                //Camera fragment
                CameraFragment cameraFragment = new CameraFragment();
                return cameraFragment;
            case 3:
                // notifications fragment
                MyAccountFragment myAccountFragment = new MyAccountFragment();
                return myAccountFragment;
            case 4:

                // settings fragment
                SettingsFragment settingsFragment = new SettingsFragment();
                return settingsFragment;
            default:
                return new HomeFragment();
        }
    }

    public void setToolbarTitle() {
        getSupportActionBar().setTitle(activityTitles[navItemIndex]);
    }

    public void selectNavMenu() {
        navigationView.getMenu().getItem(navItemIndex).setChecked(true);
    }

    public void setUpNavigationView() {
        //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            // This method will trigger on item Click of navigation menu
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                //Check to see which item was being clicked and perform appropriate action
                switch (menuItem.getItemId()) {
                    //Replacing the main content with ContentFragment Which is our Inbox View;
                    case R.id.home:
                        navItemIndex = 0;
                        CURRENT_TAG = TAG_HOME;
                        break;
                    case R.id.nav_camera:
                        navItemIndex = 1;
                        CURRENT_TAG = TAG_CAMERA;
                        break;
                    case R.id.nav_movies:
                        navItemIndex = 2;
                        CURRENT_TAG = TAG_MOVIES;
                        break;
                    case R.id.nav_my_account:
                        navItemIndex = 3;
                        CURRENT_TAG = TAG_MY_ACCOUNT;
                        break;
                    case R.id.nav_settings:
                        navItemIndex = 4;
                        CURRENT_TAG = TAG_SETTINGS;
                        break;

                    case R.id.nav_rss:
                        startActivity( new Intent(NavigationDrawerActivity.this, RSSFeedActivity.class));
                        drawer.closeDrawers();
                        return true;
                    case R.id.nav_login:
                        startActivity( new Intent(NavigationDrawerActivity.this, LoginActivity.class));
                        drawer.closeDrawers();
                        return true;

                    default:
                        navItemIndex = 0;
                }

                //Checking if the item is in checked state or not, if not make it in checked state
                if (menuItem.isChecked()) {
                    menuItem.setChecked(false);
                } else {
                    menuItem.setChecked(true);
                }
                menuItem.setChecked(true);

                loadHomeFragment();

                return true;
            }
        });

        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
                super.onDrawerOpened(drawerView);
            }
        };

        //Setting the actionbarToggle to drawer layout
        drawer.setDrawerListener(actionBarDrawerToggle);

        //calling sync state is necessary or else your hamburger icon wont show up
        actionBarDrawerToggle.syncState();
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawers();
            return;
        }

        // This code loads home fragment when back key is pressed
        // when user is in other fragment than home
        if (shouldLoadHomeFragOnBackPress) {
            // checking if user is on other navigation menu
            // rather than home
            if (navItemIndex != 0) {
                navItemIndex = 0;
                CURRENT_TAG = TAG_HOME;
                loadHomeFragment();
                return;
            }
        }

        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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 Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.add_expose) {
            Toast.makeText(getApplicationContext(), "Ein neues Exposé soll erstellt werden!", Toast.LENGTH_LONG).show();

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

and here the activity_navigation_drawer.xml:

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" >

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

</android.support.v4.widget.DrawerLayout>

here is the activity_navigation_drawer.xml which is menu Ressource file:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/nav_home" />
        <item
            android:id="@+id/nav_camera"
            android:icon="@mipmap/ic_list_black_24dp"
            android:title="@string/nav_photos" />
        <item
            android:id="@+id/nav_movies"
            android:icon="@mipmap/ic_camera_alt_black_24dp"
            android:title="@string/nav_movies" />

        <item
            android:id="@+id/nav_my_account"
            android:icon="@mipmap/ic_person_black_24dp"
            android:title="Mein Account" />

        <item
            android:id="@+id/nav_settings"
            android:icon="@mipmap/ic_settings_black_24dp"
            android:title="@string/nav_settings" />
    </group>

    <item android:title="Other">
        <menu>

            <item
                android:id="@+id/nav_rss"
                android:title="News"
                android:icon="@mipmap/ic_rss_feed_black_24dp" />

            <item
                android:id="@+id/nav_login"
                android:title="@string/action_logout"
                android:icon="@mipmap/ic_lock_black_24dp" />
        </menu>
    </item>

</menu>

It's working great up to the fact that when i click an item in the navigation nothing happens. Are there any suggestions to what I'm doing wrong.
You can find the whole project here.
Thanks for your help.
Comment: nothing happens because you have not coded what should happen. you are starting activity for only `R.id.nav_rss` and `R.id.nav_login`
Comment: @Saurabh so you are saying that i need to put the first 4 into activities as well and not use fragments? i'm kinda confused now
Answer: First , post a reference or code to how you are creating the menu item , do u create it in the resources menu file or simply load an array , If you are using array then i would suggest you to use menu xml to create menu items.
Something like this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"
          android:icon="@drawable/ic_new_game"
          android:title="@string/new_game"
          android:showAsAction="ifRoom"/>
    <item android:id="@+id/help"
          android:icon="@drawable/ic_help"
          android:title="@string/help" />
</menu>

also make corresponding changes in ur code,check
https://developer.android.com/guide/topics/ui/menus.html
https://developer.android.com/training/implementing-navigation/nav-drawer.html
Comment: i added the code snippet. it is an menu ressource file that adds the menu


Help with approaching "advanced" Big-O problems

Question: So an "advanced" problem in my mind may be easy to you but I am just starting to learn this so bare with me.
I want to find the best Big-O of the following problems:

$(15n+logn)^3$
$n^2logn + n + \sqrt n + logn$

When I look at these problems I find myself in an existential crisis, compared to problems like
Find best Big-O of $100n^2 + n$
Which is straightforward, in my mind.
I guess the part that trips me up is what do I do with the $log$'s and the $\sqrt n$'s?
I am just looking for advice on solving these problems. If you believe that solving for Big-O of the two problems listed will help me understand, then by all means solve them with explanations at each step but I am seeking help with approaching and understand what my first move should be with these problems. Thank you!
Comment: the definition is clear to you? you might want to add it anyway. For the first one consider to expand the term
Comment: When in doubt, you can just plug in a large value of $n$, say $n = 10^6$, and see what you get (e.g. using WolframAlpha). This will help you notice which terms dominate the asymptotic behavior and which terms you can ignore. When $n = 10^6$ we have that $n^2 = 10^{12}$ while $\sqrt{n} = 10^3$ and $\log_{10} n = 6$. So... which of these terms seems to be dominating?
Answer: $\log(n)$ is smaller than any positive power of $n$. The $\sqrt{n} = n^{1/2}$ is smaller than $n$ but larger than $\log(n).$ If you had $n^{1/4}$ it would be smaller than $n^{1/2}$ or $n$ but larger than $\log(n).$
The second $n^2\log(n) + n+\sqrt{n}+\log(n)$ is probably the easiest to do since the terms are all there for you and you just need to find which one dominates. Of the last three $n,$ $\sqrt{n}$ and $\log(n),$ $n$ is the largest per last paragraph. But is it larger than $n^2\log(n)$? Well, $n^2\log(n)$ is larger than $n^2,$ so it's certainly larger than $n.$
For the first $ (15n+\log(n))^3$ you can multiply it out, and then you have four terms to compare. Or note that the $n$ term dominates the $\log(n)$ term, and infer which of the four terms is going to be the leading order.
Answer: One simple fact that will help you most big-O problems we encounter in practice:
$n^\alpha$ is larger (in big-O sense) than $\log n$ for any $\alpha > 0$. $n^{1/2}, n^{1/3}, n^{1/10},$ and so on, are all larger than $\log n$.
spaceisdarkgreen's answer shows how to use this fact.
Answer: The limit test is a helpful formalism. Let $f, g : \mathbb{N} \to \mathbb{N}$ be functions. Let:
$$L := \lim_{n \to \infty} \frac{f(n)}{g(n)}$$
If:

$L = 0$, then $f(n) \in o(g(n))$. Note that this is little-o vs. Big-O, which is a stronger condition. Now if $f(n) \in o(g(n))$, then $f(n) \in O(g(n))$.
$0 < L < \infty$, then $f(n) \in \Theta(g(n))$, so $f(n) \in O(g(n))$.
$L = \infty$, then $f(n) \in \omega(g(n))$, which implies that $f(n) \in \Omega(g(n))$. Note that if $f(n) \in \Omega(g(n))$, then $g(n) \in O(f(n))$.

Now for your example. Let $f(n) = (15n + \log(n))^{3}$ and let $g(n) = n^{3}$. We have that:
$$\lim_{n \to \infty} \frac{f(n)}{g(n)} = 15^{3}$$
So $f(n) \in \Theta(g(n))$, which implies that $f(n) \in O(g(n))$.
As you do more of these problems, you will develop better intuition for how to eyeball the dominant term. It is always nice/important to be able to formally prove your intuition, though.


How to redirect programatically using a route with parameters?

Question: I am trying to use the Passwordless module API to redirect the user on login.
I want to redirect the user to a specific node edit page (node/12/edit).
In hook_passwordless_login_redirect(), the module redirects the user with this code:
return $this->redirect($redirect);
So here is my implementation:
function MYMODULE_passwordless_login_redirect_alter(&$redirect) {
  // You can use hasPermission() with currentUser, but need to load for hasRole()
  $account = \Drupal\user\Entity\user::load(\Drupal::currentUser()->id());
  $test = \Drupal::service('path.validator')->getUrlIfValid('node/12/edit');
  if (!($account->hasRole('admin'))) {
    $redirect= $test->getRouteName();
  }

The problem is that I get this error:

Some mandatory parameters are missing ("node") to generate a URL for
  route "entity.node.edit_form".

The missing route parameter is the node id, which I can get with $test->getRouteParameters().  But how do I pass this to the redirect?  (How do I call the redirect and give it both the route name and the route parameters?)
Comment: This module is probably using [UrlGeneratorTrait::redirect](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Routing%21UrlGeneratorTrait.php/function/UrlGeneratorTrait%3A%3Aredirect/8.4.x). Then you are out of luck, because the route parameters are the second parameter, which is not offered in the alter hook.
Answer: As pointed out by @4k4, the problem is that the module did not ask for the route parameters, so I patched it.
Then you can call the redirect like this:
  if (!($account->hasRole('admin'))) {
    $routename = $test->getRouteName();
    $routeparameters= $test->getRouteParameters();
  }

Answer: You can pass parameters like below:
$url = \Drupal\Core\Url::fromRoute(
    $test->getRouteName(),
     array(
       'query' => array('query1' => 'YOUR QUERY'),
       'absolute' => TRUE,
     )
);


Java Generics Inferred Types

Question: Ok, so I am implementing the state monad in java. However, I can't seem to get the generics to work right. I have the code below, and am trying to avoid the cases indicated.
public interface Monad<M, A>
{
    <B, R extends Monad<M, B>> R bind(Function<? super A, R> p_function);
}

public class State<S, A> implements Monad<State<S, ?>, A>
{
    private Function<S, Pair<S, A>> m_function;

    public State(Function<S, Pair<S, A>> p_function)
    {
        m_function = p_function;
    }

    public final Pair<S, A> run(S p_state)
    {
        return m_function.apply(p_state);
    }

    @Override
    public <B, R extends Monad<State<S, ?>, B>> R bind(
            final Function<? super A, R> p_function)
    {
        // I want to avoid the cast to R here
        return (R) new State<S, B>((S state) -> {
            Pair<S, A> run = run(state);
            // And this cast, but they seem related
            State<S, B> applied = (State<S, B>) p_function.apply(run.second());
            return applied.run(run.first());
        });
    }
}

Note: I am aware that if I cange the signature of bind to
 Monad<M, B> bind(Function<? super A, ? extends Monad<M, B>> p_function);
 The cast can be avoided. However, this causes a compile error in the following method
public static <A, B, C, M, MB extends Monad<M, B>, MC extends Monad<M, C>>
Function compose(
        Function<? super A, MB> p_first, Function<? super B, MC> p_second)
{
    // have to use an anonymous class here, because using a closure causes a
    // runtime error with the beta version of JDK 8
    return new Function() {

        @Override
        public MC apply(A arg) {
            MB monadOfB = p_first.apply(arg);
            return monadOfB.<C> bind(p_second); // <-- type error here
        }
    };
}

Now, I also tried changing the signature of compose in a similar manner. i.e. rather than MB extends Monad<M, B> I used Monad<M, B> where MB was used and similarly for MC. This makes the compose method compile. However, then the return type could not be correctly inferred by the callers of compose i.e.
Function<String, State<Integer, String>> left = ...;
Function<String, State<Integer, String>> right = ...;
Function<String, State<Integer, String>> composed = Monad.compose(left, right);

Doesn't work without specifying the types on the method call, whereas before it did.
How do I make all these generics play nicely together?
Comment: Can OP simplify your question by making up something that is simple and can demonstrate your problem?  There are simply too much "noise" in your code and I think no one actually get your problem clearly
Comment: @f1sh: Well, if `State extends Monad` (add generics at will) it might work.
Comment: Can you add the definitions of `State` and `Monad`?
Comment: @AdrianShum My attempt to simplify is below (with more edits after reading the most recent edits in OP's question).
Comment: I can't seem to understand how the first one works?
Comment: The line ``msb = sb;`` assigns these types: ``Monad, B> = State;``, that cannot work. So your comment stating "works fine" is already wrong.
Comment: The universe is collapsing under my roof tonight!!
Comment: Sorry yes state extends monad. I missed adding that. I'll update the post.
Comment: @ekj You should state what you exactly need and why my answer does not work for you (for some reason the whole trail of comments has been deleted...).
Comment: I originally had the exact opposite request - to provide more detail - so I did.
Answer: For your example to work, you need your classes to be defined similarly to:
class State<S, B> extends Monad<State<S, ?>, B> {}
class Monad<T, U> {}

R is a subclass of Monad<State<S, ?>, B>, and sb is a subclass of Monad<State<S, ?>, B> too, but there is no reason that it also is a R.
It is like writing:
Number n = 123.5d;
Integer i = n; //does not compile: cast required
Integer j = (Integer) n; //throws an exception

EDIT
I'm not familiar with what you are trying to achieve, and this simplication might not achieve your aim, but it would compile (I have removed the lambdas as I don't have a jdk8 compiler installed at the moment):
public class Test1 {

    public static  Function<A, Monad<M, C>> compose(final Function<? super A, Monad<M, B>> p_first,
                                                                final Function<? super B, Monad<M, C>> p_second) {
        // have to use an anonymous class here, because using a closure causes a runtime error
        // with the beta version of JDK 8
        return new Function<A, Monad<M, C>>() {
            @Override
            public Monad<M, C> apply(A arg) {
                Monad<M, B> monadOfB = p_first.apply(arg);
                return monadOfB.bind(p_second); // <-- type error here
            }
        };
    }
}

interface Monad<M, A> {

     Monad<M, B> bind(Function<? super A, Monad<M, B>> p_function);
}

class State<S, A> implements Monad<State<S, ?>, A> {

    private Function<S, Pair<S, A>> m_function;

    public State(Function<S, Pair<S, A>> p_function) {
        m_function = p_function;
    }

    public final Pair<S, A> run(S p_state) {
        return m_function.apply(p_state);
    }

    @Override
    public  Monad<State<S, ?>, B> bind(final Function<? super A, Monad<State<S, ?>, B>> p_function) {
        // I want to avoid the cast to R here
        return new State<S, B>(new Function<S, Pair<S, B>>() {
            public Pair<S, B> apply(S state) {
                Pair<S, A> run = run(state);
                // And this cast, but they seem related
                State<S, B> applied = (State<S, B>) p_function.apply(run.second());
                return applied.run(run.first());
            }
        });
    }
}

Comment: Worth noting that the OP was not satisfied with the proposal as it removes one layer of generics.
Answer: (I'm +1'ing jacobm's answer, I just wanted to elaborate a bit on the underlying problem.)
The problem is that in Java, there is no particular relationship between GenericClass<S> and GenericClass<T>: I mean, both are subtypes of GenericType<?>, but there's no way that GenericInterface<T> can refer to the type you'd get by taking getClass() and substituting T for S.
In Haskell, the definition of the Monad typeclass looks like this:
class Monad m where
    (>>=)  :: m a -> (a -> m b) -> m b
    return :: a -> m a

Note that it defines m by using both m a and m b, meaning "the same parameterized type m, with (potentially) different type-arguments a and b". In Java you can't create a supertype of m (that is, an interface for m) that expresses this sort of thing, because while the supertype can refer to itself with arbitrary type-parameters (because it can refer to itself by name, just like how it could use any other generic type), and can refer to an arbitrary subtype with any single type-argument (namely its own), it has no way to refer to an arbitrary subtype with an arbitrary type-parameter. It doesn't sit "outside" the type system in the way that a Haskell typeclass definition does.
This means that there's no real way to define a generic Monad interface whose implementations are generic monadic types.
Comment: @ekj: You can implement any *specific* monad, but yeah, you can't express the *concept* of monads using only the static type system. (But Java has a "runtime type" system as well. With some cleverness, and a few redundant `Class` fields on various types to keep track of their type parameters, you can probably arrange things so that all of your casts actually get checked.)
Comment: That's an interesting point, and one that I was aware of, but your description crytlised the concept for me. In my implementation I attempt to work around this by having the monad interface take two type parameters; M the monad type itself and A the wrapped type.
Comment: @ekj: Yes, I saw that, but the problem is that your `M` type parameter somehow needs to announce "I'm generic! give me a type argument! (and `M` is special!)", and Java generics simply don't offer any way to mark a type parameter as generic, nor (therefore) to pass a type parameter *to* a type argument. You tried to work around this by using a wildcard, so e.g. `Maybe` would be a `Monad, A>`, but then you ran afoul of the lack of type information encoded in that wildcard.
Comment: Hmm... Yes, it is that wild card producing the problem isn't it. It seems that I am hitting the limits of the java type system. Based on my reading, I thought I could implement monads without needing higher order kinds. Is this not the case?
Answer: Here's a version that passes the Java 7 type checker:
class State<S, A> implements Monad<State<S, ?>, A> {
    private Function<S, Pair<S, A>> m_function;

    public State(Function<S, Pair<S, A>> p_function)
    {
        m_function = p_function;
    }

    public final Pair<S, A> run(S p_state)
    {
        return m_function.apply(p_state);
    }

    @Override
    public  Monad<State<S, ?>, B> bind(
            final Function<? super A, ? extends Monad<State<S, ?>, B>> p_function) {
        return new State<S, B>(
                new Function<S, Pair<S,B>>() {
                    public Pair<S,B> apply(S state) {
                        Pair<S, A> run = run(state);
                        // And this cast, but they seem related
                        State<S, B> applied = (State<S, B>) p_function.apply(run.second());
                        return applied.run(run.first());
                    }
        });
    }

    public static
    Function<A, Monad<M,C>> compose(
            final Function<? super A, ? extends Monad<M,B>> p_first,
            final Function<? super B, ? extends Monad<M,C>> p_second) {
        return new Function<A, Monad<M,C>>() {
            @Override
            public Monad<M,C> apply(A arg) {
                Monad<M,B> monadOfB = p_first.apply(arg);
                return monadOfB.<C>bind(p_second);
            }
        };
    }
}

The problem with your original code was that you wanted to pick a particular instantiation for R but your signature allowed the caller to pick it. The signature <B, R extends Monad<State<S, ?>, B>> R bind(final Function<? super A, R> p_function) lets the caller choose an arbitrary subtype of Monad<State<S, ?>,B> and demand that bind return it. Your bind implementation didn't do that, though: it decided to always return a particular subtype of R of your choosing. So your signature was promising one thing, but your implementation was doing another.
My fix removes that promise. Instead of allowing the caller to choose a particular Monad<State<S,?>,B> subtype, the revised signature just promises to return some subtype -- which in this case means I can dispense with the generic variable entirely and just substitute the upper bound type directly in the signature.
A similar problem affected the compose method -- allowing the caller to choose MB and MC types, but then expecting to be able to produce your own choice of subtypes for MB and MC in the implementation. I fixed that in a similar way.
Comment: Yes, I mention that I have tried this solution. However, it results in the type parameters having to be specified when the compose method is called. See the last code snippet in my post
Comment: Ah, missed that, sorry.
Answer: Tell me if this simplification is still representative of your question:
The following compiles:
public class TestClass {
    public interface Monad {
        <R extends Monad> R bind();
    }

    public class State implements Monad {
        @Override
        public <R extends Monad> R bind() {
            return (R) new State(); // [1]
        }
    }

    public <M extends Monad> M apply() {
        M subMonad = null;
        return subMonad.bind();
    }
}

You want to remove the cast from [1].  If you do it this way:
public class TestClass {
    public interface Monad {
        Monad bind();
    }

    public class State implements Monad {
        @Override
        public Monad bind() {
            return new State();
        }
    }

    public <M extends Monad> M apply() {
        M subMonad = null;
        return subMonad.bind(); // [2]
    }
}

Then [2] doesn't compile.  Does this sum it up?  If so, can the apply() method simply return a Monad?
Comment: Yeah, I got that part... but what I really want is some pointer on how to make all my generics play nice together
Comment: That solution (return Monad from apply) is exactly what @jacobm suggested above, just in a simpler form. This poses other problems, see the last code snippet in my post.

Java Generics Inferred Types


Apurar classificação do artigo com base nas visualizações de todos os artigos

Question: A ideia é apurar a reputação de determinado artigo com base nas visualizações de todos os artigos existentes.
Um artigo pode ter a reputação de 1 a 5 estrelas, sendo a mesma constantemente mutável com base nas visualizações registadas para todos os artigos.
O objetivo é atribuir mais estrelas ao artigo mais visualizado, sabendo que as estrelas atribuídas são calculadas em tempo real mediante a visualização registada até ao momento em todos os artigos em catálogo.
MySQL
Para o efeito, sempre que um artigo é visualizado, é registada a visualização numa tabela:
DESCRIBE `product__statistic_views`

┌───────────────┬───────────┬──────┬─────┬─────────────────────┬────────────────┐
│ Field         │ Type      │ Null │ Key │ Default             │ Extra          │
├───────────────┼───────────┼──────┼─────┼─────────────────────┼────────────────┤
│ id            │ int(13)   │ NO   │ PRI │ NULL                │ auto_increment │
├───────────────┼───────────┼──────┼─────┼─────────────────────┼────────────────┤
│ product_id    │ int(13)   │ NO   │ MUL │ 0                   │                │
├───────────────┼───────────┼──────┼─────┼─────────────────────┼────────────────┤
│ session_id    │ char(100) │ NO   │ MUL │ old-na              │                │
├───────────────┼───────────┼──────┼─────┼─────────────────────┼────────────────┤
│ page_views    │ int(13)   │ NO   │ 0   │                     │                │
├───────────────┼───────────┼──────┼─────┼─────────────────────┼────────────────┤
│ date_created  │ datetime  │ NO   │ MUL │ 0000-00-00 00:00:00 │                │
└───────────────┴───────────┴──────┴─────┴─────────────────────┴────────────────┘

Exemplo de um registo:
┌────┬────────────┬──────────────────────────────────┬────────────┬─────────────────────┐
│ id │ product_id │ session_id                       │ page_views │ date_created        │
├────┼────────────┼──────────────────────────────────┼────────────┼─────────────────────┤
│ 2  │ 37         │ 153dd95d83bc6a6691a4c3bab42215c9 │ 3          │ 2014-12-02 18:47:17 │
└────┴────────────┴──────────────────────────────────┴────────────┴─────────────────────┘

Isto diz-nos que o artigo #37 tem um visitante único, cujo mesmo visualizou o produto 3 vezes na mesma sessão.
PHP
No lado do PHP, a informação é processada da seguinte forma:
/**
 * Product Rating
 *
 * Prepare the necessary HTML to present the product
 * rating stats based on their views count while
 * compared to all products views.
 *
 * @param integer $count Product views count.
 * @param integer $grandTotal Sum of all products views.
 *
 * @return string $returnHtml HTML ready to be used.
 */
public function productRating($count=0, $grandTotal=0) {

    $returnHtml = '

    ';

    if (intval($count)>=1) {

        $rating = number_format( ceil( ( ($count*100) / $grandTotal ) / 20 ), 0);

        if ($rating>0) {

            $returnHtml = '';

            for ($i=0; $i<$rating; $i++) {
                $returnHtml.= '';
            }

            for ($i=5; $i>$rating; $i--) {
                $returnHtml.= '';
            }
        }
    }

    return $returnHtml;
}

Exemplo de utilização:
/* Visualizações são únicas, pelo que o total de visualizações do produto é uma
 * contagem dos registos com o seu ID na tabela em cima, e o total de visualizações
 * de todos os produtos é uma contagem de todos os registos na tabela em cima referida.
 */
$ratingHtml = $this->productRating(1, 10);

HTML
O resultado será algo parecido com isto:

Pergunta
Para o que foi descrito, a função que trata de apurar a classificação de cada produto está a desempenhar o seu trabalho de forma eficiente?
Poderá todo este processo ser simplificado?
Comment: Me explica o seguinte: aquele artigo que tiver maioria de views sobre todos os demais recebe 5 estrelas? Ou é uma questão de porcentagem? os que tiverem maior porcentagem de views em relação ao total recebem 5 estrelas... não entendi a divisão por 20 ali no código
Comment: @touchmx A grosso modo, cada estrela equivale a 20%. Se o produto estiver de 80% para cima, leva 5 Estrelas. De notar que o código pode estar 100% errado, daí esta pergunta a pedir revisão do mesmo.
Answer: Se compreendi o código corretamente, esse método deverá gerar um valor muito baixo para cada produto, já que nenhum terá 100% das visualizações que você passa em $grandTotal. Uma maneira alternativa de calcular seria comparar com o produto que tem mais visualizações, em vez de comparar com a soma de todas as views. Em SQL, isso poderia ser feito assim:
SELECT
  product_id,
  page_views,
  CEIL((page_views / (SELECT MAX(page_views) FROM product__statistic_views)) * 100) AS percentual
FROM product__statistic_views
-- WHERE product_id = ? /* para filtrar por produto se necessário */

http://sqlfiddle.com/#!2/93913/4
Esse método ainda teria o problema de gerar valores baixos para todos os produtos novos, que geralmente tendem a ter poucas views. Você poderia utilizar alguma data de referência para minimizar isso. Por exemplo, para comparar um produto com os que foram cadastrados até 7 dias antes dele (considerando que date_created é a data de cadastro):
SELECT
  product_id,
  page_views,
  CEIL((page_views / (SELECT MAX(page_views) FROM product__statistic_views WHERE date_created BETWEEN DATE_SUB(date_created, INTERVAL 7 DAY) AND date_created)) * 100) AS percentual
FROM product__statistic_views
-- WHERE product_id = ? /* para filtrar por produto se necessário */

Answer: O cálculo está perfeito, o que creio está errado é o fato de a variável $returnHtml ser iniciada com estrelas. Nesse caso, me parece que serão exibidas mais de 5 estrelas. Então creio que o correto seja o seguinte:
/**
 * Product Rating
 *
 * Prepare the necessary HTML to present the product
 * rating stats based on their views count while
 * compared to all products views.
 *
 * @param integer $count Product views count.
 * @param integer $grandTotal Sum of all products views.
 *
 * @return string $returnHtml HTML ready to be used.
 */
public function productRating($count=0, $grandTotal=0) {

    $returnHtml = '';

    if (intval($count)>=1) {

        $rating = number_format( ceil( ( ($count*100) / $grandTotal ) / 20 ), 0);

            for ($i=1; $i<=5; $i++) {
                if($i <= $rating){
                   $returnHtml .= '';
                }else{
                   $returnHtml .= '';
                }
            }

        }else{
           $returnHtml = '

           ';

        }

    return $returnHtml;
}

estou assumindo que a classe fa-star-o é a estrela desativada, a cinza que você mostrou no exemplo.
Comment: Assumiste de forma correta em relação às cores! Mas, a variável `$returnHtml` tem estrelas _desativadas_ porque se o parâmetro `$count` for 0 (zero), a ideia é ter estrelas, embora vazias. De acordo com a tua sugestão, se `$count===0` vamos ficar sem estrelas no produto porque não passa do primeiro controlo `if (intval($count)>=1) {...}`.
Comment: Entendi, vou editar. a mudança é simples.
Comment: Agora está correto, faça um teste e me de um feedback.


VBA não reconhece valores

Question: Estou tentando pegar valores do tipo data de determinada célula do excel, porém, minha macro não reconhece os valores da célula, mesmo ela estando preenchida (data). Lembrando que são três sheets.
<code>  With Worksheets("TEMP")
    ActiveWorkbook.Sheets("TEMP").Activate
    minDate = WorksheetFunction.Min(Worksheets("TEMP").Range("F2:F65000"))
    maxDate = WorksheetFunction.Max(.Range(.Range("F2"), .Range("F65000")))
    numMonths = 1 + DateDiff("m", minDate, maxDate)
    If (numMonths < 3) Then
        countMonths = 3
    Else
        countMonths = numMonths
    End If
End With
</code>
O minDate e maxDate retornam como 0, apenas quando eu manualmente, clico sobre a célula e aperto Enter ou clico em outra celula a macro reconhece, apenas aquela célula.
Como fazer com que a macro reconheça aquele valor?
Comment: Seus `.Range` na quarta linha estão errados. Você deveria fazer igual a função de cima. O `minDate` funciona corretamente para mim.
Comment: Na verdade ambos funcionam quando eu clico em alguma célula manualmente e aperto enter ou clico em outra célula. O problema é a célula "inativa".
Answer: <code>Public Sub Teste()
  Dim MinDate As Date
  Dim MaxDate As Date
  MinDate = WorksheetFunction.Min(Sheets("Plan1").Range("A1:A100"))
  MaxDate = WorksheetFunction.Max(Sheets("Plan1").Range("A1:A100"))
  Debug.Print MinDate
  Debug.Print MaxDate
End Sub
</code>
Funcionou perfeitamente, verifique se os dados foram inseridos como data no intenvalo, caso não for, faça uma conversão.

VBA não reconhece valores


Allowed column type names and element type names for creating custom Field Types

Question: I'm creating new Field Types in Drupal 8.
I recently asked which are the type names allowed for the DataDefinition::create() method, receiving a good answer.
Now I figured out that I need at least other two type names:

A column type name to use inside the method schema(...) from the FieldItemBase class.
Another type name to create elements inside the method formElement(...) from the class WidgetBase.

For example this is a snippet of code used to create a new Field Type, defining the schema() method:
public static function schema(FieldStorageDefinitionInterface $fd) {

  $columns = array(

    //

    // Here the column type name is 'varchar'
    'password' => array(
      'description' => 'A plain text password.',
      'type' => 'varchar',
    ),

    //

  );

  $schema = array(
    'columns' => $columns,
    'indexes' => array(),
    'foreign keys' => array(),
  );

  return $schema;
}

In the above code the column type name is 'varchar'.
And this is another snippet, defining the formElement method (always used defining the Field Type):
public function formElement(
  FieldItemListInterface $items,
  $delta,
  array $element,
  array &$form,
  FormStateInterface $form_state
) {

  //

  // Here the element type name is 'password'
  $element['passwordlist'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Select a password for the user'),
  );

  //

  return $element;
}

In the above code the element type name is 'password'.
What can I use for 'type' in the first case and '#type' in the second case?
Answer: All available schema types are listed in the following table:
https://www.drupal.org/node/159605
Here is a list of available types of render elements (first column of the table corresponds to the #type property of the element)
https://api.drupal.org/api/drupal/elements


NoMethodError in Application#angular devise current_user?

Question: I'm trying to build a follow user feature in my app using Railstutorial.org and I'm hitting a error that doesn't make a lot of sence to me.
In my applicaion.html.haml I render 2 partials,
= render '../assets/javascripts/angular-app/templates/stats'
= render '../assets/javascripts/angular-app/templates/follow_form' if user_signed_in?

The first partial (stats) is this,
- @user ||= current_user
.stats
  %a{:href => following_user_path(@user)}
    %strong#following.stat
      = @user.following.count
    following
  %a{:href => followers_user_path(@user)}
    %strong#followers.stat
      = @user.followers.count
    followers

And resolves without error,
The second partial is this,
- unless current_user?(@user)
  #follow_form
    - if current_user.following?(@user)
      = render 'unfollow'
    - else
      = render 'follow'

And throws an error, NoMethodError in Application#angular
Showing /home/alucardu/sites/movieseat/app/assets/javascripts/angular-app/templates/_follow_form.html.haml where line #1 raised:

undefined method `current_user?' for #<#    <Class:0x007fbe544651f8>:0x007fbe64cdbb10>

I'm using Devise for my registration and user handeling.
On my application.html.haml I have
.welkom
  Welkom
  = current_user.name

And this hows my first and last name and in the first partial I also use current_user so why am I getting the error undefined methodcurrent_user?'`
Comment: possible duplicate of [Rails Michael Hartl Tutorial + Devise current\_user?](http://stackoverflow.com/questions/16797816/rails-michael-hartl-tutorial-devise-current-user)
Comment: Yup looks the same, the answers there helped me out. Thanks for he input.
Answer: There's no current_user? method in devise, if you want to check whether there's a current user or not you can use user_signed_in? method


React Native project can't be open with android emulator

Question: I'm a newbie to react native. I started a new project and followed all the steps. I had Android Studio before and I started the emulator with it. After running npx react-native run-android command I get this error.
**FAILURE: Build failed with an exception.
* What went wrong:
Task 'installDebug' not found in project ':app'.
* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 34s
error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup. Run CLI with --verbose flag for more details.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
FAILURE: Build failed with an exception.
* What went wrong:
Task 'installDebug' not found in project ':app'.
* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug
option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 34s**

Then I ran abd -d command and I get this.
Android Debug Bridge version 1.0.41
Version 29.0.6-6198805
Installed as C:\Users\User\AppData\Local\Android\Sdk\platform-tools\adb.exe

Can you please help me with this?
Answer: As said here, you can try running the following command on the root folder of your project:
cd android  && ./gradlew installDevDebug && cd .. && react-native run-android --variant=DevDebug
After this your project should run on your Android sucessfully.
If not, open your project with android studio one time, and then recompile with react-native run-android
If even after this all your project doesnt work, make sure you already have the ANDROID_HOME variable on your PATH variables
Comment: My problem was with adding the ANDROID_HOME in PATH variables. Thanks for the comment!!!


t test to determine the difference between post and pre hand hygiene training, how can I measure inverse relationship

Question: The inpatients infection rates will be tracked from the entire inpatient population on all three adult units allowing it to be compared to the rates prior and post hand hygiene training.
My hypothesis is that "by providing hand hygiene training to the DCS, there will be an inverse relationship to inpatient infection rates."
If I use t test to determine the difference between post and pre hand hygiene training, how can I measure inverse relationship? Is it possible to measure inverse relationship? Do I have to do correlation analysis in this case?
Comment: Can you clarify what you mean by "inverse relationship" in this context? I'm not sure I follow you. Do you simply mean that you think the inpatient infection rate will go down?
Comment: What is the "DCS"?  How many observations of rates will you have - just one before and one after, or a longer time series?  And is the training being given to all three units?
Answer: If I understand the heart of the question correctly: a two-sided test will work whether the post measurements are greater or less than the pre measurements.  For a two-sided t-test, the null hypothesis can be thought of as, there is zero difference in the means of the two samples.  If the difference is significantly positive or significantly negative, the result in either case is significantly different from zero.
As this is an older post, we are not likely to get clarification as to whether there will be a single rate measured in each time period or a larger set of data.
The case of comparing two rates of infection would probably best be addressed by techniques used in epidemiology.  I'm not very familiar with these techniques, but one test that may be applicable is a test to compare two Poisson rates.  Implementations of this test or similar tests are described by Medicalc and the epitools package in R.


Monte Carlo: generating autocorrelated data from empirical distribution

Question: my problem is the following: having a distribution function of daily casfhlows resulting from electricity trading, I need to calculate a yearly 99% VaR, i.e. the 1% percentile of yearly casfhlows distribution.
Method 1/ Use CLT - fast and easy, albeit daily cashflows show some autocorrelation (0.3, 0.2 on the first two lags), hence assumptions are not satisfied.
Method 2/ Simulate as though daily cashflows are independent, i.e. 10 000 times generate 365 random values from the distribution function of daily cashflows and sum them. Like this, I get 10 000 yearly cashflows and get the respective percentile.
Method 3/ Simulate taking account autocorrelation of daily cashflows. This is what I don't know how to do. Having an empirical distribution function X(avg, sdev) how can I successively generate random realizations while ensuring that the generated data have (at least on the first lags) the same autocorrelation structure as the empirical daily cashflows that I have? Is there a way of doing this without estimating an ARMA model? The reason I want to avoid ARMA is that once I randomly generate one observation and model the following observations via the estimated ARMA process, the distribution of predicted cashflows will drift away from the empirical distribution of daily cashflows (due to the expected bad fit of the ARMA process).
Any hint is highly appreciated,
Daniel
Comment: Just to be clear, are you trying to find the VaR given some horizon in the future with some holdings today,  or are you trying to evaluate the VaR of the strategy in the past?
Comment: The first one. I have a portfolio specification in my hand. For this portfolio I run a simulation of "what daily cashflows would have happenned if this portfolio was held from 1st Jan 2012 until 31st Dec 2012" and these daily cashflows are what I use for the simulation of a 1Y VaR from now on.
Answer: For the sake of simplicity, consider that you invest in a portfolio of futures contracts and want to compute the VaR. You would first model the path of the futures prices and then calculate the distribution of the profits of the portfolio at the horizon given some arbitrary holdings.
The second part is straight-forward, but the first part is generally more complicated with more options. The primary inputs into the futures curve would be the spot price and rates that drive the term structure of the futures curve (so the risk-free rate plus the convenience yield). You can interpolate those rates to arbitrary periods that are constant through time and then focus on modeling these.
So to model the prices and these interpolated rates, I would focus on the log differences for the prices and the differences in the yields (these would be time-homogenous invariants). One obvious option is to estimate a VAR with a number of lags large enough to account for the seasonality in the spot price. For a daily series, that might be a lot of lags, so weekly or monthly might be better. Another alternative is to do a bootstrap that selects more than one period historically. For instance, if you can identify when the seasons are for your electricity data, then you can sample the whole season historically. Alternately, you can sample each month only from previous months (so January's bootstrap is always from a January historically).
After simulating you would have to build back up to the futures prices at your horizon and then the distribution of the portfolio at the horizon. Then you would calculate VaR from this distribution.
Comment: Ok John, thanks for the answer. However, the problem of casfhlows from electricity trading is more complicated than modeling a futures curve. Your casfhlow in electricity trading is given by your actions, the behavior of the whole market and the current bonus/fine mechanism of the market operator. Hence, you can either carry out a historical simulation, where all these factors behave realistically or you can model each by some process. Having 4 models, each with lousy fit, will provide with a very lousy prediction and thus either unreliable or crazy high VaR, hence I want to avoid models.
Comment: That's why I mentioned the bootstrap as an alternative.


How to make Postfix able to send message to the world?

Question: I'm configuring a SMTP server based on Postfix with PostgreSQL. When I try to send a mail to another domain I got a Recipient address rejected: Access denied error.
Here is my configuration :
# postconf -n

alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
config_directory = /etc/postfix
inet_interfaces = all
local_recipient_maps =
mailbox_size_limit = 0
mydestination = lan.example.com, localhost, localhost.localdomain, localhost
myhostname = example.com
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
readme_directory = no
recipient_delimiter = +
relayhost = lan.example.com
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
smtpd_recipient_restrictions = permit_mynetworks, permit_auth_destination, reject
virtual_alias_maps = pgsql:/etc/postfix/pgsql.d/virtual_alias.cf
virtual_gid_maps = static:108
virtual_mailbox_base = /var/spool/postfix/incoming
virtual_mailbox_domains = pgsql:/etc/postfix/pgsql.d/virtual_domain.cf
virtual_mailbox_limit = 51200000
virtual_mailbox_maps = pgsql:/etc/postfix/pgsql.d/virtual_mailbox.cf
virtual_transport = virtual
virtual_uid_maps = static:105

Here, example.com is the domain name of the server, and lan.example.com is the domain name of the relay host.
Here is the complete error :
Oct 15 10:22:08 authentification postfix/smtpd[9930]: connect from unknown[10.1.250.173]
Oct 15 10:22:08 authentification postfix/smtpd[9930]: NOQUEUE: reject: RCPT from unknown[10.1.250.173]: 554 5.7.1 <email@example.com>: Recipient address rejected: Access denied; from=<firstname.lastname@example.com> to=<firstname.lastname@example.com> proto=ESMTP helo=<localhost>
Oct 15 10:22:08 authentification postfix/smtpd[9930]: lost connection after RSET from unknown[10.1.250.173]
Oct 15 10:22:08 authentification postfix/smtpd[9930]: disconnect from unknown[10.1.250.173]

Answer: If I'm not misunderstanding your question, you want to send mail through lan.example.com. If lan.example.com is the same box, relayhost = lan.example.com should not be set (as this is already the relay host).
From the postfix documentation
By default, the Postfix SMTP server accepts:

  Mail from clients whose IP address matches $mynetworks, or
  Mail to remote destinations that match $relay_domains, except for addresses
   that contain sender-specified routing (user@elsewhere@domain), or
  Mail to local destinations that match $inet_interfaces or $proxy_interfaces,
    $mydestination, $virtual_alias_domains, or $virtual_mailbox_domains.

You should specify the network 10.1.250.0/24 (or whatever bit mask) to be part of $mynetworks, or, specifically put it into smtpd_relay_restrictions:
smtpd_relay_restrictions = $mynetworks, 10.1.250.0/24

Comment: `smtpd_relay_restrictions` is new to postfix 2.10, which is still under development. Apart from that, this setting does not accept lists of hosts or IP ranges - it accepts only **restrictions**. You may be thinking of `relay_domains`, or something else.
Comment: $mynetworks is not a valid restriction.
Comment: Thanks, the problem was solved by adding ``10.0.0.0/8`` to ``$mynetworks``
Comment: @adaptr: you are mistaken. If you do not specify `smtpd_relay_restrictions` it defaults to `$mynetworks, reject`. You just have to try it to be sure ;). `relay_domains` only suits you for relaying mail for specific domains.


Straight Line Motion w/ Acceleration and Deceleration Rates?

Question: PROBLEM:
A subway train travels 400ft between two stations. It starts from rest and accelerates at the rate of 8ft/sec^2 until it's velocity reaches 20ft/sec. It then moves at this constant velocity for awhile and then decelerates to rest at the rate of 12ft/sec^2. Find the total time between the stations.
QUESTIONS:
I'm lost on how to approach this problem. I'm not for sure if I should set two acceleration expressions up and use integration to work backwards. Then somehow utilize both to arrive at (t).
I started with 8 as acceleration and used integration to get v as shown below.
(a) = 8
(v) = 8t + 20      NOTE: This seems wrong because initial velocity is technically 0ft/sec
400 = ?
Again, this can't be so and I'm stuck on how and where I should start implementing 20ft/sec and the other deceleration rate which is 12ft/sec^2. Can someone get me pointed in the right direction without giving me the complete answer.
Comment: Since _three_ accelerations are used during this trip, you must split the problem into three parts: the first, during which the acceleration was $+8 \text{ft/sec}^2$; the second (coasting) portion, when the acceleration is _zero_ ; and the third and final part, where the acceleration is $-12 \text{ft/sec}^2$.  The sum of the three distances traveled in these parts is 400 feet.
Comment: Would the expression for (s) displacement, (v) velocity and (a) acceleration look like the following.(s)=4t^2-6t^2+400                                  (v)=8t-12t                                                (a)=8-12
Comment: Some other things to think about, in view of the answer posted below:  How long does it take the train to accelerate from rest to 20 ft/sec?  How far will it move in that time?  How long does it take to decelerate back to rest?  How far does it go while decelerating?  How much of the trip was covered at 20 ft/sec?  How long would that take?  You now have the times for the three phases.
Answer: I see someone has already answered this.
I tend to tell students to break up the problems according to differing acceleration/velocities and build an expression for the total time in terms of the known variables. Also if you use integration the correct expression for v would be
$$ v(t) - v(0) = \int_{0}^t a(t) dt  $$
Where you would use the fact that your initial condition is $v(0) = 0 $ to arrive at
$$ v(t) = 8t + v(0) = 8t $$
Then you might further integrate using the initial condition $x(0) = 0$ to obtain in a similar fashion
$$ x(t) - x(0) = \int_0^t v(t) = \frac{1}{2}at^2$$
$$ x(t) = \frac{1}{2}at^2 + x(0) = \frac{1}{2}at^2 $$
Which is the usual distance equation for a zero initial velocity/position.
However this is over complicating the problem because we already would have at our disposal the equations for constant acceleration:
\begin{eqnarray*}
x(t) &=& x_0 + v_0 t + \frac{1}{2}at^2  \\
v(t) &=& v_0 + at \\
v^2(t) &=& v^2(t_0) + 2 a \Delta x \\
\end{eqnarray*}
But yes the previous post is correct, simply separate the trip into three sections with different accelerations and solve for the individual times
Comment: I might add try doing some more thinking on the subject and if you get stuck just include the rest of your thought process.


Could I use a trialthlon swimming wetsuit for diving?

Question: I am a diver, yet I always rent my wetsuits. I have been thinking of making an investment recently, but I haven't gotten around to it, as in Belgium you need some different thicknesses: 7mm (for sure, even two perhaps), 3mm for indoor and on trips, a warm undersuit for the body, etc.
I am living in San Sebastian for 2 months, and I would love to buy a triahlon swimsuit 2mm (like this one) or 3-4mm (like this one) to be able to go out for longer swims in the ocean. I can't swim with a diving suit I suppose, because of the inflexible arms, and I am considering doing triathlons for fun. Not sure which one would be confortable with water temps around 16 degrees C.
Would I also be able to wear the triathlon suit to go diving? Or do they have significant changes that I am not aware of? I guess they are less insolating around the flexible parts, would that be a problem?
Comment: Ahh - I understand. Yes - they construction of a triathlon suit is definitely not designed for that sort of load/wear
Comment: Update, I just read somewhere that a tri suit will rip faster. That might be a good point. I guess I won't be able to swim decently in a scuba suit. I guess both are in order...
Comment: When you say 'will rip faster' - what do you mean. The lifespan of these things is pretty good.
Comment: I meant when you put on a heavy BCD, lead belt and a tank on your back. I could be wrong, but that might be a possible difference. The outside feels different.
Comment: Also some tris have restrictions on the kind of suits you can wear.
Answer: My tri suit is 3 years old and I have already poked holes into it with my fingers when pulling it up and into place. The material is definitely softer and will probably not sustain a belt and tanks on your back. The outside of a tri suit is soft and porous.
The 2nd link in your question takes me to surf suites, though, and I remember from my windsurfing days 20 years ago that windsurfing wetsuites are constructed more like diving suites, i.e. they have fabric on the outside that is more rugged but still allows for arm movement. Maybe a long john (sleeveless) will do? This is if you are looking to compromise on both ends, because the drag of a surf suit will certainly put you at a disadvantage as swimmer.


importing current package

Question: I'm writing a script and running it with the -i argument in order to keep the repl open after it finishes in order to be able to see info about the objects that I'm using while debugging.
In order to avoid having to quit and re-run the script I figured out that I can modify and save the script and then import [script-name] and then call my main method with [script-name].[main-method] ().
Now I want to write a single-character method (for convenience) that does:
def x():
    import [this script]
    [this script].[main-method]()

but to also be able to change the script's file name and retain the easy-reloading functionality without having to alter the code.
I've tried using importlib (see below) to no avail.
def y():
   import importlib
   this = importlib.import_module("".join(sys.argv[0].split(".py"))) # sys.argv[0] gives [module-name].py and the rest of the code inside the parentheses removes the ".py"
   this.[main-method]()

Answer: import, in any of it's incarnations, only reloads the script once. You are looking for the reload function:
from importlib import reload
import sys

def main():
    pass

def x():
    reload(sys.modules[__name__])
    main()

This code will reload the module you are currently in (probably __main__) and rerun a method from it. If you want to reload a script from within the interpreter, do the following instead:
>>> from importlib import reload
>>> def x():
...     reload(mymodule)
...     mymodule.main()
...
>>> import mymodule
>>> mymodule.main()
>>> # Do some stuff with mymodule
>>> x()

You may have to replace import mymodule with mymodule = importlib.import_module("".join(sys.argv[0].split(".py"))) if the script is in a weird location.
Sources:

https://stackoverflow.com/a/1676860/2988730
https://stackoverflow.com/a/1547978/2988730
Comment: That gives me "ImportError: Cannot re-init internal module __main__". Could reloading the main module be the one exception?
Comment: Yes. Do not try this from the command line. \_\_main\_\_ is the "module" that contains all the stuff you type. It makes sense that you can not reload that.
Comment: Fun fact, you can use backslashes in front of every underscore to remove its special meaning. Try this: \\_\\_main\\_\\_
Comment: But...I want to reload it. Is it merely not advisable or indeed impossible?
Comment: It is not possible to reload the main module itself. Since you typed out the other stuff, you can just copy and past in the updated version.
Comment: I think I understood what the problem is. Updated the answer.
Answer: I did it!
def x(): # make what I'm doing now at this very moment easier
   main()
   print("It works!")

def y(): # calls x() after loading most recent version
   import importlib
   from imp import reload
   this = importlib.import_module("".join(sys.argv[0].split(".py"))) # sys.argv gives [module-name].py and the rest of the code inside the brackets removes the ".py"
   this = reload(this)
   this.x()

Comment: `this = importlib.import_module` only needs to be done once. Make `this` a global, then do `this = reload(this)` to reload. Also `this.main()`.
Comment: FYI, `imp` is, for whatever reason, deprecated as of 3.4. But many of its methods exist in `importlib`, including `reload`, so on 3.4 and higher, you can just import `importlib` to get both `import_module` and `reload`.

importing current package


Find the minimum number of links to remove from digraph to make it acyclic

Question: As the title says, I am looking for a way to find the minimum number of links to remove from a directed graph to make it acyclic.  I am looking both for the minimum number, as well as an actual set of links to remove.
How can this be done in a reasonably simple and efficient way?
EDIT:  In other words, how can I label/order the vertices of the graph so that the adjacency matrix will contain most (nonzero) elements below the diagonal?
Comment: An acyclic graph contains no cycles at all, rather than merely a vertex that's not in a cycle.
Comment: You may find Menger's Theorem for digraphs useful. http://books.google.com/books?id=5GdXCWhE4-MC&lpg=PA201&ots=72otW4HEWK&dq=menger's%20theorem%20digraph&pg=PA201#v=onepage&q&f=false
Comment: Would it work to just find the vertex with the least number of incoming edges and remove those? Then you have a vertex that can never be reached, hence acyclic.
Answer: This problem is well-known under the name minimum feedback arc set problem. The decision version of the problem says: given a graph $G$ and a parameter $k$, can we break all cycles in $G$ by deleting some set of at most $k$ arcs from it? [Note that, as usual, the decision version is no harder than the computational one of finding the minimum feedback arc set. ]
The above decision version of this problem is NP-complete. In fact, it is one of Richard Karp's 21 NP-completeness problems. That is, unless NP collapses to P--widely believed to be unlikely--this problem will not admit a polynomial time algorithm. You can look up the details from the wikipedia page.
Comment: @Szabolcs You are quite welcome. I guess thanks are due also to [Community](http://math.stackexchange.com/users/-1/community) for poking old unanswered posts. =)
Comment: Thanks!  I didn't expect an answer so long after asking the question
Answer: As answered above, the problem is NP-complete.
The wikipedia page doesn't state the algorithm explicitly though.
The most elegant method I found is a simple $2^n$ sized dynamic program.
It goes as:
Let $S$ denote an arbitrary subset of nodes, $f(S)$ be the number of arcs in the minimum arc set for the subgraph consisting of the nodes in $S$.
Let $c(k,S')$ denote the number of arcs from node $k$ to nodes in the subset $S'$.
Then (assuming no self loops): $$f(S)=\min_{\forall S'\subset S\\ k \in K \text{ s.t.}S=S'\cup K}\{f(S')+c(k,S') \}$$
Naturally, the base case will be:
For $S'$ unary $f(S')=0, c(k,S')=1$. Naturally this is an $\mathcal{O}(n\times 2^n)$ algorithm, with memory complexity of $\mathcal{O}(2^n)$.
Answer: You can start off by finding all cycles in the graph. You can be sure that, for each cycle, at least one of the edges (links) in it are going to be removed. You save for each edge, how many cycles it is contained in. Then, start removing edges greedily until all cycles are gone. This isn't very efficient, though.
Comment: Can you prove that this will give the *minimum* number of edges to be removed?  Also, can you suggest a way to find all cycles?  I think the total number of cycles will grow extremely fast with the vertex count in a sufficiently dense graph.


Is validation set important in SVM regression analysis

Question: I am new to machine learning and currently reading a paper about a ANN modelling in which they have divided their dataset into Training , validation and testing set. I have carried out some minor SVM regression studies of my own using R (e1071); in which I have used only Training Set and testing set but no validation test to create model. I have optimized cost and gamma of my SVR model using inbuilt tune() function.
And this is a sample code
<code>library(e1071)
set.seed(3)
data = data.frame(matrix(rnorm(100*5), nrow=100))
train=data[1:70,]
test=data[71:100,]
op=tune(svm,X1 ~ ., data=train,kernel="radial",ranges=list(cost=c(0.001,0.01),gamma=c(0.5,0.1)))
fit = op$best.model
summary(fit)
pred=predict(fit,test)
</code>
So is it necessary to use validation set in SVR. if yes how can I programmatically implement validation set in the above code.
Answer: Actually, the "tune" function already split the data into training and validation set and performs, automatically, the cross-validation (10 fold) of your data. The default parameter of the "tune" function can be found by typing "?tune.control" in R console.
So, what you did in your code was correct!
Obs.: If you want to use the function svm directly, you should split between training, validation and test set and implement, for example, the cross-validation of the models.


C: Mudar cor de letras (várias cores em uma só tela)

Question: Por exemplo, quero printar na mesma tela:
printf(".___. .___. .___.\n");

printf("._1_. ._2_. ._3_.\n");

printf("Digite 0 p/ sair ou outro número p/ continuar: ");

porém quero que as letras de cada printf fiquem com cores diferentes, por exemplo: primeiro o azul, depois o verde e depois o amarelo... Tentei usar o seguinte código:
system("color A");
printf(".___. .___. .___.\n");
system("color E");
printf("._1_. ._2_. ._3_.\n");
system("color 7");
printf("Digite 0 p/ sair ou outro número p/ continuar: ");

Porém não funcionou; ele pegou somente a última cor, ou melhor, ele foi rápido e só executou visivelmente a última cor... Tentei também:
#include <conio.h>
textcolor(blue);
printf(".___. .___. .___.\n");
textcolor(red);
printf("._1_. ._2_. ._3_.\n");
textcolor(yellow);
printf("Digite 0 p/ sair ou outro número p/ continuar: ");

Mas fala que textcolor não foi declarada.
Comment: Rapaz, `conio` é obsoleta demaisssZzzZzzZ.... Que tal [essa resposta](http://stackoverflow.com/a/23657072/4056678) no SOen?
Comment: não funcionou, só printou um monte de caracter estranho, esse acho que é para o Unix (Linux)
Comment: ops, windows [bem aqui](http://stackoverflow.com/a/9203489/4056678).
Comment: Deu certo, porém é meio complicado kk pois não posso usar função, vou ter que usar o system("color XX") mesmo, mas valeu a dica, em outros projetos eu uso esse
Comment: Experimenta se o teu ecra faz ["ANSI escape sequences"](http://ascii-table.com/ansi-escape-sequences.php): `printf("\x1b[32mHello\n");`
Comment: Se estás em Windows, talvez experimentar [ansicon](https://github.com/adoxa/ansicon) funcione *(nunca experimentei)*
Comment: Esses só funcionam no Linux, e o ansicon só muda o cursor etc
Answer: Uma forma fácil de fazer isso em C é usar o código ANSI das cores. No início você cria uma constante para armazenar o ANSI para cada cor:
#define ANSI_COLOR_RED      "\x1b[31m" //cores em ANSI utilizadas
#define ANSI_COLOR_GRAY     "\e[0;37m"

E para usar, passa essas constantes no printf:
printf(ANSI_COLOR_RED "Hello world" ANSI_COLOR_RESET);

Sendo que o primeiro é a cor que você deseja para esse texto, e no final você pode usar o Reset para voltar ao padrão.
Aqui tem um exemplo em que usei isso em um jogo.
Answer: Já que você está procurando uma solução específica em C para windows, eu recomendaria usar a função SetConsoleTextAttribute() da API win32.
Você tem que gerar um handler para o terminal e então alimenta-lo com os atributos corretos.
Segue um exemplo simples:
/* Mudar a cor do texto do terminal, e depois de volta ao normal. */
#include <stdio.h>
#include <windows.h>

int main() {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
    WORD saved_attributes;

    /* Salvar estado atual */
    GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
    saved_attributes = consoleInfo.wAttributes;

    SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
    printf("This is some nice COLORFUL text, isn't it?");

    /* Voltando ao estado original */
    SetConsoleTextAttribute(hConsole, saved_attributes);
    printf("Back to normal");

    return 0;
}

Para mais informações (em inglês), olhe aqui.


Cisco Get Current Interface Throughput

Question: I can graph a device interface with SNMP tools, platforms like Cacti even make pretty graphs, but these are based on polling intervals (typically, every 5 minutes).
I can use the CLI;
r1>show int gi0/0
GigabitEthernet0/0 is up, line protocol is up
Hardware is BCM1250 Internal MAC, address is 0011.2233.4455 (bia 0011.2233.4455)
Description: link 1
MTU 1540 bytes, BW 1000000 Kbit, DLY 10 usec,
   reliability 255/255, txload 35/255, rxload 20/255
Encapsulation 802.1Q Virtual LAN, Vlan ID  1., loopback not set
Keepalive set (10 sec)
Full Duplex, 1000Mbps, media type is RJ45
output flow-control is XON, input flow-control is XON
ARP type: ARPA, ARP Timeout 04:00:00
Last input 00:00:00, output 00:00:00, output hang never
Last clearing of "show interface" counters never
Input queue: 0/75/3208/72484 (size/max/drops/flushes); Total output drops: 1373910311
Queueing strategy: Class-based queueing
Output queue: 0/1000/12 (size/max total/drops)
5 minute input rate 79658000 bits/sec, 19312 packets/sec
5 minute output rate 140174000 bits/sec, 21984 packets/sec

I can see from the 5 minute output rate I'm transmitting 140Mbps of traffic, but that's averaged over the last five minutes. So not right now, and no better than Cacti et all.
I could enter the interface command load-interval 30 to bring down the sampling rate to 30 seconds, at which point the txload and rxload values become more accurate.
Again though, if I need to find out which link is maxed out right now, I find it difficult to believe that for all the amazing things Cisco routers and switches can do, they can't tell me current tx/rx rate for an interface, right now.
I understand a sampling period maybe required for such a figure to be attainable, what's wrong with 1 second? Surely the CPU demand isn't that much, just counting the number of packets that pass every second and their size?
Has someone perhaps developed their own way of working this out? I see others haunted by the same conundrum?
UPDATE: I should have given better context to this, so I will try and do so now.
A typical need for me to know an interface throughput right now, is when a customer who has a 100Mbps port rings up and says "Hey, I'm download X from your mirror server but its only transferring at 20Mbps". I want to be able to see their switch pot throughput right now, whilst they're on the phone to me, to confirm this (non-tech customers often report incorrect values in my experience).
So, in this scenario I can confirm whether the customer port is already receiving 100Mbps so they only get 20Mbps because their port is at capacity, or if they are even transferring at anything like the speed they are claiming  (whether it be above or below). Also, next I will want to see the throughput of the router that switch is terminated on for all those customers, this is another potential bottleneck. Also, I can check the switch port of the mirror server whilst the transfer is in progress.
I don't want to respond to the customer with "OK, well make sure you continue to download for another 5 minutes so I can wait for $NMS_OF_CHOICE to poll the interfaces", not an acceptable answer in the customers eyes. I can give many more scenarios, but essentialy, complaining customers is top priority :)
Comment: How is the throughput at any given second going to be of any use to you.  Network traffic tends to be variable.  If you have it set to 1 second, and you miss that one-second interval that a particular bit of traffic happened, then what have you learned?
Comment: Hi Zoredache, I have updated my post. I hope this will make it clear now :)
Answer: I'm not a switch designer, so so in terms of what the cost would be to monitor at this frequency I can't say.
What I can say, is that I have run into the situation where even a second isn't always enough because you can overun the buffers in periods shorter than a second. So if you want to know if a link is maxed out, I recommend looking at the dropped packets (You can monitor this via SNMP as well). If you are dropping packets (a few here there is okay, but a lot is not good) then you are demanding more than the interface can handle. This can also happen on your servers before they even hit the switch. The precise rate of dropped packets generally isn't important, but if they keep increasing each show interface you are likely in a bad place.
In terms of Cacti, that is not a limit of the switch or SNMP. SNMP records the bits sent and received as an increasing counter, so if you poll every second, you will get per second resolution. The way it works is the time stamp of each sample is taken along with the current count. It then takes the difference and expresses it in units of "per second" but in reality is is really a per 5 minute rate converted or expressed as per second.
If you try polling SNMP every second though, you better watch your CPU.
Answer: Your interface is transmitting and receiving at full gig speeds. It doesn't actually transmit anything at 140Mbps, that's just what it averages out to over the interval. Real time traffic utilization would be useless to you as a human reader because it would be a constant flipping back and forth between sending/receiving at 100% and 0%. If your concern is how quickly you can identify a network problem then I would suggest what @Kyle-Brandt has said above. Dropped packets are the best indicator of an over-utilized link.
Comment: Primarily, I want to identify bottlenecks when trouble shooting reports of slow speeds between point X and Y in the network. Its not a continuous measurement, I understand how that wouldn't be useful. Thanks for your insight though, good idea regarding dropped packets for over utilized links, but I don't just want to know when a link is at capacity, just what its current utilization level is.
Answer: SolarWinds Real-Time Interface Monitor, part of the Network Engineer's Toolset is able to poll interfaces via SNMP as low as every 5 seconds.
Polling network interfaces via SNMP every 5 seconds is not something administrators should be doing often as part of a permanent monitoring solution.  However, for monitoring on an ad-hoc point in time basis, there are a few cases where under 60 second polling interval can be useful.
Understanding polling intervals -- as they go both up and down, is paramount to being able to interpret the data coming out of the tools.
As a fictitious (but concept seen many times) example, an interface that registers 90% utilization on a 5 second interval may not lead to end-user perceived problems -- however, that same interface at 50% utilization on a 60 second interval may in fact lead to end-user perceived problems.
The error in thinking most administrators make is assuming the 50% utilization on a 60 second interval is somehow "less than" a 90% utilization on a 5 second interval.  It is not "less than" -- it is not "greater than."  The short answer is that the utilization figures cannot be compared as if they were equivalent figures because the intervals are different.
To dive a little deeper -- and show how extremes can affect the math -- it would be possible for the interface to be operating at 100% utilization for a full 30 seconds -- then go silent for 30 seconds -- and the utilization on a 60 second interval would still be 50%.  During the 30 seconds of 100% utilization, end-user applications experienced enough packet loss and/or delay to timeout/break displaying a message.
Compare that with a 90% utilization on a 5 second interval.  A case where even if the interface were at 100% utilization for 4.5 seconds, then silent for 0.5 seconds -- resulting in a 90% utilization on a 5 second interval -- the packet loss and/or delay may not be enough to cause the end-user application to react just yet.
The above are completely fictitious examples -- however, the concept has been witnessed many times.  Cogently assessing over-subscription/over-utilization of an interface relies on knowledge of the monitoring tools, understanding the monitoring/polling intervals and interpreting the output of the monitoring/polling tools, and behavior of the applications in use.
Comment: Thanks Weaver some really good points here, I hadn't thought of yet! I have posted my own answer below, perhaps I will factor these statistics into my script as well, so rather than just giving throughput, it gives drops and discards etc, for stats that more accurately reflect what's going on right now. Good idea! :)
Answer: I have written an expect script to poll for the bytes sent/received every second for me, from the output of the "show int xxx" command. The difference between each second is the traffic through the interface.
The basic script is here: http://tinyurl.com/c2sx2fc
It was my first expect script so my stack overflow thread is here :) http://tinyurl.com/82gtk3e
I will add some features like discards and drops, and make two scripts, one for traffic in, and one for traffic out.

Cisco Get Current Interface Throughput


Why A Basic Solution Is A Vertex?

Question: A basic solution is a vector with $n$ components ($n=$ the number of variables), in which $m$ of them ($m=$ the number of functional constraints) are positive and the remaining ($n-m$) components are zero.
How does this implies that it must be a vertex point?
Comment: A small but important point: $n-m$ of the components must equal 0 (these are the *nonbasic* variables); the remaining $m$ of them *may* be positive (these are the *basic* variables) -- but they may also equal 0.
Answer: Assuming the LP is written in standard form (all functional constraints are $\le$, all decision variables are $\ge 0$), then there are a total of $m+n$ constraints ($m$ functional and $n$ non-negativity), and each constraint corresponds to a variable (either a slack variable or a "regular" variable).
A basic solution is the solution you obtain by:

choosing $m$ of the constraints (out of the total of $m+n$ functional and non-negativity constraints)
setting them to equalities
forcing the $n-m$ variables that do not correspond to your $m$ constraints to 0, and
solving the resulting system of equations for the $m$ variables that do correspond to your $m$ constraints.

Since you are solving a system with $m$ equations and $m$ unknowns, there is a single unique solution (assuming there's nothing funny going on like degeneracy), and that is your basic solution. Graphically, the basic solution is a vertex of the feasible region because it is the single point that is on the boundary of all $m$ of those constraints.
Comment: Note that if the $m$ by $m$ basis matrix is singular, then even if you can solve the system of equations the solution is not considered to be a basic solution.  Degeneracy is a different problem, which occurs when there are multiple sets of $m$ constraints that give the same basic solution.  This can only happen if one or more of the basic variables takes on the value 0.
Comment: The basic solution correspond to the vertex in the higher dimensional plane that is formed by adding the slack and converting the inequalities into equations. am I correct?
Answer: The idea is, the $m$ positive components identify the vertex point, which is the exact solution of those $m$ equations.

Why A Basic Solution Is A Vertex?


Evaluate for $t\in \mathbb{R}$ $\int_{-\infty}^\infty{e^{itx} \over (1+x^2)^2}dx$

Question: Evaluate for $t\in \mathbb{R}$ $$\int_{-\infty}^\infty{e^{itx} \over (1+x^2)^2}dx.$$
Here is what I have done: Let $f(z)={e^{itz}\over (1+z^2)^2}$. This has two poles $z=i$ $z=-i$ and an essential singularity at $z=- \infty$. When $t\leq 1$ I think the integral becomes ${1\over 2}\pi (1-t)e^t$ and when $t\leq 0$ I think the integral becomes ${1\over 2}\pi(1+|t|)e^{-|t|}$. I'm not sure how to show this. Any solutions or help is greatly appreciated.
Answer: Hint: Use contour $\Gamma$ consisting of the upper semicircle $C_\rho^+ : y = \sqrt{\rho^2 - x^2}$ and the line $\gamma$ joining $(-\rho, 0)$ to $(\rho, 0)$. Apply Jordan's lemma to see that the integral vanishes over $C_\rho^+$ (or do this yourself using the M-L estimate).


Eclipse JFrame warning

Question: I often use JFrames, and because they are applications, they obviously need a
public static void main(String[] args)

method. They also need the line in main()
myJFrame g = new myJFrame();

In eclipse, I get a warning on variable g: "The local variable g is never read", but if I omit that line, the program won't run. Why do I need that line, and if g is essential, why is there a warning on it?
Comment: Unless you actually do something later with the variable `g` or reference it in some way, you can get away with just doing `new myJFrame();`
Answer: Answering your question - probably you invoke all necessary methods (like setVisible(true) etc.) to run application in myJFrame constructor. If so - you needn't g local variable - you never use it later (looking at warning).
First thing main - is starting point of all Java applications.
Second thing if you doing all things in your JFrame constructor then you only need line
new myJFrame(); //in Java it's convention to use first letter
                //upper-case class names -> MyJFrame

Below is simple, standard way of running first window in your application.
public final class App {
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                MainWindow frame = new MainWindow();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

In MainWindow class you only create Swing components etc.
Answer: The warning means that you declare a local variable/pointer (called g in this case) but never actually utilize it anywhere in your code. With the warning the program should run fine, but you have a extra "pointer" to your JFrame that's never used.
If you want to access your JFrame from the method were you called myJFrame g = new myJFrame(); you should keep it that way.
Otherwise new myJFrame(); will suffice.
Answer: If you are not intending to reference this object ones initialized this wld be enough.
new myJFrame();

Eclipse JFrame warning


Metric spaces and σ-closure-preserving bases (Nagata's metrization theorem)

Question:
The first two line of the proof say that if $X$ is metrizable (so paracompact) then clearly there is a base $\mathcal{G}= \bigcup_{i\in \mathbb{N}} G_i$ having this property. Paracompactness just gives locally finite open refinement for any open cover of $X$. So could you please tell me how I find such a base?
(The image above is from Harold W. Martin, A note on the Frink metrization theorem, Rocky Mountain J. Math., Vol.6, No.1 (1976), pp.155-157, doi:10.1216/RMJ-1976-6-1-155.)
Answer: For each $n\in\Bbb Z^+$ let $\mathscr{G}_n$ be a locally finite open refinement of the open cover
$$\left\{B\left(x,\frac1n\right):x\in X\right\}\;.$$
Locally finite families are closure-preserving, so each $\mathscr{G}_n$ is closure preserving. Let $x\in X$ and $n\in\Bbb Z^+$; then $\{G\in\mathscr{G}_n:x\in G\}$ is finite, so $V_n(x)=\bigcap\{G\in\mathscr{G}_n:x\in G\}$ is an open nbhd of $x$. Fix any $G_x\in\{G\in\mathscr{G}_n:x\in G\}$; then $G\subseteq B\left(y,\frac1n\right)$ for some $y\in X$, so
$$\operatorname{diam}V_n(x)\le\operatorname{diam}G_x\le\operatorname{diam}B\left(y,\frac1n\right)\le\frac2n\;.\tag{1}$$
Thus, for each $n\in\Bbb Z^+$ we have
$$x\in V_{3n}(x)\subseteq B\left(x,\frac1n\right)\;,$$
and $\{V_n(x):n\in\Bbb Z^+\}$ is therefore a local base at $x$.
Added: Let $\mathscr{G}=\bigcup_{n\in\Bbb Z^+}\mathscr{G}_n$. The fact that $\mathscr{G}$ is a base for $X$ also follows easily from $(1)$: for any $G\in\mathscr{G}_{3n}$ we have
$$x\in G\subseteq B\left(x,\frac1n\right)\;.$$
Comment: What is the basis for X here? Are you claiming that $\mathcal{G}=\cup_{i\in \mathbb{N}} \mathcal{G}_{i}$ will be required basis for X.   But I suppopse this might not basis for X.
Comment: @Manik: Yes, $\mathscr{G}$ is a base for $X$. I thought that that was pretty clear, so I didn't mention it, but I'll add it now.
Comment: from your construction $\mathcal{G}=\cup_{i\in \mathbb{N}}\mathcal{G}_{i}$ is a $\sigma$-locally finite open refinement for your open cover $\{(x, \frac{1}{n}) : x\in X\} $ [which you taken as a base]. But this need not imply that $\mathcal{G}$ is also base. So we can't take $\mathcal{G}$ as a base.
Comment: @Manik: What I just added to my answer proves that it's a base.
Comment: No no, I just want to know that where from you are taken the fact that $\mathcal{G}$ is a base for X?? This line I am not getting.
Comment: @Manik: It shows that if $x\in X$, and $U$ is any open nbhd of $x$, then there is a $G\in\mathscr{G}$ such that $x\in G\subseteq U$. That's exactly what it means for $\mathscr{G}$ to be a base for $X$.
Comment: for each $x\in X$ and open U if you find $G \in \mathcal{G}$ s.t $x\in G \subseteq U$ then this may not be base. You need to check other condition if $x\in U_1 \cap U_2$ then there exists U s.t $x\in U \subseteq U_1 \cap U_2$. So $\mathcal{G}$ not necessarily a base.
Comment: @Manik: That condition is an immediate consequence of what I've already proved. (And if you're advanced enough to be looking at metrization theorems, you should already know several equivalent conditions for a family $\mathscr{B}$ to be a base for a topology $\mathscr{T}$. One is the condition that I stated. Another is that $\mathscr{T}$ is the set of all unions of subfamilies of $\mathscr{B}$. And yet another is the pair of conditions that you appear to be familiar with.)