text:
package foss.devmapal.axis_allies_calc.axis_allies_calc;

import android.app.ActionBar;
import android.support.v4.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import org.json.JSONArray;
import org.json.JSONException;

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

public class MainActivity extends FragmentActivity
        implements LandFragment.OnFragmentInteractionListener,
                   NavalFragment.OnFragmentInteractionListener {

    private static final String LAND_BATTLE = "land_battle";
    private static final String NAVAL_BATTLE = "naval_battle";
    private static final String ARG_ATTACKER = "attacker";
    private static final String ARG_ATTACKER_WD = "attacker_wd";
    private static final String ARG_DEFENDER = "defender";
    private static final String ARG_DEFENDER_WD = "defender_wd";
    private static final int LAND_POS = 0;
    private static final int NAVAL_POS = 1;

    private ViewPager mViewPager;
    private TabsAdapter mTabsAdapter;

    private Bundle land_fragment_data;
    private Bundle naval_fragment_data;

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

        land_fragment_data = new Bundle();
        naval_fragment_data = new Bundle();
        int pos = LAND_POS;
        if(savedInstanceState != null) {
            restore_state_from_saved_instance_state(savedInstanceState);
        } else {
            pos = restore_state_from_preference();
        }

        mViewPager = new ViewPager(this);
        mViewPager.setId(R.id.viewpager);
        setContentView(mViewPager);

        final ActionBar bar = getActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

        mTabsAdapter = new TabsAdapter(this, mViewPager);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.title_land_battle),
                LandFragment.class, land_fragment_data);
        mTabsAdapter.addTab(bar.newTab().setText(R.string.title_naval_battle),
                NavalFragment.class, naval_fragment_data);

        if (savedInstanceState != null) {
            bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", LAND_POS));
        }
        else {
            bar.setSelectedNavigationItem(pos);
        }
        if (BuildConfig.DEBUG) {
            Log.e(Constants.LOG, "onCreate");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putBundle(LAND_BATTLE, land_fragment_data);
        savedInstanceState.putBundle(NAVAL_BATTLE, naval_fragment_data);
        savedInstanceState.putInt("tab", getActionBar().getSelectedNavigationIndex());

        if (BuildConfig.DEBUG) {
            Log.e(Constants.LOG, "onSaveInstanceState");
        }

        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (BuildConfig.DEBUG) {
            Log.e(Constants.LOG, "onStop");
        }
        save_state_to_preference();
        mTabsAdapter = null;
        mViewPager = null;
    }

    private void restore_state_from_saved_instance_state(Bundle savedInstanceState) {
        if (BuildConfig.DEBUG) {
            Log.e(Constants.LOG, "restore_state_from_saved_instance_state");
        }
        land_fragment_data = savedInstanceState.getBundle(LAND_BATTLE);
        naval_fragment_data = savedInstanceState.getBundle(NAVAL_BATTLE);
    }

    private int restore_state_from_preference() {
        SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
        int defaultValue = 0;
        boolean defaultBool = false;
        String defaultJSON = "[]";

        // Restore Land BattleSimulation input
        Army attacker = new Army(
                sharedPref.getInt("a_land_" + Infantry.name, defaultValue),
                sharedPref.getInt("a_land_" + Artillery.name, defaultValue),
                sharedPref.getInt("a_land_" + Tank.name, defaultValue),
                sharedPref.getInt("a_land_" + Fighter.name, defaultValue),
                sharedPref.getInt("a_land_" + Bomber.name, defaultValue),
                sharedPref.getInt("a_land_" + Battleship.name, defaultValue),
                sharedPref.getInt("a_land_" + Destroyer.name, defaultValue),
                defaultValue,
                defaultValue,
                defaultValue,
                sharedPref.getInt("a_land_" + AntiaircraftGun.name, defaultValue)
        );

        WeaponsDevelopment attacker_wd = new WeaponsDevelopment(
                sharedPref.getBoolean("a_land_" + getString(R.string.jet_fighters), defaultBool),
                defaultBool,
                sharedPref.getBoolean("a_land_" + getString(R.string.combined_bombardment), defaultBool),
                sharedPref.getBoolean("a_land_" + getString(R.string.heavy_bombers), defaultBool)
        );

        Army defender = new Army(
                sharedPref.getInt("d_land_" + Infantry.name, defaultValue),
                sharedPref.getInt("d_land_" + Artillery.name, defaultValue),
                sharedPref.getInt("d_land_" + Tank.name, defaultValue),
                sharedPref.getInt("d_land_" + Fighter.name, defaultValue),
                sharedPref.getInt("d_land_" + Bomber.name, defaultValue),
                sharedPref.getInt("d_land_" + Battleship.name, defaultValue),
                sharedPref.getInt("d_land_" + Destroyer.name, defaultValue),
                defaultValue,
                defaultValue,
                defaultValue,
                sharedPref.getInt("d_land_" + AntiaircraftGun.name, defaultValue)
        );

        WeaponsDevelopment defender_wd = new WeaponsDevelopment(
                sharedPref.getBoolean("d_land_" + getString(R.string.jet_fighters), defaultBool),
                defaultBool,
                sharedPref.getBoolean("d_land_" + getString(R.string.combined_bombardment), defaultBool),
                sharedPref.getBoolean("d_land_" + getString(R.string.heavy_bombers), defaultBool)
        );

        land_fragment_data.putSerializable(ARG_ATTACKER, attacker);
        land_fragment_data.putSerializable(ARG_ATTACKER_WD, attacker_wd);
        land_fragment_data.putSerializable(ARG_DEFENDER, defender);
        land_fragment_data.putSerializable(ARG_DEFENDER_WD, defender_wd);

        // Restore Naval BattleSimulation input
        attacker = new Army(
                defaultValue,
                defaultValue,
                defaultValue,
                sharedPref.getInt("a_naval_" + Fighter.name, defaultValue),
                sharedPref.getInt("a_naval_" + Bomber.name, defaultValue),
                sharedPref.getInt("a_naval_" + Battleship.name, defaultValue),
                sharedPref.getInt("a_naval_" + Destroyer.name, defaultValue),
                sharedPref.getInt("a_naval_" + Aircraftcarrier.name, defaultValue),
                sharedPref.getInt("a_naval_" + Transport.name, defaultValue),
                sharedPref.getInt("a_naval_" + Submarine.name, defaultValue),
                sharedPref.getInt("a_naval_" + AntiaircraftGun.name, defaultValue)
        );

        attacker_wd = new WeaponsDevelopment(
                sharedPref.getBoolean("a_naval_" + getString(R.string.jet_fighters), defaultBool),
                sharedPref.getBoolean("a_naval_" + getString(R.string.super_submarines), defaultBool),
                defaultBool,
                sharedPref.getBoolean("a_naval_" + getString(R.string.heavy_bombers), defaultBool)
        );

        defender = new Army(
                defaultValue,
                defaultValue,
                defaultValue,
                sharedPref.getInt("d_naval_" + Fighter.name, defaultValue),
                sharedPref.getInt("d_naval_" + Bomber.name, defaultValue),
                sharedPref.getInt("d_naval_" + Battleship.name, defaultValue),
                sharedPref.getInt("d_naval_" + Destroyer.name, defaultValue),
                sharedPref.getInt("d_naval_" + Aircraftcarrier.name, defaultValue),
                sharedPref.getInt("d_naval_" + Transport.name, defaultValue),
                sharedPref.getInt("d_naval_" + Submarine.name, defaultValue),
                sharedPref.getInt("d_naval_" + AntiaircraftGun.name, defaultValue)
        );

        defender_wd = new WeaponsDevelopment(
                sharedPref.getBoolean("d_naval_" + getString(R.string.jet_fighters), defaultBool),
                sharedPref.getBoolean("d_naval_" + getString(R.string.super_submarines), defaultBool),
                defaultBool,
                sharedPref.getBoolean("d_naval_" + getString(R.string.heavy_bombers), defaultBool)
        );

        naval_fragment_data.putSerializable(ARG_ATTACKER, attacker);
        naval_fragment_data.putSerializable(ARG_ATTACKER_WD, attacker_wd);
        naval_fragment_data.putSerializable(ARG_DEFENDER, defender);
        naval_fragment_data.putSerializable(ARG_DEFENDER_WD, defender_wd);

        return sharedPref.getInt("tab", LAND_POS);
    }

    private void save_state_to_preference() {
        SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();

        // Store land battle data
        Army attacker = (Army) land_fragment_data.getSerializable(ARG_ATTACKER);
        editor.putInt("a_land_" + Infantry.name, attacker.get_infantry());
        editor.putInt("a_land_" + Artillery.name, attacker.get_artillery());
        editor.putInt("a_land_" + Tank.name, attacker.get_tanks());
        editor.putInt("a_land_" + Fighter.name, attacker.get_fighters());
        editor.putInt("a_land_" + Bomber.name, attacker.get_bombers());
        editor.putInt("a_land_" + Battleship.name, attacker.get_battleships());
        editor.putInt("a_land_" + Destroyer.name, attacker.get_destroyers());
        editor.putInt("a_land_" + AntiaircraftGun.name, attacker.get_antiaircraftguns());

        WeaponsDevelopment attacker_wd =
                (WeaponsDevelopment) land_fragment_data.getSerializable(ARG_ATTACKER_WD);
        editor.putBoolean("a_land_" + getString(R.string.jet_fighters), attacker_wd.jet_fighters);
        editor.putBoolean("a_land_" + getString(R.string.combined_bombardment), attacker_wd.combined_bombardment);
        editor.putBoolean("a_land_" + getString(R.string.heavy_bombers), attacker_wd.heavy_bombers);

        Army defender = (Army) land_fragment_data.getSerializable(ARG_DEFENDER);
        editor.putInt("d_land_" + Infantry.name, defender.get_infantry());
        editor.putInt("d_land_" + Artillery.name, defender.get_artillery());
        editor.putInt("d_land_" + Tank.name, defender.get_tanks());
        editor.putInt("d_land_" + Fighter.name, defender.get_fighters());
        editor.putInt("d_land_" + Bomber.name, defender.get_bombers());
        editor.putInt("d_land_" + Battleship.name, defender.get_battleships());
        editor.putInt("d_land_" + Destroyer.name, defender.get_destroyers());
        editor.putInt("d_land_" + AntiaircraftGun.name, defender.get_antiaircraftguns());

        WeaponsDevelopment defender_wd =
                (WeaponsDevelopment) land_fragment_data.getSerializable(ARG_DEFENDER_WD);
        editor.putBoolean("d_land_" + getString(R.string.jet_fighters), defender_wd.jet_fighters);
        editor.putBoolean("d_land_" + getString(R.string.combined_bombardment), defender_wd.combined_bombardment);
        editor.putBoolean("d_land_" + getString(R.string.heavy_bombers), defender_wd.heavy_bombers);

        // Store naval battle data
        attacker = (Army) naval_fragment_data.getSerializable(ARG_ATTACKER);
        editor.putInt("a_naval_" + Fighter.name, attacker.get_fighters());
        editor.putInt("a_naval_" + Bomber.name, attacker.get_bombers());
        editor.putInt("a_naval_" + Battleship.name, attacker.get_battleships());
        editor.putInt("a_naval_" + Destroyer.name, attacker.get_destroyers());
        editor.putInt("a_naval_" + Aircraftcarrier.name, attacker.get_aircraftcarriers());
        editor.putInt("a_naval_" + Transport.name, attacker.get_transports());
        editor.putInt("a_naval_" + Submarine.name, attacker.get_submarines());
        editor.putInt("a_naval_" + AntiaircraftGun.name, attacker.get_antiaircraftguns());

        attacker_wd = (WeaponsDevelopment) naval_fragment_data.getSerializable(ARG_ATTACKER_WD);
        editor.putBoolean("a_naval_" + getString(R.string.jet_fighters), attacker_wd.jet_fighters);
        editor.putBoolean("a_naval_" + getString(R.string.super_submarines), attacker_wd.super_submarines);
        editor.putBoolean("a_naval_" + getString(R.string.heavy_bombers), attacker_wd.heavy_bombers);

        defender = (Army) naval_fragment_data.getSerializable(ARG_DEFENDER);
        editor.putInt("d_naval_" + Fighter.name, defender.get_fighters());
        editor.putInt("d_naval_" + Bomber.name, defender.get_bombers());
        editor.putInt("d_naval_" + Battleship.name, defender.get_battleships());
        editor.putInt("d_naval_" + Destroyer.name, defender.get_destroyers());
        editor.putInt("d_naval_" + Aircraftcarrier.name, defender.get_aircraftcarriers());
        editor.putInt("d_naval_" + Transport.name, defender.get_transports());
        editor.putInt("d_naval_" + Submarine.name, defender.get_submarines());
        editor.putInt("d_naval_" + AntiaircraftGun.name, defender.get_antiaircraftguns());

        defender_wd = (WeaponsDevelopment) naval_fragment_data.getSerializable(ARG_DEFENDER_WD);
        editor.putBoolean("d_naval_" + getString(R.string.jet_fighters), defender_wd.jet_fighters);
        editor.putBoolean("d_naval_" + getString(R.string.super_submarines), defender_wd.super_submarines);
        editor.putBoolean("d_naval_" + getString(R.string.heavy_bombers), defender_wd.heavy_bombers);

        editor.putInt("tab", getActionBar().getSelectedNavigationIndex());

        editor.commit();
    }

    public void runAction() {
        Intent i;
        switch(getActionBar().getSelectedNavigationIndex()) {
            case LAND_POS:
                LandFragment land_fragment = (LandFragment) mTabsAdapter.
                                                              getFragment(R.id.viewpager, LAND_POS);
                land_fragment.getFields(land_fragment.getView());
                i = new Intent(this, ResultActivity.class);
                i.putExtra("attacker", land_fragment.getAttacker());
                i.putExtra("attacker_wd", land_fragment.getAttacker_wd());
                i.putExtra("defender", land_fragment.getDefender());
                i.putExtra("defender_wd", land_fragment.getDefender_wd());
                i.putExtra("land_battle", true);

                LandAttackerHitOrderFragment lahof =
                        (LandAttackerHitOrderFragment) getFragmentManager()
                                .findFragmentById(R.id.attacker_land_hit_order);
                i.putIntegerArrayListExtra("attacker_hit_order",
                           MainActivity.get_hit_order(lahof.get_hit_order()));

                LandDefenderHitOrderFragment ldhof =
                        (LandDefenderHitOrderFragment) getFragmentManager()
                                .findFragmentById(R.id.defender_land_hit_order);
                i.putIntegerArrayListExtra("defender_hit_order",
                        MainActivity.get_hit_order(ldhof.get_hit_order()));

                startActivity(i);
                break;
            case NAVAL_POS:
                NavalFragment naval_fragment = (NavalFragment) mTabsAdapter.
                        getFragment(R.id.viewpager, NAVAL_POS);
                naval_fragment.getFields(naval_fragment.getView());
                i = new Intent(this, ResultActivity.class);
                i.putExtra("attacker", naval_fragment.getAttacker());
                i.putExtra("attacker_wd", naval_fragment.getAttacker_wd());
                i.putExtra("defender", naval_fragment.getDefender());
                i.putExtra("defender_wd", naval_fragment.getDefender_wd());
                i.putExtra("land_battle", false);

                NavalAttackerHitOrderFragment nahof =
                        (NavalAttackerHitOrderFragment) getFragmentManager()
                                .findFragmentById(R.id.attacker_naval_hit_order);
                i.putIntegerArrayListExtra("attacker_hit_order",
                        MainActivity.get_hit_order(nahof.get_hit_order()));

                NavalDefenderHitOrderFragment ndhof =
                        (NavalDefenderHitOrderFragment) getFragmentManager()
                                .findFragmentById(R.id.defender_naval_hit_order);
                i.putIntegerArrayListExtra("defender_hit_order",
                        MainActivity.get_hit_order(ndhof.get_hit_order()));

                startActivity(i);
                break;
        }
    }

    public static ArrayList<Integer> get_hit_order(List<String> hit_order_str) {
        ArrayList<Integer> hit_order = new ArrayList<>();
        for(String hit_type: hit_order_str) {
            switch(hit_type) {
                case "Infantry":
                    hit_order.add(Infantry.id);
                    break;
                case "Artillery":
                    hit_order.add(Artillery.id);
                    break;
                case "Tank":
                    hit_order.add(Tank.id);
                    break;
                case "Fighter":
                    hit_order.add(Fighter.id);
                    break;
                case "Bomber":
                    hit_order.add(Bomber.id);
                    break;
                case "Transport":
                    hit_order.add(Transport.id);
                    break;
                case "Submarine":
                    hit_order.add(Submarine.id);
                    break;
                case "Destroyer":
                    hit_order.add(Destroyer.id);
                    break;
                case "Aircraftcarrier":
                    hit_order.add(Aircraftcarrier.id);
                    break;
                case "Battleship":
                    hit_order.add(Battleship.id);
                    break;
            }
        }

        return hit_order;
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (BuildConfig.DEBUG) {
            Log.e(Constants.LOG, "onOptionsItemSelected");
        }
        switch(item.getItemId()) {
            case R.id.action_settings:
                Intent i = new Intent(this, SettingsActivity.class);
                startActivity(i);
                return true;
            case R.id.action_clear:
                switch(getActionBar().getSelectedNavigationIndex()) {
                    case LAND_POS:
                        LandFragment land_fragment = (LandFragment) mTabsAdapter.
                                                        getFragment(R.id.viewpager, LAND_POS);
                        land_fragment.clear_fields();
                        LandAttackerHitOrderFragment lahof =
                                (LandAttackerHitOrderFragment) getFragmentManager()
                                        .findFragmentById(R.id.attacker_land_hit_order);
                        lahof.clear_fields();
                        LandDefenderHitOrderFragment ldhof =
                                (LandDefenderHitOrderFragment) getFragmentManager()
                                        .findFragmentById(R.id.defender_land_hit_order);
                        ldhof.clear_fields();
                        break;
                    case NAVAL_POS:
                        NavalFragment naval_fragment = (NavalFragment) mTabsAdapter.
                                                        getFragment(R.id.viewpager, NAVAL_POS);
                        naval_fragment.clear_fields();
                        NavalAttackerHitOrderFragment nahof =
                                (NavalAttackerHitOrderFragment) getFragmentManager()
                                        .findFragmentById(R.id.attacker_naval_hit_order);
                        nahof.clear_fields();
                        NavalDefenderHitOrderFragment ndhof =
                                (NavalDefenderHitOrderFragment) getFragmentManager()
                                        .findFragmentById(R.id.defender_naval_hit_order);
                        ndhof.clear_fields();
                }
                return true;
            case R.id.action_run:
                runAction();
                return true;
            case R.id.action_swap:
                switch(getActionBar().getSelectedNavigationIndex()) {
                    case LAND_POS:
                        LandFragment land_fragment = (LandFragment) mTabsAdapter.
                                getFragment(R.id.viewpager, LAND_POS);
                        land_fragment.swap();
                        break;
                    case NAVAL_POS:
                        NavalFragment naval_fragment = (NavalFragment) mTabsAdapter.
                                getFragment(R.id.viewpager, NAVAL_POS);
                        naval_fragment.swap();
                }
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSaveState(String id,
                            Army attacker,
                            WeaponsDevelopment attacker_wd,
                            Army defender,
                            WeaponsDevelopment defender_wd) {
        if(id.equals(getString(R.string.title_land_battle))) {
            land_fragment_data.putSerializable(ARG_ATTACKER, new Army(attacker));
            land_fragment_data.putSerializable(ARG_ATTACKER_WD, new WeaponsDevelopment(attacker_wd));
            land_fragment_data.putSerializable(ARG_DEFENDER, new Army(defender));
            land_fragment_data.putSerializable(ARG_DEFENDER_WD, new WeaponsDevelopment(defender_wd));
        }
        else if(id.equals(getString(R.string.title_naval_battle))) {
            naval_fragment_data.putSerializable(ARG_ATTACKER, new Army(attacker));
            naval_fragment_data.putSerializable(ARG_ATTACKER_WD, new WeaponsDevelopment(attacker_wd));
            naval_fragment_data.putSerializable(ARG_DEFENDER, new Army(defender));
            naval_fragment_data.putSerializable(ARG_DEFENDER_WD, new WeaponsDevelopment(defender_wd));
        }

        if (BuildConfig.DEBUG) {
            Log.e(Constants.LOG, "onSaveState");
        }
    }

    public void onCheckboxClicked(View view) {
        LandFragment land_fragment = (LandFragment) mTabsAdapter.
            getFragment(R.id.viewpager, LAND_POS);
        land_fragment.onCheckboxClicked(view);
    }

    public static class TabsAdapter extends FragmentPagerAdapter
            implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
        private final FragmentActivity mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(Class<?> _class, Bundle _args) {
                clss = _class;
                args = _args;
            }
        }

        public TabsAdapter(FragmentActivity activity, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mActionBar = activity.getActionBar();
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }
        public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
            TabInfo info = new TabInfo(clss, args);
            tab.setTag(info);
            tab.setTabListener(this);
            mTabs.add(info);
            mActionBar.addTab(tab);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            final InputMethodManager imm = (InputMethodManager) mContext.getSystemService(
                    Context.INPUT_METHOD_SERVICE);
            if(imm != null) {
                Fragment frag = getFragment(R.id.viewpager, position);
                if(frag != null) {
                    View view = frag.getView();
                    if(view != null)
                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            }
            mActionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            Object tag = tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i) == tag) {
                    mViewPager.setCurrentItem(i);
                }
            }
        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
        }

        private String makeFragmentName(int viewId, int position) {
            return "android:switcher:" + viewId + ":" + position;
        }

        public Fragment getFragment(int viewId, int position) {
            FragmentManager fm = mContext.getSupportFragmentManager();
            String tag = makeFragmentName(viewId, position);
            return fm.findFragmentByTag(tag);
        }
    }

    public interface Constants {
        String LOG = "foss.devmapal.axis_allies_calc.axis_allies_calc.MainActivity";
    }
}


text:
import sys

import mock
from osc_lib.tests import utils
import requests

from oslo_serialization import jsonutils

AUTH_TOKEN = "foobar"
AUTH_URL = "http://0.0.0.0"
USERNAME = "itchy"
PASSWORD = "scratchy"

TEST_RESPONSE_DICT_V3 = {
    "token": {
        "audit_ids": [
            "a"
        ],
        "catalog": [
        ],
        "expires_at": "2034-09-29T18:27:15.978064Z",
        "extras": {},
        "issued_at": "2014-09-29T17:27:15.978097Z",
        "methods": [
            "password"
        ],
        "project": {
            "domain": {
                "id": "default",
                "name": "Default"
            },
            "id": "bbb",
            "name": "project"
        },
        "roles": [
        ],
        "user": {
            "domain": {
                "id": "default",
                "name": "Default"
            },
            "id": "aaa",
            "name": USERNAME
        }
    }
}
TEST_VERSIONS = {
    "versions": {
        "values": [
            {
                "id": "v3.0",
                "links": [
                    {
                        "href": AUTH_URL,
                        "rel": "self"
                    }
                ],
                "media-types": [
                    {
                        "base": "application/json",
                        "type": "application/vnd.openstack.identity-v3+json"
                    },
                    {
                        "base": "application/xml",
                        "type": "application/vnd.openstack.identity-v3+xml"
                    }
                ],
                "status": "stable",
                "updated": "2013-03-06T00:00:00Z"
            }
        ]
    }
}

class FakeStdout(object):
    def __init__(self):
        self.content = []

    def write(self, text):
        self.content.append(text)

    def make_string(self):
        result = ''
        for line in self.content:
            result = result + line
        return result

class FakeApp(object):
    def __init__(self, _stdout):
        self.stdout = _stdout
        self.client_manager = None
        self.stdin = sys.stdin
        self.stdout = _stdout or sys.stdout
        self.stderr = sys.stderr

class FakeClient(object):
    def __init__(self, **kwargs):
        self.auth_url = kwargs['auth_url']
        self.token = kwargs['token']

class FakeClientManager(object):
    def __init__(self):
        self.compute = None
        self.identity = None
        self.image = None
        self.object_store = None
        self.volume = None
        self.network = None
        self.session = None
        self.auth_ref = None

class FakeModule(object):
    def __init__(self, name, version):
        self.name = name
        self.__version__ = version

class FakeResource(object):
    def __init__(self, manager, info, loaded=False):
        self.manager = manager
        self._info = info
        self._add_details(info)
        self._loaded = loaded

    def _add_details(self, info):
        for (k, v) in info.items():
            setattr(self, k, v)

    def __repr__(self):
        reprkeys = sorted(k for k in self.__dict__.keys() if k[0] != '_' and
                          k != 'manager')
        info = ", ".join("%s=%s" % (k, getattr(self, k)) for k in reprkeys)
        return "<%s %s>" % (self.__class__.__name__, info)

class FakeResponse(requests.Response):
    def __init__(self, headers={}, status_code=200, data=None, encoding=None):
        super(FakeResponse, self).__init__()

        self.status_code = status_code

        self.headers.update(headers)
        self._content = jsonutils.dump_as_bytes(data)

class FakeClusteringv1Client(object):
    def __init__(self, **kwargs):
        self.http_client = mock.Mock()
        self.http_client.auth_token = kwargs['token']
        self.profiles = FakeResource(None, {})

class TestClusteringv1(utils.TestCommand):
    def setUp(self):
        super(TestClusteringv1, self).setUp()

        self.app.client_manager.clustering = FakeClusteringv1Client(
            token=AUTH_TOKEN, auth_url=AUTH_URL
        )

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>BLOM 2.0: BLOM_ExtractModel.m File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

BLOM 2.0

Main Page

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

 All Files Functions

Functions

BLOM_ExtractModel.m File Reference

BLOM 2.0 Outline based on what we discussed previously.
More...

Functions

function 	BLOM_ExtractModel (in name, in horizon, in dt, in integ_method, in options)

 	This function extracts a Simulink model and is the first step into converting it into an optimization problem.

function 	findBlocks (in name)

 	Finds all Input, External, Constraint and Cost BLOM library blocks.

 	function ()

 	Find all connected source blocks using a breadth first search. Includes the handles already given.

function 	getOutports (in inports, in existingOutports, in iZero)

 	From given inports, see which outports are relevant.

function 	relevantTimes (in outportHandles)

 	Creates struct that says which outports are relevant at which times.

function 	makeStruct (in outportHandles, in name)

 	From outport list, create three different structures needed for the optimization problem.

Detailed Description

BLOM 2.0 Outline based on what we discussed previously.

Function Documentation

          function BLOM_ExtractModel
          (
          in
          name,

          in
          horizon,

          in
          dt,

          in
          integ_method,

          in
          options

          )

This function extracts a Simulink model and is the first step into converting it into an optimization problem.

Overview of BLOM Extract Model Structure

Find all Input, External, Constraint and Cost BLOM library blocks.

Build cost and constraint dependency wire graph, starting from Constraint and Cost blocks and traverse backwards.

BFS to find the graph.

Recognize reaching non-BLOM inputs (user error).

Format of the graph: Sparse connectivity matrix of all wires, store just the block handles.

Each wire has a property whether optimization variables is introduced for it for each derivative evaluation, intermediate major time step, initial time, final time.

Store for each wire, if it is constrained, cost (discrete or continuous), input, external.

Flatten the wires:

"Fetch" all PolyBlocks data: variables from the base workspace or values from the dialog (just do evalin('base',get_param(h,'A')).

Get all possible dimensions (with or without the Simulink "compile").

Translate all supported Simulink blocks to PolyBlocks using the known dimensions.

Eliminate duplicate routing variables.

Combine all PolyBlocks to a large P and K matrices.

Eliminate whatever is possible (constants, identity PolyBlocks, linearly dependent constraints, replicated P rows, unused terms).

Propagate time property information using the processed P and K structure.

Create the whole problem:

Introduce and duplicate all major time step variables, including their dependencies.

Introduce and duplicate minor time steps variables and their dependencies.

Link by the appropriate Butcher tableau values major and minor time steps variables.

Add move blocking constraints.

Eliminate whatever is possible.

Mark external, input.

Take care of cost. Examples: ModelSpec = BLOM_ExportModel; Converts current active model.

ModelSpec = BLOM_ExportModel('Sys',10,0.5); Converts current model 'Sys', with a a time step of 0.5 sec and 10 time steps. ModelSpec = BLOM_ExportModel('Sys',10,0.5,); Converts current model 'Sys', with a a time step of 0.5 sec and 10 time steps, assuming discrete model.

ModelSpec = BLOM_ExportModel('Sys',10,0.5,'Trapez'); Converts current model 'Sys', with a a time step of 0.5 sec ,10 time steps and trapezoidal discretization method.

Parameters:

name	name of the model to convert

horizon	integer number of steps in prediction horizon length, 1 if not supplied

dt	time step size [s], 1 if not supplied

disc	discretization method {'none,'Euler','Trapez','RK4'}

options	options created by BLOM_opset function

Return values:

out1	return value for the first output variable

out2	return value for the second output variable

          function findBlocks
          (
          in
          name	)

Finds all Input, External, Constraint and Cost BLOM library blocks.

More detailed description of the problem.

Parameters:

name	Name of the simulink model

Return values:

blockHandles	handles of all the relevant blocks

          function
          (
          	)

Find all connected source blocks using a breadth first search. Includes the handles already given.

More detailed description of the problem.

Parameters:

handleArray	the array of handles that you want to search. These are the block handles of the costs and constraints

varargin	the external and input from simulink handles. the sources of these blocks are not relevant to the optimization problem

Return values:

sourceHandles	return all the handles connected to input handles

stop	if there are any unconnected blocks or blocks that BLOM does not support, this parameter gives a 1 to indicate true and 0 to indicate false

boundsStruct	structure with fields: 1) outport handles found, 2) boolean true or false if it is connected to a bounds block

          function getOutports
          (
          in
          inports,

          in
          existingOutports,

          in
          iZero

          )

From given inports, see which outports are relevant.

More detailed description of the problem.

Parameters:

inports	inports of current source

existingOutports	current outports found. used to check for redundancy

iZero	current index of the first zero

Return values:

outportHandles	new outports found

iZero	updates current index of the first zero

          function makeStruct
          (
          in
          outportHandles,

          in
          name

          )

From outport list, create three different structures needed for the optimization problem.

More detailed description of the problem.

Parameters:

outportHandles	outportHandles found by searchSources

name	name of model

Return values:

optimVar	structure with fields 1) index of block name 2) index of port or vector

polyStruct	structure with fields 1) index of block name 2) P matrix 3) K matrix

blocks	structure with fields 1) name of block 2) handle of block

          function relevantTimes
          (
          in
          outportHandles	)

Creates struct that says which outports are relevant at which times.

More detailed description of the problem.

Parameters:

outportHandles	outportHandles found by searchSources

Return values:

timeStruct	structure with following fields. 1) outportHandles 2) majorTimeStep 3) minorTimeStep

<address class="footer">
Generated on Thu Aug 2 2012 12:07:47 for BLOM 2.0 by

 1.8.1.1
</address>


text:
using std::cout;
using std::endl;

int main( int argc, char* argv[] ) {
  int error = 0;

  // Set the node ID
  error = node_set_id( argv[1] );
  if ( error != 0 ) {
    cout << "Error in setting node ID" << endl;
    return error;
  }

  // Start communications
  error = comm_start( argv[2] );
  if ( error != 0 ) {
    cout << "Error in starting communications" << endl;
    return error;
  }

  cout << "Communication server started" << endl;

  // Start calculations
  error = calc_start();
  if ( error != 0 ) {
    cout << "Error in starting calculations" << endl;
    return error;
  }

  // Wait for calculations to complete
  calc_to_completion();

  return 0;
}


text:
import React, { Component } from 'react';
import { Treemap } from 'react-vis';
import Button from '../button';

function _getRandomData() {
  const totalLeaves = Math.random() * 20;
  const leaves = [];
  let title;
  for (let i = 0; i < totalLeaves; i++) {
    title = Math.random();
    if (Math.random() > 0.5) {
      title = (
        {title}
      );
    }
    leaves.push({
      title,
      size: Math.random() * 1000,
      color: Math.random()
    });
  }
  return {
    title: '',
    color: 1,
    children: leaves
  };
}

export default class DynamicTreeMap extends Component {
  state = {
    hoveredNode: false,
    treemapData: _getRandomData(),
    useCirclePacking: false
  }

  render() {
    const {hoveredNode, useCirclePacking} = this.state;
    const { width, height } = this.props;
    const treeProps = {
      animation: {
        damping: 9,
        stiffness: 300
      },
      data: this.state.treemapData,
      onLeafMouseOver: x => this.setState({hoveredNode: x}),
      onLeafMouseOut: () => this.setState({hoveredNode: false}),
      onLeafClick: () => this.setState({treemapData: _getRandomData()}),
      height: height,
      mode: this.state.useCirclePacking ? 'circlePack' : 'squarify',
      width: width,
    };
    return (

          <Button
            onClick={() => this.setState({useCirclePacking: !useCirclePacking})}
            buttonContent={'TOGGLE CIRCLE PACK'} />

        <Treemap {...treeProps}/>
        click above to the update data
        {hoveredNode && hoveredNode.value}

    );
  }

}


text:
using System.Collections.Generic;

namespace Lunchorder.Domain.Dtos
{
    /// <summary>
    /// The history of the vendor
    /// </summary>
    public class VendorOrderHistory
    {
        /// <summary>
        /// An identifier for the order history at the vendor
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// The id of the vendor
        /// </summary>
        public string VendorId { get; set; }

        /// <summary>
        /// The date for the order in yyyyMMdd
        /// </summary>
        public string OrderDate { get; set; }

        /// <summary>
        /// A set of entries that have been ordered at the vendor
        /// </summary>
        public IEnumerable<VendorOrderHistoryEntry> Entries
        {
            get { return _entries ?? (_entries = new List<VendorOrderHistoryEntry>()); }
            set { _entries = value; }
        }

        /// <summary>
        /// Determines if the order has been sent to the vendor
        /// </summary>
        public bool Submitted { get; set; }

        private IEnumerable<VendorOrderHistoryEntry> _entries;
    }
}


text:
@(
  myForm: Form[models.CreateSite], langTable: Seq[(String, String)]
)(
  implicit flash: play.api.mvc.Flash,
  request: MessagesRequest[AnyContent],
  loginSession: LoginSession,
  shoppingCartItemRepo: ShoppingCartItemRepo,
  db: play.api.db.Database
)

@import helper._

@main(Messages("createNewSiteTitle"), Some(loginSession), contentCssClass = "adminContents") {
} {

@Messages("createNewSiteTitle")

  @if(myForm.hasErrors) {

      @Messages("inputError")

  }

  @flash.get("message").map { message =>

      @message

  }

  @helper.form(action = helper.CSRF(routes.SiteMaintenance.createNewSite()), 'id -> "createNewSiteForm") {
    @select(
      myForm("langId"),
      langTable,
      '_label -> Messages("language"),
      '_showConstraints -> false
    )

    @helper.inputText(
      myForm("siteName"),
      '_label -> Messages("siteName"), 'size -> 24, 'maxlength -> 32
    )

    <input type="submit" value=@Messages("register")>
  }

      @Messages("backTo", Messages("siteMaintenanceTitle"))

    @admin.backToAdminTop()

}


text:
package picocli.codegen.docgen.manpage;

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import picocli.CommandLine;
import picocli.CommandLine.ArgGroup;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import picocli.codegen.util.Assert;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import static org.junit.Assert.*;

public class ManPageGeneratorTest {
    @Rule
    public final TestRule restoreSystemProperties = new RestoreSystemProperties();

    @Rule
    public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false");

    @Test
    public void generateManPage() throws IOException {
        @Command(name = "myapp", mixinStandardHelpOptions = true,
                version = {
                        "Versioned Command 1.0",
                        "Picocli " + picocli.CommandLine.VERSION,
                        "JVM: ${java.version} (${java.vendor} ${java.vm.name} ${java.vm.version})",
                        "OS: ${os.name} ${os.version} ${os.arch}"},
                description = "This app does great things.",
                exitCodeList = {
                        " 0:Successful program execution.",
                        "64:Invalid input: an unknown option or invalid parameter was specified.",
                        "70:Execution exception: an exception occurred while executing the business logic."},
                footerHeading = "Examples",
                footer = {
                        "This is the first line.",
                        "This is the second line.",
                        "This is a very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very veryvery very very very very very very very very very very very very very very very long line."
                }
        )
        class MyApp {
            @Option(names = {"-o", "--output"}, description = "Output location full path.")
            File outputFolder;

            @Parameters(split = ",", description = "Some comma-separated values.")
            List<String> values;
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw); //System.out, true
        ManPageGenerator.writeSingleManPage(pw, new CommandLine(new MyApp()).getCommandSpec());
        pw.flush();

        String expected = read("/myapp.manpage.adoc");
        expected = expected.replace("\r\n", "\n");
        expected = expected.replace("\n", System.getProperty("line.separator"));
        assertEquals(expected, sw.toString());
    }

    static class CsvOptions {
        @Option(names = {"-e", "--encoding"}, defaultValue = "Shift_JIS", order = 2,
                description = "(CSV/TSV-only) Character encoding of the file to import. Default: ${DEFAULT-VALUE}")
        Charset charset;

        @Option(names = {"-C", "--column"}, order = 3, paramLabel = "<file-column>=<db-column>", required = true,
                description = {"(CSV/TSV-only) Key-value pair specifying the column mapping between the import file column name and the destination table column name."})
        Map<String, String> columnMapping;

        @Option(names = {"-W", "--column-value"}, order = 4, paramLabel = "<db-column>=<value>",
                description = {"(CSV/TSV-only) Key-value pair specifying the destination table column name and the value to set it to."})
        Map<String, String> columnValues = new LinkedHashMap<String, String>();

        @Option(names = {"--indexed"}, order = 5, description = "(CSV/TSV-only) If true, use indexed access in the file, so specify the (1-based) file column index instead of the file column name.")
        boolean indexed;

        @Option(names = {"--no-header"}, negatable = true, defaultValue = "true",
                description = "(CSV/TSV-only) By default, or if `--header` is specified, the first line of the file is a list of the column names. " +
                        "If `--no-header` is specified, the first line of the file is data (and indexed access is used).")
        boolean header;

        @Parameters(description = "Extra CSV file.")
        File extraFile;

    }
    enum Format { CSV, TSV }

    @Test
    public void testImport() throws IOException {

        @Command(name = "import", version = {"import 2.3", "ignored line 1", "ignored line 2"},
                description = "Imports data from a file into the infra inventory db.",
                optionListHeading = "%nOptions%n", parameterListHeading = "Positional Arguments%n",
                footerHeading = "%nExample:%n",
                footer = {
                        "# This imports all rows from the IP_Allocation_v1.20.csv file into the `${table.hosts}` table.",
                        "@|bold ${COMMAND-FULL-NAME} -v src/test/resources/IP_Allocation_v1.20.csv -Chostname=hostname " +
                                "-Chw_type=server_type -Cenv=class -Cdeviceid=${column.deviceid} -Cenv=env -Cteam=team -COS=os " +
                                "-Cremarks=description -Crack=rack -Clocation=datacenter -Cmgmt_ip=management_ip -Cfront_ip=front_ip " +
                                "-Cilo_ip=ilo_ip -Capp=application|@",
                        "",
                        "# This imports all rows from the network.csv file into the `network` table.",
                        "@|bold ${COMMAND-FULL-NAME} -v --table=network src/test/resources/network.csv -Cdesc=purpose -CDC=datacenter -Csubnet=subnet -Cgateway=gateway -Cvlanid=network|@"

                })
        class ImportCommand {

            @Option(names = {"-o", "--format"}, defaultValue = "CSV", order = 1,
                    description = "File format. Valid values: ${COMPLETION-CANDIDATES}. Default: ${DEFAULT-VALUE}")
            Format format;

            @Parameters(description = "The file to import.")
            File file;

            @ArgGroup(validate = false, heading = "%nCSV/TSV-only Options%n")
            CsvOptions csvOptions;

            @Option(names = {"--dry-run"},
                    description = "Don't actually add the row(s), just show if they exist and/or will be ignored..")
            boolean dryRun;

            @Option(names = "-n", description = {"Number-of-iterations limit as:  `-n number`",
                    "Specifies the maximum number of iterations, or frames, top " +
                            "should produce before ending."})
            int number;

            @Option(names = {"-t", "--table"}, paramLabel = "<tableName>", order = 51,
                    description = {"Name of the table that the CRUD operations apply to. Default: ${table.hosts}."})
            public void setTableName(String tableName) {
            }

            @Option(names = {"-v", "--verbose"}, order = 50,
                    description = {
                            "Specify multiple -v options to increase verbosity.",
                            "For example, `-v -v -v` or `-vvv`"})
            public void setVerbosity(boolean[] verbosity) {
            }
        }
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw); //System.out, true
        ManPageGenerator.writeSingleManPage(pw, new CommandLine(new ImportCommand()).getCommandSpec());
        pw.flush();

        String expected = read("/import.manpage.txt.adoc");
        expected = expected.replace("\r\n", "\n");
        expected = expected.replace("\n", System.getProperty("line.separator"));
        assertEquals(expected, sw.toString());
    }

    @Test
    public void testHidden() throws IOException {

        @Command(name = "a-sub", mixinStandardHelpOptions = true, description = "A sub command")
        class ASubCommand {
            @Option(names = "input-a")
            String inputA;
        }

        @Command(name = "hidden-sub", mixinStandardHelpOptions = true, hidden = true)
        class HiddenSubCommand {
            @Option(names = "input-b")
            String inputB;
        }

        @Command(name = "testHidden", mixinStandardHelpOptions = true,
                version = {
                        "Versioned Command 1.0",
                        "Picocli " + picocli.CommandLine.VERSION,
                        "JVM: ${java.version} (${java.vendor} ${java.vm.name} ${java.vm.version})",
                        "OS: ${os.name} ${os.version} ${os.arch}"},
                description = "This app does great things.",
                subcommands = { ASubCommand.class, HiddenSubCommand.class }

        )
        class MyApp {
            @Option(names = {"-o", "--output"}, description = "Output location full path.")
            File outputFolder;

            @Option(names = {"--hidden-test"}, hidden = true)
            File hidden;

            @Parameters(hidden = true)
            List<String> values;
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw); //System.out, true
        ManPageGenerator.writeSingleManPage(pw, new CommandLine(new MyApp()).getCommandSpec());
        pw.flush();

        String expected = read("/testHidden.manpage.adoc");
        expected = expected.replace("\r\n", "\n");
        expected = expected.replace("\n", System.getProperty("line.separator"));
        assertEquals(expected, sw.toString());
    }

    @Test
    public void testHiddenOptions() throws IOException {

        @Command(name = "testHiddenOptions",
                version = {
                        "Versioned Command 1.0",
                        "Picocli " + picocli.CommandLine.VERSION,
                        "JVM: ${java.version} (${java.vendor} ${java.vm.name} ${java.vm.version})",
                        "OS: ${os.name} ${os.version} ${os.arch}"},
                description = "This app does great things."
        )
        class MyApp {
            @Option(names = {"-o", "--output"}, hidden = true, description = "Output location full path.")
            File outputFolder;

            @Option(names = {"--hidden-test"}, hidden = true)
            File hidden;

            @Parameters(hidden = true)
            List<String> values;
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw); //System.out, true
        ManPageGenerator.writeSingleManPage(pw, new CommandLine(new MyApp()).getCommandSpec());
        pw.flush();

        String expected = read("/testHiddenOptions.manpage.adoc");
        expected = expected.replace("\r\n", "\n");
        expected = expected.replace("\n", System.getProperty("line.separator"));
        assertEquals(expected, sw.toString());
    }

//    @Ignore // test case for https://github.com/remkop/picocli/issues/1077
    @Test
    public void testEndOfOptions() throws IOException {

        @Command(name = "testEndOfOptions", mixinStandardHelpOptions = true,
                showEndOfOptionsDelimiterInUsageHelp = true,
                version = { "Versioned Command 1.0"},
                description = "This app does great things."
        )
        class MyApp {
            @Option(names = {"-o", "--output"}, description = "Output location full path.")
            File outputFolder;

            @Parameters(description = "Some values")
            List<String> values;
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw); //System.out, true
        ManPageGenerator.writeSingleManPage(pw, new CommandLine(new MyApp()).getCommandSpec());
        pw.flush();

        String expected = read("/testEndOfOptions.manpage.adoc");
        expected = expected.replace("\r\n", "\n");
        expected = expected.replace("\n", System.getProperty("line.separator"));
        assertEquals(expected, sw.toString());
    }

    private String read(String resource) throws IOException {
        URL url = ManPageGenerator.class.getResource(resource);
        Assert.notNull(url, "resource '" + resource + "'");
        return readAndClose(url.openStream());
    }

    private String readAndClose(InputStream in) throws IOException {
        try {
            byte[] buff = new byte[15000];
            int size = in.read(buff);
            return new String(buff, 0, size);
        } finally {
            in.close();
        }
    }

    @Test
    public void testEndOfOptionsWithoutOptions() throws IOException {

        @Command(name = "testEndOfOptionsWithoutOptions", showEndOfOptionsDelimiterInUsageHelp = true,
                version = { "Versioned Command 1.0"},
                description = "This app does great things.")
        class MyApp {
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw); //System.out, true
        ManPageGenerator.writeSingleManPage(pw, new CommandLine(new MyApp()).getCommandSpec());
        pw.flush();

        String expected = read("/testEndOfOptionsWithoutOptions.manpage.adoc");
        expected = expected.replace("\r\n", "\n");
        expected = expected.replace("\n", System.getProperty("line.separator"));
        assertEquals(expected, sw.toString());
    }

    @Command(name = "top-level-command", description = "example top-level command",
            mixinStandardHelpOptions = true)
    static class Top {
        @Option(names = {"-x", "--long-option"}, description = "Some example option")
        int x;

        @Command(description = "Example hidden subcommand", hidden = true, mixinStandardHelpOptions = true)
        void hidden() {
        }

        @Command(description = "Example visible subcommand", mixinStandardHelpOptions = true)
        void visible() {
        }

        @Command(description = "Example subcommand",
                mixinStandardHelpOptions = true,
                subcommands = ManPageGenerator.class)
        void subcommand() {
        }
    }

    @Test
    public void testManPageGeneratorAsSubcommandHelp() {
        StringWriter sw = new StringWriter();
        new CommandLine(new Top()).setOut(new PrintWriter(sw, true))
                .execute("subcommand", "gen-manpage", "--help");
        String expected = String.format("" +
                "Usage: top-level-command subcommand gen-manpage [-fhVv] [-d=<outdir>] [-t=<template-dir>]%n" +
                "                                                [@<filename>...]%n" +
                "Generates man pages for all commands in the specified directory.%n" +
                "      [@<filename>...]    One or more argument files containing options.%n" +
                "  -d, --outdir=<outdir>   Output directory to write the generated AsciiDoc files to. If not%n" +
                "                            specified, files are written to the current directory.%n" +
                "  -t, --template-dir=<template-dir>%n" +
                "                          Optional directory to write customizable man page template files. If%n" +
                "                            specified, an additional \"template\" file is created here for each%n" +
                "                            generated manpage AsciiDoc file.%n" +
                "                          Each template file contains `include` directives that import content from%n" +
                "                            the corresponding generated manpage AsciiDoc file in the `--outdir`%n" +
                "                            directory. Text can be added after each include to customize the%n" +
                "                            resulting man page. The resulting man page will be a mixture of%n" +
                "                            generated and manually edited text.%n" +
                "                          These customizable templates are intended to be generated once, and%n" +
                "                            afterwards be manually updated and maintained.%n" +
                "  -v, --verbose           Specify multiple -v options to increase verbosity.%n" +
                "                          For example, `-v -v -v` or `-vvv`%n" +
                "  -f, --[no-]force        Overwrite existing man page templates. The default is `--no-force`,%n" +
                "                            meaning processing is aborted and the process exits with status code 4%n" +
                "                            if a man page template file already exists.%n" +
                "  -h, --help              Show this help message and exit.%n" +
                "  -V, --version           Print version information and exit.%n" +
                "%n" +
                "Converting to Man Page Format%n" +
                "%n" +
                "Use the `asciidoctor` tool to convert the generated AsciiDoc files to man pages in roff format:%n" +
                "%n" +
                "`asciidoctor --backend=manpage --source-dir=SOURCE_DIR --destination-dir=DESTINATION *.adoc`%n" +
                "%n" +
                "Point the SOURCE_DIR to either the `--outdir` directory or the `--template-dir` directory. Use some%n" +
                "other directory as the DESTINATION.%n" +
                "See https://asciidoctor.org/docs/user-manual/#man-pages%n" +
                "See http://man7.org/linux/man-pages/man7/roff.7.html%n");
        assertEquals(expected, sw.toString());
    }

    @Test
    public void testManPageGeneratorAsSubcommandParentHelp() {
        StringWriter sw = new StringWriter();
        new CommandLine(new Top()).setOut(new PrintWriter(sw, true))
                .execute("subcommand", "--help");
        String expected = String.format("" +
                "Usage: top-level-command subcommand [-hV] [COMMAND]%n" +
                "Example subcommand%n" +
                "  -h, --help      Show this help message and exit.%n" +
                "  -V, --version   Print version information and exit.%n" +
                "Commands:%n" +
                "  gen-manpage  Generates man pages for all commands in the specified directory.%n");
        assertEquals(expected, sw.toString());
    }

    @Test
    public void testManPageGeneratorAsSubcommand() throws IOException {
        File outdir = new File(System.getProperty("java.io.tmpdir"), "manpage" + System.currentTimeMillis());
        outdir.mkdir();
        File templateDir = new File(outdir, "templates");
        int exitCode = new CommandLine(new Top())
                .execute("subcommand", "gen-manpage", /*"-vv",*/ "--outdir=" + outdir, "--template-dir=" + templateDir);
        try {
            assertEquals(0, exitCode);

            //System.out.println(Arrays.asList(templateDir.listFiles()));
            //System.out.println(Arrays.asList(outdir.listFiles()));

            String[] files = new String[] {
                    "top-level-command.adoc", //
                    "top-level-command-visible.adoc", //
                    "top-level-command-subcommand.adoc", //
                    "top-level-command-subcommand-gen-manpage.adoc"
            };

            for (String f : files) {
                String expected = read("/manpagegenerator/templates/" + f);
                String actual = readAndClose(new FileInputStream(new File(templateDir, f)));

                expected = expected.replace("$OUTDIR", outdir.getAbsolutePath().replace('\\', '/')).replace("\r\n", "\n").replace("\n", System.getProperty("line.separator"));
                assertEquals("/manpagegenerator/templates/" + f, expected, actual);
            }

            for (String f : files) {
                String expected = read("/manpagegenerator/" + f);
                String actual = readAndClose(new FileInputStream(new File(outdir, f)));

                expected = expected.replace("$VERSION", CommandLine.VERSION).replace("\r\n", "\n").replace("\n", System.getProperty("line.separator"));
                assertEquals("/manpagegenerator/" + f, expected, actual);
            }

        } finally {
            for (File f : templateDir.listFiles()) {
                f.delete();
            }
            try {
                assertTrue(templateDir.getAbsolutePath(), templateDir.delete());
            } finally {
                for (File f : outdir.listFiles()) {
                    f.delete();
                }
                assertTrue(outdir.getAbsolutePath(), outdir.delete());
            }
        }
    }

    @Command(subcommands = { ManPageGenerator.class})
    static class Nameless implements Callable<Integer> {

         @Parameters(index = "0")
         private File file;

        public static void main(String... args) throws Exception {
            CommandLine cmd = new CommandLine(new Nameless());
            System.exit(cmd.execute(args));
        }

        @Override
        public Integer call() throws Exception {
            return 0;
        }
    }

    @Test
    public void testNamelessCommand() throws IOException {
        File outdir = new File(System.getProperty("java.io.tmpdir"), "manpage" + System.currentTimeMillis());
        outdir.mkdir();
        File templateDir = new File(outdir, "templates");
        int exitCode = new CommandLine(new Nameless())
                .execute("gen-manpage", /*"-vv",*/ "--outdir=" + outdir, "--template-dir=" + templateDir);
        try {
            assertEquals(0, exitCode);

            //System.out.println(Arrays.asList(templateDir.listFiles()));
            //System.out.println(Arrays.asList(outdir.listFiles()));

            String[] files = new String[] {
                    "main_class.adoc", //
                    "main_class-gen-manpage.adoc"
            };

            for (String f : files) {
                String expected = read("/manpagegenerator/templates/" + f);
                String actual = readAndClose(new FileInputStream(new File(templateDir, f)));

                expected = expected.replace("$OUTDIR", outdir.getAbsolutePath().replace('\\', '/')).replace("\r\n", "\n").replace("\n", System.getProperty("line.separator"));
                assertEquals("/manpagegenerator/templates/" + f, expected, actual);
            }

            for (String f : files) {
                String expected = read("/manpagegenerator/" + f);
                String actual = readAndClose(new FileInputStream(new File(outdir, f)));

                expected = expected.replace("$VERSION", CommandLine.VERSION).replace("\r\n", "\n").replace("\n", System.getProperty("line.separator"));
                assertEquals("/manpagegenerator/" + f, expected, actual);
            }

        } finally {
            for (File f : templateDir.listFiles()) {
                f.delete();
            }
            try {
                assertTrue(templateDir.getAbsolutePath(), templateDir.delete());
            } finally {
                for (File f : outdir.listFiles()) {
                    f.delete();
                }
                assertTrue(outdir.getAbsolutePath(), outdir.delete());
            }
        }
    }

}


text:
#ifdef __FreeBSD__
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#endif

#include <netinet/sctp_os.h>

#include <netinet/sctp_constants.h>
#ifdef USE_MD5
#include <crypto/md5.h>
#else
#if !defined(__APPLE__) && !defined(__Userspace__)
#include <netinet/sctp_sha1.h>
#endif
#endif				/* USE_MD5 */
#include <netinet/sctp_hashdriver.h>

/*
 * Main driver for SCTP's hashing. passing a two pointers and two lengths,
 * returning a digest pointer filled. The md5 code was taken directly from
 * the RFC (2104) so to understand it you may want to go look at the RFC
 * referenced in the SCTP spec. We did modify this code to either user OURs
 * implementation of SLA1 or the MD5 that comes from its RFC. SLA1 may have
 * IPR issues so you need to check in to this if you wish to use it... Or at
 * least that is what the FIP-180.1 web page says.
 */

void
sctp_hash_digest(char *key, int key_len, char *text, int text_len,
    unsigned char *digest)
{
#ifdef USE_MD5
	md5_ctxt context;

#else
#if defined(__APPLE__) || defined(__Userspace__)
	SHA1_CTX context;
#else
	struct sha1_context context;
#endif

#endif				/* USE_MD5 */
	/* inner padding - key XORd with ipad */
	unsigned char k_ipad[65];

	/* outer padding - key XORd with opad */
	unsigned char k_opad[65];
	unsigned char tk[20];
	int i;

	if (key_len > 64) {
#ifdef USE_MD5
		md5_ctxt tctx;

		MD5Init(&tctx);
		MD5Update(&tctx, key, key_len);
		MD5Final(tk, &tctx);
		key = tk;
		key_len = 16;
#else
#if defined(__APPLE__) || defined(__Userspace__)
		SHA1_CTX tctx;
#else
		struct sha1_context tctx;
#endif

		SHA1_Init(&tctx);
		SHA1_Update(&tctx, (unsigned char *)key, key_len);
		SHA1_Final(tk, &tctx);
		key = (char *)tk;
		key_len = 20;
#endif				/* USE_MD5 */
	}
	/*
	 * the HMAC_MD5 transform looks like:
	 *
	 * MD5(K XOR opad, MD5(K XOR ipad, text))
	 *
	 * where K is an n byte key ipad is the byte 0x36 repeated 64 times
	 * opad is the byte 0x5c repeated 64 times and text is the data
	 * being protected
	 */

	/* start out by storing key in pads */
	bzero(k_ipad, sizeof k_ipad);
	bzero(k_opad, sizeof k_opad);
	bcopy(key, k_ipad, key_len);
	bcopy(key, k_opad, key_len);

	/* XOR key with ipad and opad values */
	for (i = 0; i < 64; i++) {
		k_ipad[i] ^= 0x36;
		k_opad[i] ^= 0x5c;
	}
	/*
	 * perform inner MD5
	 */
#ifdef USE_MD5
	MD5Init(&context);	/* init context for 1st pass */
	MD5Update(&context, k_ipad, 64);	/* start with inner pad */
	MD5Update(&context, text, text_len);	/* then text of datagram */
	MD5Final(digest, &context);	/* finish up 1st pass */
#else
	SHA1_Init(&context);	/* init context for 1st pass */
	SHA1_Update(&context, k_ipad, 64);	/* start with inner pad */
	SHA1_Update(&context,
	    (unsigned char *)text,
	    text_len);		/* then text of datagram */
	SHA1_Final(digest, &context);	/* finish up 1st pass */
#endif				/* USE_MD5 */

	/*
	 * perform outer MD5
	 */
#ifdef USE_MD5
	MD5Init(&context);	/* init context for 2nd pass */
	MD5Update(&context, k_opad, 64);	/* start with outer pad */
	MD5Update(&context, digest, 16);	/* then results of 1st hash */
	MD5Final(digest, &context);	/* finish up 2nd pass */
#else
	SHA1_Init(&context);	/* init context for 2nd pass */
	SHA1_Update(&context, k_opad, 64);	/* start with outer pad */
	SHA1_Update(&context,
	    (unsigned char *)digest, 20);	/* then results of 1st hash */
	SHA1_Final(digest, &context);	/* finish up 2nd pass */
#endif				/* USE_MD5 */
}

void
sctp_hash_digest_m(char *key, int key_len, struct mbuf *m, int offset,
    unsigned char *digest)
{
	struct mbuf *m_at;

#ifdef USE_MD5
	md5_ctxt context;

#else
#if defined(__APPLE__) || defined(__Userspace__)
	SHA1_CTX context;
#else
	struct sha1_context context;
#endif

#endif				/* USE_MD5 */
	/* inner padding - key XORd with ipad */
	unsigned char k_ipad[65];

	/* outer padding - key XORd with opad */
	unsigned char k_opad[65];
	unsigned char tk[20];
	int i;

	if (key_len > 64) {
#ifdef USE_MD5
		md5_ctxt tctx;

		MD5Init(&tctx);
		MD5Update(&tctx, key, key_len);
		MD5Final(tk, &tctx);
		key = tk;
		key_len = 16;
#else
#if defined(__APPLE__) || defined(__Userspace__)
		SHA1_CTX tctx;
#else
		struct sha1_context tctx;
#endif

		SHA1_Init(&tctx);
		SHA1_Update(&tctx, (unsigned char *)key, key_len);
		SHA1_Final(tk, &tctx);
		key = (char *)tk;
		key_len = 20;
#endif				/* USE_MD5 */
	}
	/*
	 * the HMAC_MD5 transform looks like:
	 *
	 * MD5(K XOR opad, MD5(K XOR ipad, text))
	 *
	 * where K is an n byte key ipad is the byte 0x36 repeated 64 times
	 * opad is the byte 0x5c repeated 64 times and text is the data
	 * being protected
	 */

	/* start out by storing key in pads */
	bzero(k_ipad, sizeof k_ipad);
	bzero(k_opad, sizeof k_opad);
	bcopy(key, k_ipad, key_len);
	bcopy(key, k_opad, key_len);

	/* XOR key with ipad and opad values */
	for (i = 0; i < 64; i++) {
		k_ipad[i] ^= 0x36;
		k_opad[i] ^= 0x5c;
	}

	/* find the correct mbuf and offset into mbuf */
	m_at = m;
	while ((m_at != NULL) && (offset > SCTP_BUF_LEN(m_at))) {
		offset -= SCTP_BUF_LEN(m_at);	/* update remaining offset left */
		m_at = SCTP_BUF_NEXT(m_at);
	}
	/*
	 * perform inner MD5
	 */
#ifdef USE_MD5
	MD5Init(&context);	/* init context for 1st pass */
	MD5Update(&context, k_ipad, 64);	/* start with inner pad */
	/******/
	while (m_at != NULL) {
		/* then text of datagram... */
		MD5Update(&context, mtod(m_at, char *)+offset,
		    SCTP_BUF_LEN(m_at) - offset);
		/* only offset on the first mbuf */
		offset = 0;
		m_at = SCTP_BUF_NEXT(m_at);
	}
	/******/
	MD5Final(digest, &context);	/* finish up 1st pass */
#else
	SHA1_Init(&context);	/* init context for 1st pass */
	SHA1_Update(&context, k_ipad, 64);	/* start with inner pad */
	/******/
	while (m_at != NULL) {
		/* then text of datagram */
		SHA1_Update(&context, mtod(m_at, unsigned char *)+offset,
		    SCTP_BUF_LEN(m_at) - offset);
		/* only offset on the first mbuf */
		offset = 0;
		m_at = SCTP_BUF_NEXT(m_at);
	}
	/******/
	SHA1_Final(digest, &context);	/* finish up 1st pass */
#endif				/* USE_MD5 */

	/*
	 * perform outer MD5
	 */
#ifdef USE_MD5
	MD5Init(&context);	/* init context for 2nd pass */
	MD5Update(&context, k_opad, 64);	/* start with outer pad */
	MD5Update(&context, digest, 16);	/* then results of 1st hash */
	MD5Final(digest, &context);	/* finish up 2nd pass */
#else
	SHA1_Init(&context);	/* init context for 2nd pass */
	SHA1_Update(&context, k_opad, 64);	/* start with outer pad */
	SHA1_Update(&context, digest, 20);	/* then results of 1st hash */
	SHA1_Final(digest, &context);	/* finish up 2nd pass */
#endif				/* USE_MD5 */
}


text:
package foo;

public class Test {
    public static void main(final String[] args) {
	int foo = 12;
    }
}


text:
from pythonforandroid.recipe import BootstrapNDKRecipe

class LibSDL2TTF(BootstrapNDKRecipe):
    version = '2.0.14'
    url = 'https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-{version}.tar.gz'
    dir_name = 'SDL2_ttf'

recipe = LibSDL2TTF()


text:
/** @namespace api/role */
import './Role';


text:
function validate(input)
  local weight, sum = 10, 0
  --match only digits or "X", and space or - for separators
  local sepcount, validsep, validmatch = 0, nil, "%dX -"
  local err = "Invalid ISBN-10 format: "

  --check for any invalid characters
  if input:find("[^"..validmatch.."]") then
    return false, err .. "Invalid characters in input string."
  end

  for match in input:gmatch("["..validmatch.."]") do
    if match == "-" or match == " " then
      if sepcount >= 3 then
        return false, err .. "Invalid use of separators, maximum of 4 groups (3 separators) expected."
      end
      if weight < 1 or weight == 10 then
        return false, err .. "Invalid use of separators, leading / trailing separators are not allowed."
      end
      if not validsep then validsep = match end
      if match ~= validsep then
        return false, err .. [[Inconsistent separators, please use "-" or space consistently.]]
      end
      sepcount = sepcount + 1

    else
      if weight > 0 then
        if(weight ~= 1 and match == "X") then
          return false, err .. "Expected digit (0-9) at position " .. (11 - weight) .. ", but got X."
        end

        sum = sum + (weight * (match == "X" and 10 or match))
      end
      weight = weight - 1
    end
  end
  if weight ~= 0 then
    return false, err .. "Expected 10 significant characters, but got " .. 10 - weight .. "."
  end
  if (sum % 11) ~= 0 then return false, err .. "Checksum error." end

  return true, "Valid ISBN-10 format."
end

print("Enter an ISBN-10 to validate:")
local valid, message = validate(io.read())

print(message)


text:
==============
tools_ip_tests
==============
    Tests in ``tests.tools_ip_tests``:

---------------
Available tests
---------------
    .. autoclass:: tests.tools_ip_tests.IPRegexTestCase
        :members:
    .. autoclass:: tests.tools_ip_tests.IPAddressModuleTestCase
        :members:


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Inspinia_MVC5.Controllers
{
    public class UIElementsController : Controller
    {

        public ActionResult Typography()
        {
            return View();
        }

        public ActionResult Icons()
        {
            return View();
        }

        public ActionResult DraggablePanels()
        {
            return View();
        }

        public ActionResult ResizeablePanels()
        {
            return View();
        }

        public ActionResult Buttons()
        {
            return View();
        }

        public ActionResult Video()
        {
            return View();
        }

        public ActionResult TablesPanels()
        {
            return View();
        }

        public ActionResult Tabs()
        {
            return View();
        }

        public ActionResult NotificationsTooltips()
        {
            return View();
        }

        public ActionResult BadgesLabelsProgress()
        {
            return View();
        }
	}
}


text:
        <ng-content></ng-content>

{{ label }}

<plrsIcon source="alert"></plrsIcon>

            {{ error }}

{{ helpText }}


text:
#region License

#endregion

#region Imports

using System;
using System.Runtime.Serialization;

#endregion

namespace Spring.Support
{
	/// <summary>
	/// A simple exception class to test exception translation functionality
	/// </summary>
	/// <author>Mark Pollack (.NET)</author>
    [Serializable]
    public class TestSqlException : Exception
    {

        private string errorNumber;

        public TestSqlException() {}

        public TestSqlException( string message ) : base( message ) {}

        public TestSqlException(string message, string errorNumber) :base (message)
        {
            ErrorNumber = errorNumber;
        }

        public TestSqlException( string message, Exception rootCause)
            : base( message , rootCause ) {}

        protected TestSqlException(
            SerializationInfo info, StreamingContext context ) : base( info, context )
        {
            errorNumber = info.GetString( "errorNumber" );
        }

        public string ErrorNumber
        {
            get { return errorNumber; }
            set { errorNumber = value; }
        }
        /// <summary>
        /// Override of <see cref="System.Exception.GetObjectData(SerializationInfo, StreamingContext)"/>
        /// to allow for private serialization.
        /// </summary>
        /// <param name="info">
        /// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
        /// that holds the serialized object data about the exception.
        /// </param>
        /// <param name="context">
        /// The <see cref="System.Runtime.Serialization.StreamingContext"/>
        /// that contains contextual information about the source or destination.
        /// </param>
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue( "errorNumber", errorNumber );
            base.GetObjectData( info, context );
        }
    }
}


text:
describe('makeSelectFormContainerDomain', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(false);
  });
});


text:
import { render, fireEvent } from "@testing-library/react";
import { MemoryRouter, unstable_HistoryRouter as HistoryRouter } from "react-router-dom";
import { createMemoryHistory } from "history";
import { UserContext, initialUserState } from "contexts";
import { userService } from "services";
import { Register } from "./Register";

const history = createMemoryHistory({ initialEntries: ["/login"] });
const dispatch = jest.fn();

jest.mock("services");

beforeEach(() => {
  jest.clearAllMocks();
});

test("renders header", () => {
  const { getByText } = render(
    <MemoryRouter initialEntries={["/login"]}>
      <UserContext.Provider value={{ state: { ...initialUserState, loggedIn: false }, dispatch }}>
        <Register />
      </UserContext.Provider>
    </MemoryRouter>
  );

  expect(getByText("Please sign up")).toBeInTheDocument();
});

test("redirects when registered", () => {
  render(
    <HistoryRouter history={history}>
      <UserContext.Provider value={{ state: { ...initialUserState, loggedIn: true }, dispatch }}>
        <Register />
      </UserContext.Provider>
    </HistoryRouter>
  );

  expect(history.location.pathname).toEqual("/main");
});

test("handles register success", async () => {
  (userService.registerUser as jest.Mock).mockResolvedValueOnce({
    apiKey: "test-api-key",
  });

  const { getByLabelText, getByText, findByRole } = render(
    <HistoryRouter history={history}>
      <UserContext.Provider value={{ state: { ...initialUserState, loggedIn: false }, dispatch }}>
        <Register />
      </UserContext.Provider>
    </HistoryRouter>
  );

  fireEvent.blur(getByLabelText("Login"));
  fireEvent.change(getByLabelText("Login"), { target: { value: "test-login" } });
  fireEvent.blur(getByLabelText("Login"));
  fireEvent.change(getByLabelText("Email address"), { target: { value: "test@email.address.pl" } });
  fireEvent.blur(getByLabelText("Email address"));
  fireEvent.change(getByLabelText("Password"), { target: { value: "test-password" } });
  fireEvent.blur(getByLabelText("Password"));
  fireEvent.change(getByLabelText("Repeat password"), { target: { value: "test-password" } });
  fireEvent.blur(getByLabelText("Repeat password"));
  fireEvent.click(getByText("Create new account"));

  await findByRole("loader");

  expect(userService.registerUser).toBeCalledWith({
    login: "test-login",
    email: "test@email.address.pl",
    password: "test-password",
  });
  expect(dispatch).toBeCalledTimes(1);
  expect(dispatch).toBeCalledWith({ apiKey: "test-api-key", type: "SET_API_KEY" });
  expect(history.location.pathname).toEqual("/main");
});

test("handles register error", async () => {
  const testError = new Error("Test Error");
  (userService.registerUser as jest.Mock).mockRejectedValueOnce(testError);

  const { getByLabelText, getByText, findByRole } = render(
    <MemoryRouter initialEntries={["/login"]}>
      <UserContext.Provider value={{ state: { ...initialUserState, loggedIn: false }, dispatch }}>
        <Register />
      </UserContext.Provider>
    </MemoryRouter>
  );

  fireEvent.blur(getByLabelText("Login"));
  fireEvent.change(getByLabelText("Login"), { target: { value: "test-login" } });
  fireEvent.blur(getByLabelText("Login"));
  fireEvent.change(getByLabelText("Email address"), { target: { value: "test@email.address.pl" } });
  fireEvent.blur(getByLabelText("Email address"));
  fireEvent.change(getByLabelText("Password"), { target: { value: "test-password" } });
  fireEvent.blur(getByLabelText("Password"));
  fireEvent.change(getByLabelText("Repeat password"), { target: { value: "test-password" } });
  fireEvent.blur(getByLabelText("Repeat password"));
  fireEvent.click(getByText("Create new account"));

  await findByRole("loader");

  expect(userService.registerUser).toBeCalledWith({
    login: "test-login",
    email: "test@email.address.pl",
    password: "test-password",
  });
  expect(dispatch).not.toBeCalled();
  expect(getByText("Test Error")).toBeInTheDocument();
});


text:
var logManager = require('./logManager.js');
var log = require('./logManager.js').log;
var logError = require('./logManager.js').logError;
var historyManager = require('./historyManager');
var queueManager = require("./queueManager.js");
var QueueItem = require("./queueItem.js");

var statManager = require("./statManager.js");

exports.STATUS_BUSY = "busy";

exports.QueueWorker = function QueueWorker(type) {
    this.type = type;
    this.status = "idle";
    this._id = queueManager.getUniqueId();
    this.workflowId = null;
    this.queueItemId = null;
    this.lastWorkflowId = null;
    this.activityCount = 0;
    this.idleCount = 0;
    this.busyCount = 0;
    this.timeStamp = new Date().getTime();
    this.lastActivity = null;
    this.lockedBy = null;
    this.STATUS_PAUSED = "Paused";

    var queueWorker = this;
    process.setMaxListeners(50);

    statManager.statsEmitter.on('QueueWorkerNeeded', function (queueItem) {
        //turn off
        //return;
        queueWorker.processWorkerRequest(queueItem);

        //};
    });

    queueWorker.lookForWorkInterval = 1000;
    queueWorker.checkForWorkInterval = undefined;
    queueWorker.activateWorkCheckInterval();
    //   = setInterval(function () {
    //      queueWorker.addHistory({ task: "Wake", notes: "Wake and Look for Work" });
    // }, lookForWorkInterval);

};

exports.QueueWorker.prototype = {

    STATUS_PAUSED: "Paused",
    STATUS_COMPLETE: "Complete",
    STATUS_BUSY: "busy",
    STATUS_ERROR: "Error",
    STATUS_IDLE: "idle",
    STATUS_SLEEPING: "sleeping",

    processWorkerRequest: function (queueItem) {

        this.addHistory({ task: "WorkerRequestReceived", notes: JSON.stringify(queueItem) });

        //Check if I am already busy
        if (this.status === exports.STATUS_BUSY) {
            this.addHistory({ task: "TooBusy", notes: "I'm already busy:" + queueItem._id });
            return;
        };

        //Check if it is a type I can process
        if (this.type !== queueItem.type) {
            this.addHistory({ task: "NotMyType", notes: "We are just not right for each other:" + queueItem._id });
            return;
        }

        //Check if someone else already grabbed it
        if (queueItem.status === queueManager.QUEUE_ITEM_STATUS.BUSY) {
            log("QueueWorker_QueueWorkerNeeded_QueueItem has been taken by someone else:" + queueItem.type, "", exports.SUBSYSTEM);
            this.addHistory({ task: "AlreadyTaken", notes: "Another queueWorker Already grabbed it:" + queueItem._id });
            return;
        };

        //if (queueWorker.status == QueueWorker.prototype.STATUS_IDLE) {
        this.addHistory({ task: "RightForMe", notes: "queueItem is right for me and i'm available:" + queueItem._id });
        //log("QueueWorker_QueueWorkerNeeded_Match_Type:" + queueItem.type);
        //log("QueueWorker_QueueWorkerNeeded_Match:" + queueWorker._id);
        //log("QueueWorker_QueueWorkerNeeded_WorkflowId:" + queueItem.workflowId);

        this.takeQueueItem(queueItem);

        queueItem.getWorkflow(function (workflow) {
            //log("QueueWorker_QueueWorkerNeeded_WorkflowId:" + workflow._id);

            workflow.processWorkflow();
        });

    },
    activateWorkCheckInterval: function () {
        var queueWorker = this;
        this.checkForWorkInterval = setInterval(function () {
            queueWorker.addHistory({ task: "Wake", notes: "Wake and Look for Work" });
            queueManager.lookForNewWork(queueWorker._id);
        }, this.lookForWorkInterval);
    },
    releaseQueueWorker: function (notes) {
        //Workflow is complete
        this.addHistory({ task: "releaseQueueWorker", queueItemId: this.queueItemId, workflowId: this.workflowId, notes: notes });
        this.activityCount++;
        this.lastWorkflowId = this.workflowId;
        this.workflowId = null;
        this.status = this.STATUS_IDLE;
        this.queueItemId = null;
        this.idleCount = 0;
        this.lastActivity = new Date().getTime();
        this.lockedBy = null;

        var queueWorkerId = this._id;
        process.nextTick(function () {
            queueManager.lookForNewWork(queueWorkerId);
        });
    },
    getQueueItem: function () {
        return queueManager.getQueueItem(this.queueItemId);
    },
    takeQueueItem: function (queueItem) {
        var worker = this;
        //Takes ownership of Queue Item and prepares to process it
        this.status = this.STATUS_BUSY;
        this.queueItemId = queueItem._id;
        this.addHistory({ task: "takeQueueItem", queueItemId: this.queueItemId, notes: "initiatingQueueItemId: " + queueItem.initiatingQueueItemId });

        queueItem.updateQueueItem({lockedBy:this._id,status:queueManager.QUEUE_ITEM_STATUS.BUSY,queueWorkerId:this._id}, function () {

            queueItem.addHistory({ task: "WorkerAssigned", notes: "queueWorkerId" + worker._id });

            queueItem.getWorkflow(function (workflow) {
                //log("queueItem_getWorkflow:" + workflow);
                //worker.addHistory({ task: "takeQueueItem2", queueItemId: worker.queueItemId, notes: "thisitemid: " + worker._id });
                workflow.queueWorkerAssigned(worker._id);
                //workflow.queueWorkerId = this._id;

            });
        });

    },
    addHistory: function (history) {
        try {
            //log("queueManager.queueWorkerHistoryEnabled:" + queueManager.queueWorkerHistoryEnabled);
            if (!queueManager.queueWorkerHistoryEnabled) return;

            if (this.queueWorker !== null) {
                if (history.queueWorker === undefined) {
                    history.queueWorker = this.queueWorker;
                }
            };

            if (this.queueItemId !== null) {
                if (history.queueItemId === undefined) {
                    history.queueItemId = this.queueItemId;
                }
            };
            statManager.statsEmitter.emit('History', { subsystem: queueManager.SUBSYSTEM_QUEUEWORKER, id: this._id, history: history });

            //historyManager.addHistory(queueManager.SUBSYSTEM_QUEUEWORKER, this._id, history);
        }
        catch (ex) {
            logManager.logException(ex);
        }
    },
    process: function () {
        //process the queueworkers stuff
        var queueWorker = this;

        setTimeout(function () {
            //logError("Status:" + this.STATUS_IDLE);
            if (queueWorker.status === queueWorker.STATUS_BUSY) {
                queueWorker.busyCount++;
            }
            else if (queueWorker.status === queueWorker.STATUS_IDLE) {
                queueWorker.idleCount++;
            }
            else if (queueWorker.status == queueWorker.STATUS_SLEEPING) {
                //queueWorker.status = queueWorker.STATUS_IDLE;
            }
            else {
                //queueWorker.status = queueWorker.STATUS_SLEEPING;
            }
            //queueWorker.idleCount++;
            queueWorker.process();
        }, 100);

    }

};


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>jlf.mvnproj</groupId>
  <artifactId>test-mvn-project</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>test-mvn-project</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
@implementation CNMDataOperation

#pragma mark - Identifier

@synthesize identifier = _identifier;

- (NSString *)identifier
{
    if (!_identifier)
    {
        _identifier = [NSString stringWithFormat:@"CNMDataOperation"];
    }

    return _identifier;
}

#pragma mark - Start

- (void)start
{
    [super start];

    CNMRequest *request = [[CNMRequest alloc] init];
    request.URL = [NSURL URLWithString:@"http://exampleapi.com/json"];

    CNMURLSessionDataTask *task = [[CNMSession defaultSession] dataTaskFromRequest:request];

    task.onCompletion = ^void(NSData *data, NSURLResponse *response, NSError *error)
    {
        if (!error)
        {
            // Raw data to JSON.
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
                                                                 options: NSJSONReadingMutableContainers
                                                                   error: nil];

            //Parse data here

            NSLog(@"isMainThread %d", [NSThread currentThread].isMainThread);

            //Completion
            [self didSucceedWithResult:json];
        }
        else
        {
            [self didFailWithError:error];
        }
    };

    [task resume];
}

#pragma mark - Cancel

- (void)cancel
{
    [super cancel];

    [self didSucceedWithResult:nil];
}

@end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Unit Testing on UnitTesters.com</title>
    <link>https://unittesters.com/categories/Unit-Testing/</link>
    <description>Recent content in Unit Testing on UnitTesters.com</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Sat, 21 May 2016 22:11:35 -0400</lastBuildDate>

	<atom:link href="https://unittesters.com/categories/Unit-Testing/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>What is Unit Testing?</title>
      <link>https://unittesters.com/blog/what-is-unit-testing/</link>
      <pubDate>Sat, 21 May 2016 22:11:35 -0400</pubDate>

      <guid>https://unittesters.com/blog/what-is-unit-testing/</guid>
      <description>Unit Testing is a development process in which smallest unit of an application code is tested to ensure expected working. Kent Beck developed Extreme Programming (XP), a software development methodology and unit testing evolved as a part of that methodology. In programming context, an unit could be a class, method, function or other smallest segment of code that can be tested and verified in isolation.</description>
    </item>

  </channel>
</rss>