text:
package com.sscience.stopapp.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.science.baserecyclerviewadapter.interfaces.OnItemClickListener;
import com.sscience.stopapp.R;
import com.sscience.stopapp.adapter.AboutAdapter;
import com.sscience.stopapp.base.BaseActivity;
import com.sscience.stopapp.util.CommonUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sscience.stopapp.R.id.recyclerView;

/**
 * @author SScience
 * @description
 * @email chentushen.science@gmail.com
 * @data 2017/2/6
 */

public class AboutActivity extends BaseActivity {

    private RecyclerView mRecyclerView;
    private AboutAdapter mAboutAdapter;

    public static void actionStartActivity(Context context) {
        Intent intent = new Intent(context, AboutActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getContentLayout() {
        getWindow().setStatusBarColor(getResources().getColor(android.R.color.transparent));
        return R.layout.activity_about;
    }

    @Override
    protected void doOnCreate(@Nullable Bundle savedInstanceState) {
        setToolbar("");

        TextView tvVersion = (TextView) findViewById(R.id.tv_version);
        tvVersion.setText(getString(R.string.version, CommonUtil.getAppVersion(this)));

        mRecyclerView = (RecyclerView) findViewById(recyclerView);
        mRecyclerView.setHasFixedSize(true);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, manager.getOrientation()));
        mAboutAdapter = new AboutAdapter(this, mRecyclerView);
        mRecyclerView.setAdapter(mAboutAdapter);

        List<Map<String, String>> aboutList = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        map1.put("title", getString(R.string.about_app));
        map1.put("subtitle", getString(R.string.about_app_detail));
        aboutList.add(map1);
        Map<String, String> map2 = new HashMap<>();
        map2.put("title", getString(R.string.source_code_address));
        map2.put("subtitle", getString(R.string.source_code_address_detail));
        aboutList.add(map2);
        Map<String, String> map3 = new HashMap<>();
        map3.put("title", getString(R.string.report_issues));
        map3.put("subtitle", getString(R.string.report_issues_detail));
        aboutList.add(map3);
        Map<String, String> map4 = new HashMap<>();
        map4.put("title", getString(R.string.feedback_suggestions));
        map4.put("subtitle", getString(R.string.feedback_suggestions_detail));
        aboutList.add(map4);
        mAboutAdapter.setData(false, aboutList);

        initListener();
    }

    private void initListener() {
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar_layout);
        final TextView toolbarTitle = (TextView) findViewById(R.id.toolbar_title);
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int maxScroll = appBarLayout.getTotalScrollRange() - (int) getResources().getDimension(R.dimen.abc_action_bar_default_height_material);
                float percentage = (float) Math.abs(verticalOffset) / (float) maxScroll;
                ViewCompat.setAlpha(toolbarTitle, percentage);
            }
        });

        mAboutAdapter.setOnItemClickListener(new OnItemClickListener<Map<String, String>>() {
            @Override
            public void onItemClick(Map<String, String> maps, int i) {
                switch (i) {
                    case 0:
                        aboutApp();
                        break;
                    case 1:
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/XYScience/StopApp")));
                        break;
                    case 2:
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/XYScience/StopApp/issues")));
                        break;
                    case 3:
                        feedbackToEmail();
                        break;
                }
            }
        });

        FloatingActionButton fabShare = (FloatingActionButton) findViewById(R.id.fab_share);
        fabShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_content) +
                        "https://play.google.com/store/apps/details?id=com.sscience.stopapp、\n" +
                        "http://coolapk.com/apk/com.sscience.stopapp");
                startActivity(Intent.createChooser(intent, getString(R.string.share_title)));
            }
        });
    }

    private void aboutApp() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.about_app);
        builder.setMessage(R.string.about_app_dialog);
        builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    private void feedbackToEmail() {
        Intent data = new Intent(Intent.ACTION_SENDTO);
        data.setData(Uri.parse("mailto:chentushen.science@gmail.com"));
        data.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.send_email_subject));
        data.putExtra(Intent.EXTRA_TEXT, "----------\n" + getString(R.string.send_email_app_name) + getString(R.string.app_name)
                + getString(R.string.send_email_app_version) + CommonUtil.getAppVersion(AboutActivity.this)
                + getString(R.string.send_email_phone_model) + CommonUtil.getPhoneModel()
                + getString(R.string.android_version) + CommonUtil.getAndroidVersion()
                + "\n----------"
                + getString(R.string.leave_feedback));
        startActivity(Intent.createChooser(data, getString(R.string.choose_email_app)));
    }
}


text:
import itertools
from collections import defaultdict

import numpy as np
from networkx.algorithms import bipartite

from pgmpy.models.MarkovNetwork import MarkovNetwork
from pgmpy.base import UndirectedGraph
from pgmpy.factors.discrete import DiscreteFactor
from pgmpy.factors import factor_product

class FactorGraph(UndirectedGraph):
    """
    Class for representing factor graph.

    DiscreteFactor graph is a bipartite graph representing factorization of a function.
    They allow efficient computation of marginal distributions through sum-product
    algorithm.

    A factor graph contains two types of nodes. One type corresponds to random
    variables whereas the second type corresponds to factors over these variables.
    The graph only contains edges between variables and factor nodes. Each factor
    node is associated with one factor whose scope is the set of variables that
    are its neighbors.

    Parameters
    ----------
    data: input graph
        Data to initialize graph. If data=None (default) an empty graph is
        created. The data is an edge list.

    Examples
    --------
    Create an empty FactorGraph with no nodes and no edges

    >>> from pgmpy.models import FactorGraph
    >>> G = FactorGraph()

    G can be grown by adding variable nodes as well as factor nodes

    **Nodes:**

    Add a node at a time or a list of nodes.

    >>> G.add_node('a')
    >>> G.add_nodes_from(['a', 'b'])
    >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
    >>> G.add_factors(phi1)
    >>> G.add_nodes_from([phi1])

    **Edges:**

    G can also be grown by adding edges.

    >>> G.add_edge('a', phi1)

    or a list of edges

    >>> G.add_edges_from([('a', phi1), ('b', phi1)])
    """

    def __init__(self, ebunch=None):
        super(FactorGraph, self).__init__()
        if ebunch:
            self.add_edges_from(ebunch)
        self.factors = []

    def add_edge(self, u, v, **kwargs):
        """
        Add an edge between variable_node and factor_node.

        Parameters
        ----------
        u, v: nodes
            Nodes can be any hashable Python object.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> G.add_nodes_from([phi1])
        >>> G.add_edge('a', phi1)
        """
        if u != v:
            super(FactorGraph, self).add_edge(u, v, **kwargs)
        else:
            raise ValueError("Self loops are not allowed")

    def add_factors(self, *factors, replace=False):
        """
        Associate a factor to the graph.
        See factors class for the order of potential values.

        Parameters
        ----------
        *factor: pgmpy.factors.DiscreteFactor object
            A factor object on any subset of the variables of the model which
            is to be associated with the model.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_factors(phi1, phi2)
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        """
        for factor in factors:
            if set(factor.variables) - set(factor.variables).intersection(
                set(self.nodes())
            ):
                raise ValueError(
                    "Factors defined on variable not in the model", factor.__repr__()
                )

            if replace:
                for fa in self.factors:
                    if set(factor.variables) == set(fa.variables):
                        neighbors = self.neighbors(fa)
                        self.remove_factors(fa)
                        self.add_node(factor)
                        self.add_edges_from([(factor, neigh) for neigh in neighbors])
                self.factors.append(factor)

            else:
                self.factors.append(factor)

    def remove_factors(self, *factors):
        """
        Removes the given factors from the added factors.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> G.add_factors(phi1)
        >>> G.remove_factors(phi1)
        """
        for factor in factors:
            self.factors.remove(factor)
            # If factor is also in the graph, remove the node and corresponding edges.
            if factor in self.nodes:
                self.remove_node(factor)

    def get_cardinality(self, node=None):
        """
        Returns the cardinality of the node

        Parameters
        ----------
        node: any hashable python object (optional)
            The node whose cardinality we want. If node is not specified returns a
            dictionary with the given variable as keys and their respective cardinality
            as values.

        Returns
        -------
        int or dict : If node is specified returns the cardinality of the node.
                      If node is not specified returns a dictionary with the given
                      variable as keys and their respective cardinality as values.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_nodes_from([phi1, phi2])
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        >>> G.add_factors(phi1, phi2)
        >>> G.get_cardinality()
        defaultdict(<class 'int'>, {'c': 2, 'b': 2, 'a': 2})

        >>> G.get_cardinality('a')
        2
        """
        if node:
            for factor in self.factors:
                for variable, cardinality in zip(factor.scope(), factor.cardinality):
                    if node == variable:
                        return cardinality
        else:
            cardinalities = defaultdict(int)
            for factor in self.factors:
                for variable, cardinality in zip(factor.scope(), factor.cardinality):
                    cardinalities[variable] = cardinality
            return cardinalities

    def check_model(self):
        """
        Check the model for various errors. This method checks for the following
        errors. In the same time it also updates the cardinalities of all the
        random variables.

        * Check whether bipartite property of factor graph is still maintained
          or not.
        * Check whether factors are associated for all the random variables or not.
        * Check if factors are defined for each factor node or not.
        * Check if cardinality information for all the variables is available or not.
        * Check if cardinality of random variable remains same across all the
          factors.
        """
        variable_nodes = set([x for factor in self.factors for x in factor.scope()])
        factor_nodes = set(self.nodes()) - variable_nodes

        if not all(
            isinstance(factor_node, DiscreteFactor) for factor_node in factor_nodes
        ):
            raise ValueError("Factors not associated for all the random variables")

        if not (bipartite.is_bipartite(self)) or not (
            bipartite.is_bipartite_node_set(self, variable_nodes)
            or bipartite.is_bipartite_node_set(self, variable_nodes)
        ):
            raise ValueError("Edges can only be between variables and factors")

        if len(factor_nodes) != len(self.factors):
            raise ValueError("Factors not associated with all the factor nodes.")

        cardinalities = self.get_cardinality()
        if len(variable_nodes) != len(cardinalities):
            raise ValueError("Factors for all the variables not defined")

        for factor in self.factors:
            for variable, cardinality in zip(factor.scope(), factor.cardinality):
                if cardinalities[variable] != cardinality:
                    raise ValueError(
                        f"Cardinality of variable {variable} not matching among factors"
                    )

        return True

    def get_variable_nodes(self):
        """
        Returns variable nodes present in the graph.

        Before calling this method make sure that all the factors are added
        properly.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_nodes_from([phi1, phi2])
        >>> G.add_factors(phi1, phi2)
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        >>> G.get_variable_nodes()
        ['a', 'c', 'b']
        """
        self.check_model()

        variable_nodes = set([x for factor in self.factors for x in factor.scope()])
        return list(variable_nodes)

    def get_factor_nodes(self):
        """
        Returns factors nodes present in the graph.

        Before calling this method make sure that all the factors are added
        properly.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_nodes_from([phi1, phi2])
        >>> G.add_factors(phi1, phi2)
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        >>> G.get_factor_nodes()
        [<DiscreteFactor representing phi(b:2, c:2) at 0x4b8c7f0>,
         <DiscreteFactor representing phi(a:2, b:2) at 0x4b8c5b0>]
        """
        self.check_model()

        variable_nodes = self.get_variable_nodes()
        factor_nodes = set(self.nodes()) - set(variable_nodes)
        return list(factor_nodes)

    def to_markov_model(self):
        """
        Converts the factor graph into markov model.

        A markov model contains nodes as random variables and edge between
        two nodes imply interaction between them.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_factors(phi1, phi2)
        >>> G.add_nodes_from([phi1, phi2])
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        >>> mm = G.to_markov_model()
        """
        mm = MarkovNetwork()

        variable_nodes = self.get_variable_nodes()

        if len(set(self.nodes()) - set(variable_nodes)) != len(self.factors):
            raise ValueError("Factors not associated with all the factor nodes.")

        mm.add_nodes_from(variable_nodes)
        for factor in self.factors:
            scope = factor.scope()
            mm.add_edges_from(itertools.combinations(scope, 2))
            mm.add_factors(factor)

        return mm

    def to_junction_tree(self):
        """
        Create a junction treeo (or clique tree) for a given factor graph.

        For a given factor graph (H) a junction tree (G) is a graph
        1. where each node in G corresponds to a maximal clique in H
        2. each sepset in G separates the variables strictly on one side of
        edge to other

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_factors(phi1, phi2)
        >>> G.add_nodes_from([phi1, phi2])
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        >>> mm = G.to_markov_model()
        """
        mm = self.to_markov_model()
        return mm.to_junction_tree()

    def get_factors(self, node=None):
        """
        Returns the factors that have been added till now to the graph.

        If node is not None, it would return the factor corresponding to the
        given node.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_factors(phi1, phi2)
        >>> G.add_nodes_from([phi1, phi2])
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        >>> G.get_factors()
        >>> G.get_factors(node=phi1)
        """
        if node is None:
            return self.factors
        else:
            factor_nodes = self.get_factor_nodes()
            if node not in factor_nodes:
                raise ValueError(
                    "Factors are not associated with the " "corresponding node."
                )
            factors = list(
                filter(
                    lambda x: set(x.scope()) == set(self.neighbors(node)), self.factors
                )
            )
            return factors[0]

    def get_partition_function(self):
        """
        Returns the partition function for a given undirected graph.

        A partition function is defined as

        .. math:: \sum_{X}(\prod_{i=1}^{m} \phi_i)

        where m is the number of factors present in the graph
        and X are all the random variables present.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_factors(phi1, phi2)
        >>> G.add_nodes_from([phi1, phi2])
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        >>> G.get_factors()
        >>> G.get_partition_function()
        """
        factor = self.factors[0]
        factor = factor_product(
            factor, *[self.factors[i] for i in range(1, len(self.factors))]
        )
        if set(factor.scope()) != set(self.get_variable_nodes()):
            raise ValueError("DiscreteFactor for all the random variables not defined.")

        return np.sum(factor.values)

    def copy(self):
        """
        Returns a copy of the model.

        Returns
        -------
        FactorGraph : Copy of FactorGraph

        Examples
        --------
        >>> import numpy as np
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors.discrete import DiscreteFactor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = DiscreteFactor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = DiscreteFactor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_factors(phi1, phi2)
        >>> G.add_nodes_from([phi1, phi2])
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        >>> G_copy = G.copy()
        >>> G_copy.nodes()
        NodeView((<Factor representing phi(b:2, c:2) at 0xb4badd4c>, 'b', 'c',
          'a', <Factor representing phi(a:2, b:2) at 0xb4badf2c>))

        """
        copy = FactorGraph(self.edges())
        copy.add_nodes_from(self.nodes())

        if self.factors:
            factors_copy = [factor.copy() for factor in self.factors]
            copy.add_factors(*factors_copy)

        return copy

redpajama_set_name: RedPajamaGithub


text:
sudo killall xbee_proxy
sudo killall erasure_proxy
sudo killall sensor_server
sudo killall vlc
sudo killall rocket.sh


text:
define(['require'], function(require){

    return {templateUrl: require.toUrl('./partials/notifications-full.html')}

});


text:
package com.android.documentsui;

import static com.android.documentsui.Shared.DEBUG;

import android.annotation.IntDef;
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.Log;
import android.view.View;
import android.widget.Toolbar;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * A facade over the various pieces comprising "roots fragment in a Drawer".
 *
 * @see DrawerController#create(DrawerLayout)
 */
abstract class DrawerController implements DrawerListener {
    public static final String TAG = "DrawerController";

    // Drawer opening triggered by tapping the navigation icon
    public static final int OPENED_HAMBURGER = 0;
    // Drawer opening triggered by swiping right from the edge of the screen
    public static final int OPENED_SWIPE = 1;
    // Mostly programmatically forced drawer opening
    public static final int OPENED_OTHER = 2;

    @IntDef(flag = true, value = {
            OPENED_HAMBURGER,
            OPENED_SWIPE,
            OPENED_OTHER
    })
    @Retention(RetentionPolicy.SOURCE)
    public @interface Trigger {}

    /**
     * Toggles the drawer and sets the OPENED_OTHER as the action that causes opening the drawer.
     * @param open
     */
    abstract void setOpen(boolean open);

    /**
     * Toggles the drawer.
     * @param open
     * @param trigger Indicates what action caused opening the drawer. It is ignored for closing.
     */
    abstract void setOpen(boolean open, @Trigger int trigger);
    abstract boolean isPresent();
    abstract boolean isOpen();
    abstract void setTitle(String title);
    abstract void update();

    /**
     * Returns a controller suitable for {@code Layout}.
     */
    static DrawerController create(Activity activity) {

        DrawerLayout layout = (DrawerLayout) activity.findViewById(R.id.drawer_layout);

        if (layout == null) {
            return new DummyDrawerController();
        }

        View drawer = activity.findViewById(R.id.drawer_roots);
        Toolbar toolbar = (Toolbar) activity.findViewById(R.id.roots_toolbar);

        drawer.getLayoutParams().width = calculateDrawerWidth(activity);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                activity,
                layout,
                R.drawable.ic_hamburger,
                R.string.drawer_open,
                R.string.drawer_close);

        return new RuntimeDrawerController(layout, drawer, toggle, toolbar);
    }

    /**
     * Returns a controller suitable for {@code Layout}.
     */
    static DrawerController createDummy() {
        return new DummyDrawerController();
    }

    private static int calculateDrawerWidth(Activity activity) {
        // Material design specification for navigation drawer:
        // https://www.google.com/design/spec/patterns/navigation-drawer.html
        float width = Display.screenWidth(activity) - Display.actionBarHeight(activity);
        float maxWidth = activity.getResources().getDimension(R.dimen.max_drawer_width);
        int finalWidth = (int) ((width > maxWidth ? maxWidth : width));

        if (DEBUG)
            Log.d(TAG, "Calculated drawer width:" + (finalWidth / Display.density(activity)));

        return finalWidth;
    }

    /**
     * Runtime controller that manages a real drawer.
     */
    private static final class RuntimeDrawerController extends DrawerController {
        private final ActionBarDrawerToggle mToggle;
        private DrawerLayout mLayout;
        private View mDrawer;
        private Toolbar mToolbar;
        private @Trigger int mTrigger = OPENED_OTHER;

        public RuntimeDrawerController(
                DrawerLayout layout, View drawer, ActionBarDrawerToggle toggle,
                Toolbar drawerToolbar) {
            mToolbar = drawerToolbar;
            assert(layout != null);

            mLayout = layout;
            mDrawer = drawer;
            mToggle = toggle;

            mLayout.setDrawerListener(this);
        }

        @Override
        void setOpen(boolean open) {
            setOpen(open, OPENED_OTHER);
        }

        @Override
        void setOpen(boolean open, @Trigger int trigger) {
            if (open) {
                mLayout.openDrawer(mDrawer);
                mTrigger = trigger;
            } else {
                mLayout.closeDrawer(mDrawer);
            }
        }

        @Override
        boolean isOpen() {
            return mLayout.isDrawerOpen(mDrawer);
        }

        @Override
        boolean isPresent() {
            return true;
        }

        @Override
        void setTitle(String title) {
            mToolbar.setTitle(title);
        }

        @Override
        void update() {
            mToggle.syncState();
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            mToggle.onDrawerSlide(drawerView, slideOffset);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            mToggle.onDrawerOpened(drawerView);
            Metrics.logDrawerOpened(mToolbar.getContext(), mTrigger);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            mToggle.onDrawerClosed(drawerView);
            mTrigger = OPENED_OTHER;
        }

        @Override
        public void onDrawerStateChanged(int newState) {
            mToggle.onDrawerStateChanged(newState);
            if (newState == DrawerLayout.STATE_DRAGGING) {
                mTrigger = OPENED_SWIPE;
            }
        }
    }

    /*
     * Dummy controller useful with clients that don't host a real drawer.
     */
    private static final class DummyDrawerController extends DrawerController {

        @Override
        void setOpen(boolean open) {}

        @Override
        void setOpen(boolean open, @Trigger int trigger) {}

        @Override
        boolean isOpen() {
            return false;
        }

        @Override
        boolean isPresent() {
            return false;
        }

        @Override
        void setTitle(String title) {}

        @Override
        void update() {}

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {}

        @Override
        public void onDrawerOpened(View drawerView) {}

        @Override
        public void onDrawerClosed(View drawerView) {}

        @Override
        public void onDrawerStateChanged(int newState) {}
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;

namespace OnlineMediaAnalyzer.Models
{
    public class Category
    {
        public int ID { get; set; }

        [Required(ErrorMessage = "Name is required")]
        [StringLength(64, ErrorMessage = "Name length should be less than 64")]
        public string Name { get; set; }

        [StringLength(128, ErrorMessage = "Url length should be less than 128")]
        public string Url { get; set; }

        public int FeedID { get; set; }
        public virtual Feed Feed { get; set; }

        public virtual ICollection<Article> Articles { get; set; }

        [StringLength(32)]
        public string Self
        {
            get
            {
                return string.Format(CultureInfo.CurrentCulture,
                    "api/categories/{0}", this.ID);
            }
            set { }
        }
    }
}


text:
package org.neo4art.domain;

/**
 *
 * @author Mattia Zaratin
 * @since 30 Apr 2015
 */
public class Coordinates {

  public static final int COMPUTED   = 0;
  public static final int UNCOMPLETE = 1;

  private String          name;
  private String          map;

  private Double          latD;
  private Double          latM;
  private Double          latS;
  private String          latNS;

  private Double          longD;
  private Double          longM;
  private Double          longS;
  private String          longEW;

  private Double          coordsRef;

  private Double          latitude;
  private Double          longitude;

  public Coordinates() {

    this.name = null;
    this.map = null;

    this.latD = null;
    this.latM = null;
    this.latS = null;
    this.latNS = null;

    this.longD = null;
    this.longM = null;
    this.longS = null;
    this.longEW = null;

    this.coordsRef = null;

    this.latitude = null;
    this.longitude = null;
  }

  public String getName() {
    return name;
  }

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

  public String getMap() {
    return map;
  }

  public void setMap(String map) {
    this.map = map;
  }

  public Double getLatD() {
    return latD;
  }

  public void setLatD(Double latD) {
    this.latD = latD;
  }

  public Double getLatM() {
    return latM;
  }

  public void setLatM(Double latM) {
    this.latM = latM;
  }

  public Double getLatS() {
    return latS;
  }

  public void setLatS(Double latS) {
    this.latS = latS;
  }

  public String getLatNS() {
    return latNS;
  }

  public void setLatNS(String latNS) {
    this.latNS = latNS;
  }

  public Double getLongD() {
    return longD;
  }

  public void setLongD(Double longD) {
    this.longD = longD;
  }

  public Double getLongM() {
    return longM;
  }

  public void setLongM(Double longM) {
    this.longM = longM;
  }

  public Double getLongS() {
    return longS;
  }

  public void setLongS(Double longS) {
    this.longS = longS;
  }

  public String getLongEW() {
    return longEW;
  }

  public void setLongEW(String longEW) {
    this.longEW = longEW;
  }

  public Double getCoordsRef() {
    return coordsRef;
  }

  public void setCoordsRef(Double coordsRef) {
    this.coordsRef = coordsRef;
  }

  public Double getLatitude() {

    if (this.latitude == null && this.latD != null && this.latM != null && this.latS != null) {

      latitude  = this.latD;
      latitude += this.latM / 60;
      latitude += this.latS / 3600;
    }

    return latitude;
  }

  public void setLatitude(Double latitude) {
    this.latitude = latitude;
  }

  public Double getLongitude() {

    if (this.longitude == null && this.longD != null && this.longM != null && this.longS != null) {

      longitude  = this.longD;
      longitude += this.longM / 60;
      longitude += this.longS / 3600;
    }

    return longitude;
  }

  public void setLongitude(Double longitude) {
    this.longitude = longitude;
  }

  public int getStatus() {
    return (this.getLatitude() != null && this.getLongitude() != null) ? COMPUTED : UNCOMPLETE;
  }
}


text:
Version 5.8.1

* Improved slugify; now all blank spaces in id values are rendered as '-'

Version 5.8.0

* Introduced simplified new format for in-document auto-numbering options

## Version 5.7.1

* Fixed a long-hunted bug: markdown-it failure in some valid but less usual use cases, such as: paragraph in next line after heading, HTML comment before heading, end-of file at the end line of a paragraph following some heading

## Version 5.7.0

* Improved handling of the case of invalid JSON in the in-doc auto-numbering specifications

## Version 5.6.0

* New major feature: heading number iterates not only by numbers or letters, but also by array of "numbers", such as ["One", "Two", "Three"]
* Regression issue fix: arrays in user options are not overridden by default, first of all, `includeLevel` used in TOC

## Version 5.5.4

* Many improvements related to auto-numbering options, defaults and handling the options and the defaults
* Improved syntax coloring for extended syntactic features

* Fixed a bug with second run of embedded markdown-it plugin: TOC was not updated

## Version 5.5.3

* Fixed a bug with second run of embedded markdown-it plugin: TOC was not updated

## Version 5.5.1

* Fixed regression bug in auto-numbering, related to handling of RegExp failure: if first token is paragraph and not a auto-numbering settings tag, it wasn't rendering

## Version 5.5.0

* Fixed known bugs in 5.4.0: incorrect auto numbering default in settings, redundant re-setting of handler in the embedded markdown-it plugin

## Version 5.4.0

* Added user-configurable auto-numbering

## Version 5.3.0

* Fixed critical bugs in the embedded markdown-it plug-in: shifted sequence of `id` values in TOC when some heading levels are excluded

## Version 5.2.0

* Fixed critical bugs in the embedded markdown-it plug-in: shifted sequence of `id` values in headings when "no-TOC" features is used

## Version 5.1.0

* Found critical bugs in the legacy code of the embedded markdown-it plug-in, so this module is fully re-written

## Version 5.0.0

* Added advanced Markdown extension features based on embedded markdown-it plug-in:
	- Syntax extension: a tag to mark a heading to be excluded from TOC
	- Extended options to make a choice between `ul` or `ol` elements in TOC, either globally or per TOC level
	- Extended options to add sets of HTML attributes to TOC list elements, either globally or per TOC level
* Added images to conversion and preview commands and menu items to the editor title
* Improved logo

## Version 4.3.0

* Added logo
* Minor fixes (non-functional)

## Version 4.2.0

* Table of Contents and generation of heading `id` attributes unified in a single embedded module.
* Added settings option: "markdown.extension.convertToHtml.options.headingIdPrefix", default "heading."
* Fixed a bug in heading `id` attribute generation; now the set of used `id` values is reset on each rendering

## Version 4.1.0

* Added settings option: "markdown.extension.convertToHtml.tocIncludeLevels", default [1, 2, 3, 4, 5, 6]
* Added settings option: "markdown.extension.convertToHtml.tocContainerClass", default "toc"
* Added settings option: "markdown.extension.convertToHtml.tocListType", default "ul" (later removed SA???)

## Version 4.0.0

* Found critical bug in the external "markdown-it-named-headers" and "markdown-it-table-of-contents": generated id values of headers were not unique. As a work-around, these external modules are eliminated and replaced with modules embedded in the extension.

Major version is incremented because the default Markdown pattern for Table of Content has changed to `^\[\]\(toc\)`, which means "`[](toc)`" at the beginning of line. Potentially, it could break backward compatibility with existing Markdown documents using "`[[toc]]`", but it's easy to fix.

## Version 3.0.0

* Location of the included file is now relative to the Markdown document location

## Version 2.3.0

* Implemented extensible Markdown syntax coloring for each plug-in syntax, user-configurable
* Implemented user-configurable syntax coloring for document title in input Markdown
* Implemented file includes, with user-configurable syntax coloring
* Added keybinding, to overwrite "VS Code Markdown" preview key bindings

## Version 2.2.0

* Implemented preview identical to generated HTML
* Improved performance (lazy evaluation of markdown-it module setup and settings)
* In settings, implemented "outputPath" option

## Version 2.1.0

* Minor code fixes: turned on JavaScript strict mode; it revealed some undeclared variables, fixed; none of those problems were functional
* Added forgotten and important `<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>` element to the HTML template

## Version 2.0.0

* New feature introduced: user-installed additional markdown-it plug-ins, configurable through the "settings.json" of the extension

## Version 1.2.0

* Some "markdown-it" options and "markdown-it-named-headers" plug-in exposed as optional: 6 new options added to extension settings
* Fixed CSS relative path in generated HTML: on Windows, backslash separator replaced with /

## Version 1.1.1

* Fixed a bug in a relative path to CSS files

## Version 1.1.0

* Implemented new settings option: "markdown.extension.convertToHtml.embedCss"
* Multiple CSS files listed in "markdown.styles" option are supported
* For CSS files, path relative to HTML path is calculated

## Version 1.0.3

* README fix: corrected linking to https://vsmarketplacebadge.apphb.com/version/sakryukov.convert-markdown-to-html.svg and extension page

## Version 1.0.2

* Cosmetic code and README fixes

## Version 1.0.1

* Updated README to include release version image from https://vsmarketplacebadge.apphb.com/version/sakryukov.convert-markdown-to-html.svg

## Version 1.0.0

* Initial production release

## Version 0.1.0

* Initial release


text:
<?php
class MessageController extends UserAreaController
{
    public function actionHistory($userId = null)
    {

        if (Yii::app()->request->isPostRequest && !empty($userId)){
            $message = new Message();
            $message->user_from_id = $this->user->id;
            $message->user_to_id = $userId;
            $message->body = $_POST['Message']['body'];
            $message->created_at = date('Y-m-d H:i:s');
            $message->save();
            $this->user->refresh();
        }

        $allMessages  = $this->user->messages;
        $participants = array_filter(Message::getParticipants($allMessages), function($user) {
            return $user->id != $this->user->id;
        });

        $participantsMessageCount = [];

        sort($participants);

        foreach ($participants as $participant){
            $participantsMessageCount[$participant->id]= count(array_filter($allMessages, function (Message $message) use ($participant) {
                return $message->userFrom->id == $participant->id
                || $message->userTo->id == $participant->id;
            }));
        }

        $currentParticipant = empty($userId)
            ? $participants[0]
            : User::model()->findByPk($userId);

        $criteria = new CDbCriteria();
        $criteria->condition = '
            (user_from_id = :user_id AND user_to_id = :participant_id)
            OR (user_to_id = :user_id AND user_from_id = :participant_id)';

        $criteria->params = [
            ':user_id' => $this->user->id,
            ':participant_id' => $currentParticipant->id
        ];

        $criteria->order = 'created_at DESC';

        $dataProvider = new CActiveDataProvider('Message', [
            'pagination' => [
                'pageSize' => 5
            ],
            'criteria' => $criteria,
        ]);

        $this->render('history',[
            'messages' => $dataProvider->getData(),
            'participants' => $participants,
            'currentParticipant' => $currentParticipant,
            'participantsMessageCount' => $participantsMessageCount,
            'pagination' => $dataProvider->getPagination()
        ]);
    }

}


text:
class Fraction

  attr_accessor :numerator, :denominator

  def initialize (numerator, denominator)
    @numerator = numerator
    @denominator = denominator
  end

  def to_f
    numerator / denominator.to_f
  end

  def lowest
    divide = gcd(numerator, denominator)
    Fraction.new(numerator/divide, denominator/divide)
  end

  def to_s
    "#{numerator}/#{denominator}"
  end

  def gcd(a,b)
    return a if b == 0
    gcd(b, a%b)
  end
end

f = Fraction.new 50, 100
p f.numerator
p f.denominator
p f.to_f
p f.lowest.to_s
p f.to_s


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>pandas.TimedeltaIndex — pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="pandas.TimedeltaIndex.days" href="pandas.TimedeltaIndex.days.html" />
    <link rel="prev" title="pandas.DatetimeIndex.indexer_between_time" href="pandas.DatetimeIndex.indexer_between_time.html" />

Navigation

          index

          modules |

          next |

          previous |

pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation »

API Reference »

Table Of Contents

What's New

Installation

Contributing to pandas

Package overview

10 Minutes to pandas

Tutorials

Cookbook

Intro to Data Structures

Essential Basic Functionality

Working with Text Data

Options and Settings

Indexing and Selecting Data

MultiIndex / Advanced Indexing

Computational tools

Working with missing data

Group By: split-apply-combine

Merge, join, and concatenate

Reshaping and Pivot Tables

Time Series / Date functionality

Time Deltas

Categorical Data

Visualization

Styling

IO Tools (Text, CSV, HDF5, …)

Enhancing Performance

Sparse data structures

Frequently Asked Questions (FAQ)

rpy2 / R interface

pandas Ecosystem

Comparison with R / R libraries

Comparison with SQL

Comparison with SAS

Comparison with Stata

API Reference

Input/Output

General functions

Series

DataFrame

Panel

Index

Numeric Index

CategoricalIndex

IntervalIndex

MultiIndex

DatetimeIndex

TimedeltaIndex

pandas.TimedeltaIndex

pandas.TimedeltaIndex.days

pandas.TimedeltaIndex.seconds

pandas.TimedeltaIndex.microseconds

pandas.TimedeltaIndex.nanoseconds

pandas.TimedeltaIndex.components

pandas.TimedeltaIndex.inferred_freq

pandas.TimedeltaIndex.to_pytimedelta

pandas.TimedeltaIndex.to_series

pandas.TimedeltaIndex.round

pandas.TimedeltaIndex.floor

pandas.TimedeltaIndex.ceil

pandas.TimedeltaIndex.to_frame

Components

Conversion

PeriodIndex

Scalars

Frequencies

Window

GroupBy

Resampling

Style

Plotting

General utility functions

Extensions

Developer

Internals

Extending Pandas

Release Notes

Search

                <form class="search" action="../search.html" method="get">
                    <input type="text" name="q" size="18"/>
                    <input type="submit" value="Go"/>
                    <input type="hidden" name="check_keywords" value="yes"/>
                    <input type="hidden" name="area" value="default"/>
                </form>

                    Enter search terms or a module, class or function name.

pandas.TimedeltaIndex¶

class pandas.TimedeltaIndex[source]¶

Immutable ndarray of timedelta64 data, represented internally as int64, and
which can be boxed to timedelta objects

<col class="field-name" />
<col class="field-body" />

Parameters:
data : array-like (1-dimensional), optional

Optional timedelta-like data to construct index with

unit: unit of the arg (D,h,m,s,ms,us,ns) denote the unit, optional

which is an integer/float number

freq: a frequency for the index, optional

copy : bool

Make a copy of input ndarray

start : starting value, timedelta-like, optional

If data is None, start is used as the start point in generating regular
timedelta data.

periods : int, optional, > 0

Number of periods to generate, if generating index. Takes precedence
over end argument

end : end time, timedelta-like, optional

If periods is none, generated index will extend to first conforming
time on or just past end argument

closed : string or None, default None

Make the interval closed with respect to the given frequency to
the 'left', 'right', or both sides (None)

name : object

Name to be stored in the index

See also

Index

The base pandas Index type

Timedelta

Represents a duration between two dates or times.

DatetimeIndex

Index of datetime64 data

PeriodIndex

Index of Period data

Notes

To learn more about the frequency strings, please see this link.

Attributes

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

days
Number of days for each element.

seconds
Number of seconds (>= 0 and less than 1 day) for each element.

microseconds
Number of microseconds (>= 0 and less than 1 second) for each element.

nanoseconds
Number of nanoseconds (>= 0 and less than 1 microsecond) for each element.

components
Return a dataframe of the components (days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.

inferred_freq
Tries to return a string representing a frequency guess, generated by infer_freq.

Methods

<colgroup>
<col width="10%" />
<col width="90%" />
</colgroup>

to_pytimedelta()
Return TimedeltaIndex as object ndarray of datetime.timedelta objects

to_series([index, name])
Create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index

round(freq, *args, **kwargs)
round the data to the specified freq.

floor(freq)
floor the data to the specified freq.

ceil(freq)
ceil the data to the specified freq.

to_frame([index])
Create a DataFrame with a column containing the Index.

Navigation

          index

          modules |

          next |

          previous |

pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation »

API Reference »

Scroll To Top


text:
require "game"
--require "SFML"
require "timer"

math.randomseed(os.time())

tileSize = 53
zoom= 1

Game.tileChanged = function (x,y,id)
	tilemap:setIDForTile(id,x-1,y-1)
end

Game.stateChanged = function (newState)
	print("state "..newState)
end

window = sfRenderWindow.new(sfVideoMode.new(10*tileSize*zoom,16*tileSize*zoom,32),"Tetris",sfWindowStyle.Titlebar + sfWindowStyle.Close  );
window:setFramerateLimit(30)
window:setKeyRepeatEnabled(false)

texture =  sfTexture.new();
texture:loadFromFile("tetris_tiles-53.png");
texture:setSmooth(true);

tilemap = sfeTileMap.new();
tilemap:setSize(10,16)--game.mapWidth,game.mapHeight);
tilemap:setTexture(texture);
tilemap:setTileSize(tileSize,tileSize);
tilemap:scale(zoom,zoom)

game = Game:new();
clearColor = sfColor.new(0,0,0);
stepTimer = Timer:new(Game.step,game);
stepTimer:start(1,true);

event = sfEvent.new();
while window:isOpen() do
	i = 0;
	while window:pollEvent(event) do
		if(event:type() == sfEventType.Closed) then window:close(); end
		if(event:type() == sfEventType.KeyReleased and event:key():code() == sfKey.Escape ) then window:close(); end
		if(event:type() == sfEventType.KeyReleased and event:key():code() == sfKey.Q and event:key():system() == true ) then window:close(); end
		if(event:type() == sfEventType.KeyReleased and event:key():code() == sfKey.Left ) then game:moveLeft(); end
		if(event:type() == sfEventType.KeyReleased and event:key():code() == sfKey.Right) then game:moveRight(); end
		if(event:type() == sfEventType.KeyReleased and event:key():code() == sfKey.Space) then game:rotateRight(); end
		if(event:type() == sfEventType.KeyReleased and event:key():code() == sfKey.Down)  then game:step(); end
	end
	stepTimer:update();
	window:clear(clearColor);
	window:draw(tilemap);
	window:display();
end