text:
<link rel="import" href="../polymer/polymer.html">
<script>
  Polymer({

    is: 'oauth-popup',

    properties: {
      url: {
        type: String
      },
      target: {
        type: String,
        value: '_blank'
      },
      width: {
        type: Number,
        value: 500
      },
      height: {
        type: Number,
        value: 500
      },
      left: {
        type: Number,
        computed: '_compute_left(width)'
      },
      top: {
        type: Number,
        computed: '_compute_top(height)'
      },
      options: {
        type: Object,
        computed: '_compute_options(width, height, left, top)'
      },
      options_string: {
        type: String,
        computed: '_compute_options_string(options)'
      },
      response: {
        type: Object,
        notify: true
      },
      error: {
        type: Object,
        notify: true
      }
    },

    ready: function () {
      this.popup = null;
    },

    open: function () {
      this.popup = window.open(this.url, '_blank', this.options_string);

      if (this.popup && this.popup.focus) {
        this.popup.focus();
      }

      this._poll_popup();
    },

    _poll_popup: function () {
      var scope = this;
      var popup = this.popup;

      var polling = setInterval(function() {
        var document_domain = document.domain;
        var response = {};
        var error = {};

        try {
          var popup_domain = popup.document.domain;
          var popup_search = popup.location.search;
          var popup_hash = popup.location.hash;
          var popup_redirect = document_domain === popup_domain && (popup_search || popup_hash);

          if (popup_redirect) {
            var hash_params = popup.location.hash.substring(1).replace(/\/$/, '');
            var query_params = popup.location.search.substring(1).replace(/\/$/, '');
            var query = scope._parse_querystring(query_params);
            var hash = scope._parse_querystring(hash_params);
            var key;

            for (key in query) {
              response[key] = query[key];
            }
            for (key in hash) {
              response[key] = hash[key];
            }

            if (response.error) {
              scope.error = response;
              scope.fire('error', scope.response);
            } else {
              scope.response = response;
              scope.fire('response', scope.response);
            }

            clearInterval(polling);
            popup.close();
          }
        } catch (error) {
          // console.warn(error);
        }

        if (!popup) {
          clearInterval(polling);
          scope.error = { data: 'Provider Popup Blocked' };
          scope.fire('error', scope.error);
        } else if (popup.closed && scope.error) {
          clearInterval(polling);
          scope.error = { data: 'Authorization Failed' };
          scope.fire('error', scope.error);
        }
      }, 100);

    },

    _compute_left: function (width) {
      return window.screenX + ((window.outerWidth - width) / 2);
    },

    _compute_top: function (height) {
      return window.screenY + ((window.outerHeight - height) / 2.5);
    },

    _compute_options: function (width, height, left, top) {
      var options = { width: width, height: height, left: left, top: top };
    },

    _compute_options_string: function (options) {
      var string;
      var pairs = [];
      var pair;
      var key;
      var value;
      for (key in options) {
        value = options[key];
        pair = key + '=' + value;
        pairs.push();
      }
      string = pairs.join(',');
      return string;
    },

    _parse_querystring: function (querystring) {
      var obj = {};
      var pairs = querystring.split('&');
      var key;
      var value;
      pairs.forEach(function (pair) {
        pair = pair.split('=');
        key = decodeURIComponent(pair[0]);
        value = (typeof pair[1] !== 'undefined') ? decodeURIComponent(pair[1]) : true;
        obj[key] = value;
      });
      return obj;
    }

  });
</script>


text:
package io.netty.handler.ssl;

import io.netty.buffer.ByteBufAllocator;

import javax.net.ssl.SSLEngine;

import static io.netty.util.ReferenceCountUtil.safeRelease;

/**
 * Implements a {@link SSLEngine} using
 * OpenSSL BIO abstractions.
 *

 * This class will use a finalizer to ensure native resources are automatically cleaned up. To avoid finalizers
 * and manually release the native memory see {@link ReferenceCountedOpenSslEngine}.
 */
public final class OpenSslEngine extends ReferenceCountedOpenSslEngine {
    OpenSslEngine(OpenSslContext context, ByteBufAllocator alloc, String peerHost, int peerPort) {
        super(context, alloc, peerHost, peerPort, false);
    }

    @Override
    @SuppressWarnings("FinalizeDeclaration")
    protected void finalize() throws Throwable {
        super.finalize();
        OpenSsl.releaseIfNeeded(this);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.camunda.bpm.engine.impl;

import java.util.Map;

import org.camunda.bpm.dmn.engine.DmnDecisionTableResult;
import org.camunda.bpm.engine.DecisionService;
import org.camunda.bpm.engine.dmn.DecisionEvaluationBuilder;
import org.camunda.bpm.engine.dmn.DecisionsEvaluationBuilder;
import org.camunda.bpm.engine.impl.dmn.DecisionEvaluationBuilderImpl;
import org.camunda.bpm.engine.impl.dmn.DecisionTableEvaluationBuilderImpl;

/**
 * @author Philipp Ossler
 */
public class DecisionServiceImpl extends ServiceImpl implements DecisionService {

  public DmnDecisionTableResult evaluateDecisionTableById(String decisionDefinitionId, Map<String, Object> variables) {
    return evaluateDecisionTableById(decisionDefinitionId)
        .variables(variables)
        .evaluate();
  }

  public DmnDecisionTableResult evaluateDecisionTableByKey(String decisionDefinitionKey, Map<String, Object> variables) {
    return evaluateDecisionTableByKey(decisionDefinitionKey)
        .variables(variables)
        .evaluate();
  }

  public DmnDecisionTableResult evaluateDecisionTableByKeyAndVersion(String decisionDefinitionKey, Integer version, Map<String, Object> variables) {
    return evaluateDecisionTableByKey(decisionDefinitionKey)
        .version(version)
        .variables(variables)
        .evaluate();
  }

  public DecisionEvaluationBuilder evaluateDecisionTableByKey(String decisionDefinitionKey) {
    return DecisionTableEvaluationBuilderImpl.evaluateDecisionTableByKey(commandExecutor, decisionDefinitionKey);
  }

  public DecisionEvaluationBuilder evaluateDecisionTableById(String decisionDefinitionId) {
    return DecisionTableEvaluationBuilderImpl.evaluateDecisionTableById(commandExecutor, decisionDefinitionId);
  }

  public DecisionsEvaluationBuilder evaluateDecisionByKey(String decisionDefinitionKey) {
    return DecisionEvaluationBuilderImpl.evaluateDecisionByKey(commandExecutor, decisionDefinitionKey);
  }

  public DecisionsEvaluationBuilder evaluateDecisionById(String decisionDefinitionId) {
    return DecisionEvaluationBuilderImpl.evaluateDecisionById(commandExecutor, decisionDefinitionId);
  }

}


text:
function save_ram() {
	Module.ccall('check_save', 'number', [], []);
}

document.getElementById('save-ram')
  .addEventListener('click', save_ram);


text:
package it.personal.keyring;

import it.personal.keyring.model.SecurityQuestion;
import it.personal.keyring.model.UserProfile;

import java.util.Locale;

import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

public class SetupActivity extends FragmentActivity implements
		ActionBar.TabListener {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;
	PasswordSectionFragment mPasswordPage;
	QuestionsSectionFragment mQuestionsPage;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setup);

		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}
	}

	public ViewPager getViewPager() {
		return mViewPager;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.setup, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.setup_action_cancel:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			// NavUtils.navigateUpFromSameTask(this);
			setResult(Activity.RESULT_CANCELED);
			finish();
			return true;
		case R.id.setup_action_save:
			if (!save()) {
				return false;
			}
			setResult(Activity.RESULT_OK);
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	private boolean save() {
		if(mPasswordPage.validatePasswords()) {
			if(mQuestionsPage.validateAnswers()) {
				boolean create = false;
				UserProfile usr = ((KeyringApp)getApplicationContext()).getCurrentUser();
				if(usr == null) {
					create = true;
					usr = new UserProfile();
				}
				usr.setPassword(mPasswordPage.getPassword());
				usr.setSecurityQuestion1(mQuestionsPage.getQuestion(1));
				usr.setSecurityQuestion2(mQuestionsPage.getQuestion(2));
				usr.setSecurityQuestion3(mQuestionsPage.getQuestion(3));
				usr.setSecurityAnswer1(mQuestionsPage.getAnswer(1));
				usr.setSecurityAnswer2(mQuestionsPage.getAnswer(2));
				usr.setSecurityAnswer3(mQuestionsPage.getAnswer(3));

				KeyringDatabaseOpenHelper db = new KeyringDatabaseOpenHelper(this);
				try {
					db.saveUserProfile(usr, create);
					((KeyringApp)getApplicationContext()).setCurrentUser(usr);
					((KeyringApp)getApplicationContext()).setAuthenticationMode(mPasswordPage.getAuthenticationMode());
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				} finally {
					db.close();
				}
				return true;
			} else {
				mViewPager.setCurrentItem(1);
			}
		} else {
			mViewPager.setCurrentItem(0);
		}
		return false;
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
	}

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

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

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.

			Fragment fragment = null;
			Bundle args = null;
			switch (position) {
			case 0:
				mPasswordPage = new PasswordSectionFragment();
				args = new Bundle();
				args.putInt(PasswordSectionFragment.ARG_AUTH_MODE,
						((KeyringApp)getApplicationContext()).getAuthenticationMode());
				mPasswordPage.setArguments(args);
				fragment = mPasswordPage;
				break;
			case 1:
				mQuestionsPage = new QuestionsSectionFragment();
				args = new Bundle();
				args.putInt(QuestionsSectionFragment.ARG_SECTION_NUMBER,
						position + 1);
				UserProfile profile = ((KeyringApp)getApplicationContext()).getCurrentUser();
				if(profile != null) {
					args.putCharSequence(QuestionsSectionFragment.ARG_QUESTION_1, profile.getQA1());
					args.putCharSequence(QuestionsSectionFragment.ARG_QUESTION_2, profile.getQA2());
					args.putCharSequence(QuestionsSectionFragment.ARG_QUESTION_3, profile.getQA3());
				}
				mQuestionsPage.setArguments(args);
				fragment = mQuestionsPage;
				break;
			}
			return fragment;
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			}
			return null;
		}
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class PasswordSectionFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_AUTH_MODE = "auth_mode";

		private EditText mPasswordView;
		private EditText mConfirmPasswordView;
		private RadioGroup authModeGroupView;
		private String password;
		private String confirmPassword;
		public PasswordSectionFragment() {
		}

		public int getAuthenticationMode() {
			if(authModeGroupView.getCheckedRadioButtonId()==R.id.page_password_auth_mode_pin)
				return KeyringApp.AUTH_MODE_PIN;

			return KeyringApp.AUTH_MODE_PASSWORD;
		}
		public String getPassword() {
			return password;
		}

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

			authModeGroupView = (RadioGroup)rootView.findViewById(R.id.page_password_auth_mode);
			authModeGroupView.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(RadioGroup group, int checkedId) {
					if(checkedId == R.id.page_password_auth_mode_password) {
						mPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
						mConfirmPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
					} else {
						mPasswordView.setText("");
						mPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
						mPasswordView.setTransformationMethod(PasswordTransformationMethod.getInstance());
						mConfirmPasswordView.setText("");
						mConfirmPasswordView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
						mConfirmPasswordView.setTransformationMethod(PasswordTransformationMethod.getInstance());
					}

				}
			});
			rootView.findViewById(R.id.page_password_next_button).setOnClickListener(
					new View.OnClickListener() {
						@Override
						public void onClick(View view) {
							if(validatePasswords()) {
								((SetupActivity) getActivity()).getViewPager()
										.setCurrentItem(1);
							}
						}
					});

			mPasswordView = (EditText)rootView.findViewById(R.id.page_password_password);
			mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener()
			{
				@Override
				public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent)
				{
					if (id == R.id.page_password_password || id == EditorInfo.IME_NULL) {
						return validatePasswords();
					}
					return false;
				}
			});

			mConfirmPasswordView = (EditText)rootView.findViewById(R.id.page_password_confirm_password);
			mConfirmPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener()
			{
				@Override
				public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent)
				{
					if (id == R.id.page_password_confirm_password || id == EditorInfo.IME_NULL) {
						return validatePasswords();
					}
					return false;
				}
			});

			// sets load arguments
			Bundle args = getArguments();
			if(args.containsKey(ARG_AUTH_MODE)) {
				if(args.getInt(ARG_AUTH_MODE) == KeyringApp.AUTH_MODE_PASSWORD) {
					authModeGroupView.check( R.id.page_password_auth_mode_password);
				} else {
					authModeGroupView.check( R.id.page_password_auth_mode_pin);
				}
			}

			return rootView;
		}

		public boolean validatePasswords() {
			mPasswordView.setError(null);
			mConfirmPasswordView.setError(null);

			password = mPasswordView.getText().toString();

			// Check for a valid password.
			if (TextUtils.isEmpty(password)) {
				mPasswordView.setError(getString(R.string.error_field_required));
				mPasswordView.requestFocus();
				return false;
			} else if (password.length() < 4) {
				mPasswordView.setError(getString(R.string.error_invalid_password));
				mPasswordView.requestFocus();
				return false;
			} else {
				confirmPassword = mConfirmPasswordView.getText().toString();
				if(!TextUtils.equals(password,confirmPassword)) {
					mConfirmPasswordView.setError(getString(R.string.passwords_not_match));
					mConfirmPasswordView.requestFocus();
					return false;
				}
			}
			return true;
		}
	}

	public static class QuestionsSectionFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";
		public static final String ARG_QUESTION_1 = "question_1";
		public static final String ARG_QUESTION_2 = "question_2";
		public static final String ARG_QUESTION_3 = "question_3";

		private Spinner mQuestion1;
		private Spinner mQuestion2;
		private Spinner mQuestion3;

		private EditText mAnswer1;
		private EditText mAnswer2;
		private EditText mAnswer3;

		public QuestionsSectionFragment() {
		}

		public int getQuestion(int number) {
			switch(number) {
			case 1:
				return mQuestion1.getSelectedItemPosition();
			case 2:
				return mQuestion2.getSelectedItemPosition();
			case 3:
				return mQuestion3.getSelectedItemPosition();
			}

			return -1;
		}

		public String getAnswer(int number) {
			switch(number) {
			case 1:
				return mAnswer1.getText().toString();
			case 2:
				return mAnswer2.getText().toString();
			case 3:
				return mAnswer3.getText().toString();
			}

			return null;
		}

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

			mQuestion1 = (Spinner) rootView.findViewById(R.id.page_question_question_1);

			mQuestion2 = (Spinner) rootView.findViewById(R.id.page_question_question_2);
			mQuestion3 = (Spinner) rootView.findViewById(R.id.page_question_question_3);

			// Create an ArrayAdapter using the string array and a default
			// spinner layout
			ArrayAdapter<CharSequence> adapter = ArrayAdapter
					.createFromResource(rootView.getContext(),
							R.array.security_questions_array,
							android.R.layout.simple_spinner_item);
			// Specify the layout to use when the list of choices appears
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

			// Apply the adapter to the spinner
			mQuestion1.setAdapter(adapter);
			mQuestion2.setAdapter(adapter);
			mQuestion3.setAdapter(adapter);

			mAnswer1 = (EditText)rootView.findViewById(R.id.page_question_answer_1);
			mAnswer2 = (EditText)rootView.findViewById(R.id.page_question_answer_2);
			mAnswer3 = (EditText)rootView.findViewById(R.id.page_question_answer_3);

			Bundle args = getArguments();
			SecurityQuestion question;
			if(args.containsKey(ARG_QUESTION_1)) {
				question = UserProfile.parseQA(args.getString(ARG_QUESTION_1));
				mQuestion1.setSelection(question.getQuestionIndex());
				mAnswer1.setText(question.getAnswer());
			}
			if(args.containsKey(ARG_QUESTION_2)) {
				question = UserProfile.parseQA(args.getString(ARG_QUESTION_2));
				mQuestion2.setSelection(question.getQuestionIndex());
				mAnswer2.setText(question.getAnswer());
			}
			if(args.containsKey(ARG_QUESTION_3)) {
				question = UserProfile.parseQA(args.getString(ARG_QUESTION_3));
				mQuestion3.setSelection(question.getQuestionIndex());
				mAnswer3.setText(question.getAnswer());
			}
			return rootView;
		}

		public boolean validateAnswers() {
			mAnswer1.setError(null);
			mAnswer2.setError(null);
			mAnswer3.setError(null);

			if(TextUtils.isEmpty(getAnswer(1))) {
				mAnswer1.setError(getString(R.string.error_field_required));
				mAnswer1.requestFocus();
				return false;
			}
			if(TextUtils.isEmpty(getAnswer(2))) {
				mAnswer2.setError(getString(R.string.error_field_required));
				mAnswer2.requestFocus();
				return false;
			}
			if(TextUtils.isEmpty(getAnswer(3))) {
				mAnswer3.setError(getString(R.string.error_field_required));
				mAnswer3.requestFocus();
				return false;
			}

			return true;
		}
	}

}


text:
using System;
using System.ServiceModel;

namespace Myrtille.Services.Contracts
{
    [ServiceContract(CallbackContract = typeof(IRemoteSessionProcessCallback))]
    public interface IRemoteSessionProcess
    {
        /// <summary>
        /// start the host client process
        /// </summary>
        [OperationContract]
        void StartProcess(
            Guid remoteSessionId,
            HostType HostType,
            SecurityProtocol securityProtocol,
            string serverAddress,
            string vmGuid,
            string userDomain,
            string userName,
            string startProgram,
            int clientWidth,
            int clientHeight,
            bool allowRemoteClipboard,
            bool allowPrintDownload,
            bool allowAudioPlayback);

        /// <summary>
        /// stop the host client process
        /// CAUTION! in order to close the host session, killing the client process is a bit harsh...
        /// better ask it to exit normally, from the remote session manager, using a close command
        /// </summary>
        [OperationContract]
        void StopProcess();

        /// <summary>
        /// retrieve the user account the host client process is running on
        /// </summary>
        [OperationContract]
        string GetProcessIdentity();
    }

    public interface IRemoteSessionProcessCallback
    {
        /// <summary>
        /// process exited callback
        /// </summary>
        [OperationContract]
        void ProcessExited(int exitCode);
    }
}


text:
struct BadHash {
  template <class T>
  size_t operator()(T const& t) {
    return std::hash<T>{}(t);
  }
};

struct BadEqual {
  template <class T, class U>
  bool operator()(T const& t, U const& u) {
    return t == u;
  }
};

int main(int, char**) {
  static_assert(!std::__invokable<BadEqual const&, int const&, int const&>::value, "");
  static_assert(std::__invokable<BadEqual&, int const&, int const&>::value, "");

  // expected-warning@unordered_set:* 2 {{the specified comparator type does not provide a viable const call operator}}
  // expected-warning@unordered_map:* 2 {{the specified comparator type does not provide a viable const call operator}}
  // expected-warning@unordered_set:* 2 {{the specified hash functor does not provide a viable const call operator}}
  // expected-warning@unordered_map:* 2 {{the specified hash functor does not provide a viable const call operator}}

  {
    using C = std::unordered_set<int, BadHash, BadEqual>;
    C s;
  }
  {
    using C = std::unordered_multiset<long, BadHash, BadEqual>;
    C s;
  }
  {
    using C = std::unordered_map<int, int, BadHash, BadEqual>;
    C s;
  }
  {
    using C = std::unordered_multimap<long, int, BadHash, BadEqual>;
    C s;
  }

  return 0;
}


text:
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#nav-User">
                Toggle navigation

            </button>
            FridaySheriff

                    {{AuthService.user.name}}

Settings

Admin

Sign out


text:
package org.springframework.cloud.config.server.support;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jgit.util.FileUtils;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.StringUtils;

/**
 * Base class for components that want to access a source control management system.
 *
 * @author Dave Syer
 *
 */
public class AbstractScmAccessor implements ResourceLoaderAware {

	private static final String[] DEFAULT_LOCATIONS = new String[] { "/" };

	protected Log logger = LogFactory.getLog(getClass());
	/**
	 * Base directory for local working copy of repository.
	 */
	private File basedir;
	/**
	 * URI of remote repository.
	 */
	private String uri;
	private ConfigurableEnvironment environment;
	/**
	 * Username for authentication with remote repository.
	 */
	private String username;
	/**
	 * Password for authentication with remote repository.
	 */
	private String password;
	/**
	 * Search paths to use within local working copy. By default searches only the root.
	 */
	private String[] searchPaths = DEFAULT_LOCATIONS;

	private ResourceLoader resourceLoader = new DefaultResourceLoader();

	public AbstractScmAccessor(ConfigurableEnvironment environment) {
		this.environment = environment;
		this.basedir = createBaseDir();
	}

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	protected File createBaseDir() {
		try {
			final File basedir = Files.createTempDirectory("config-repo-").toFile();
			Runtime.getRuntime().addShutdownHook(new Thread() {
				@Override
				public void run() {
					try {
						FileUtils.delete(basedir, FileUtils.RECURSIVE);
					}
					catch (IOException e) {
						AbstractScmAccessor.this.logger.warn(
								"Failed to delete temporary directory on exit: " + e);
					}
				}
			});
			return basedir;
		}
		catch (IOException e) {
			throw new IllegalStateException("Cannot create temp dir", e);
		}
	}

	public ConfigurableEnvironment getEnvironment() {
		return this.environment;
	}

	public void setEnvironment(ConfigurableEnvironment environment) {
		this.environment = environment;
	}

	public void setUri(String uri) {
		while (uri.endsWith("/")) {
			uri = uri.substring(0, uri.length() - 1);
		}
		int index = uri.indexOf("://");
		if (index > 0 && !uri.substring(index + "://".length()).contains("/")) {
			// If there's no context path add one
			uri = uri + "/";
		}
		this.uri = uri;
	}

	public String getUri() {
		return this.uri;
	}

	public void setBasedir(File basedir) {
		this.basedir = basedir.getAbsoluteFile();
	}

	public File getBasedir() {
		return this.basedir;
	}

	public void setSearchPaths(String... searchPaths) {
		this.searchPaths = searchPaths;
	}

	public String[] getSearchPaths() {
		return this.searchPaths;
	}

	public String getUsername() {
		return this.username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	protected File getWorkingDirectory() {
		if (this.uri.startsWith("file:")) {
			try {
				return new UrlResource(StringUtils.cleanPath(this.uri)).getFile();
			}
			catch (Exception e) {
				throw new IllegalStateException(
						"Cannot convert uri to file: " + this.uri);
			}
		}
		return this.basedir;
	}

	protected String[] getSearchLocations(File dir, String application, String profile,
			String label) {
		String[] locations = this.searchPaths;
		if (locations == null || locations.length == 0) {
			locations = DEFAULT_LOCATIONS;
		}
		else if (locations != DEFAULT_LOCATIONS) {
			locations = StringUtils.concatenateStringArrays(DEFAULT_LOCATIONS, locations);
		}
		Collection<String> output = new LinkedHashSet<String>();
		for (String location : locations) {
			String[] profiles = new String[] { profile };
			if (profile != null) {
				profiles = StringUtils.commaDelimitedListToStringArray(profile);
			}
			String[] apps = new String[] { application };
			if (application != null) {
				apps = StringUtils.commaDelimitedListToStringArray(application);
			}
			for (String prof : profiles) {
				for (String app : apps) {
					String value = location;
					if (app != null) {
						value = value.replace("{application}", app);
					}
					if (prof != null) {
						value = value.replace("{profile}", prof);
					}
					if (label != null) {
						value = value.replace("{label}", label);
					}
					if (!value.endsWith("/")) {
						value = value + "/";
					}
					output.addAll(matchingDirectories(dir, value));
				}
			}
		}
		return output.toArray(new String[0]);
	}

	private List<String> matchingDirectories(File dir, String value) {
		List<String> output = new ArrayList<String>();
		try {
			PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
					this.resourceLoader);
			String path = new File(dir, value).toURI().toString();
			for (Resource resource : resolver.getResources(path)) {
				if (resource.getFile().isDirectory()) {
					output.add(resource.getURI().toString());
				}
			}
		}
		catch (IOException e) {
		}
		return output;
	}

}


text:
import React from 'react';
import { Header, Popup, Table } from '../semantic_ui_react_wrappers';
import { StatusIcon } from './StatusIcon';
import { getMetricResponseOverrun, pluralize } from '../utils';

function formatDays(days) {
    return `${days} ${pluralize("day", days)}`
}

export function Overrun({ metric_uuid, metric, report, measurements, dates }) {
    const { totalOverrun, overruns } = getMetricResponseOverrun(metric_uuid, metric, report, measurements);
    if (totalOverrun === 0) { return null }
    const triggerText = formatDays(totalOverrun)
    let trigger = {triggerText}
    const sortedDates = dates.slice().sort((d1, d2) => d1.getTime() > d2.getTime())
    const period = `${sortedDates.at(0).toLocaleDateString()} - ${sortedDates.at(-1).toLocaleDateString()}`
    const content = (
        <>

                Metric reaction time overrunsIn the period {period}

When did the metric need action?

How long did it take to react?

Status

Start

End

Actual

Desired

Overrun

                {overruns.map((overrun) => (

<StatusIcon size="small" status={overrun.status}/>

{overrun.start.split("T")[0]}

{overrun.end.split("T")[0]}

{formatDays(overrun.actual_response_time)}

{formatDays(overrun.desired_response_time)}

{formatDays(overrun.overrun)}

                ))}

Total

{triggerText}

        </>
    )
    return (
        <Popup
            content={content}
            flowing
            hoverable
            trigger={trigger}
        />
    )
}


text:
**This chart has been deprecated and moved to [Oteemo Charts](https://github.com/oteemo/charts)**

[Nexus OSS](https://www.sonatype.com/nexus-repository-oss) is a free open source repository manager. It supports a wide range of package formats and it's used by hundreds of tech companies.

## Introduction

This chart bootstraps a Nexus OSS deployment on a cluster using Helm.
This setup is best configured in [GCP](https://cloud.google.com/) since:
- [google cloud storage](https://cloud.google.com/storage/) is used for backups
- [GCE Ingress controller](https://github.com/kubernetes/ingress/blob/master/docs/faq/gce.md) is used for using a pre-allocated static IP in GCE.

There is also the option of using a [proxy for Nexus](https://github.com/travelaudience/nexus-proxy) that authenticates Nexus against an external identity provider (only GCP IAM at the moment) which is **disabled** by default.

## Prerequisites

- Kubernetes 1.8+ with Beta APIs enabled
- PV provisioner support in the underlying infrastructure
- [Fulfill Nexus kubernetes requirements](https://github.com/travelaudience/kubernetes-nexus#pre-requisites)

### With GCP IAM enabled
All the [Prerequisites](#Prerequisites) should be in place, plus:
- [Fulfill GCP IAM requirements](https://github.com/travelaudience/kubernetes-nexus/blob/master/docs/admin/configuring-nexus-proxy.md#pre-requisites)

## Testing the Chart
To test the chart:
```bash
$ helm install --dry-run --debug ./
```
To test the chart with your own values:
```bash
$ helm install --dry-run --debug -f my_values.yaml ./
```

## Installing the Chart

To install the chart:

```bash
$ helm install stable/sonatype-nexus
```

The above command deploys Nexus on the Kubernetes cluster in the default configuration. The [configuration](#configuration) section lists the parameters that can be configured during installation.

The default login is admin/admin123

## Uninstalling the Chart

To uninstall/delete the deployment:

```bash
$ helm list
NAME           	REVISION	UPDATED                 	STATUS  	CHART      	NAMESPACE
plinking-gopher	1       	Fri Sep  1 13:19:50 2017	DEPLOYED	sonatype-nexus-0.1.0	default
$ helm delete plinking-gopher
```

The command removes all the Kubernetes components associated with the chart and deletes the release.

## Configuration

The following table lists the configurable parameters of the Nexus chart and their default values.

| Parameter                                   | Description                         | Default                                 |
| ------------------------------------------  | ----------------------------------  | ----------------------------------------|
| `statefulset.enabled`                       | Use statefulset instead of deployment | `false` |
| `replicaCount`                              | Number of Nexus service replicas    | `1`                                     |
| `deploymentStrategy`                        | Deployment Strategy     |  `rollingUpdate` |
| `nexus.imageName`                           | Nexus image                         | `quay.io/travelaudience/docker-nexus`   |
| `nexus.imageTag`                            | Version of Nexus                    | `3.19.1`                                 |
| `nexus.imagePullPolicy`                     | Nexus image pull policy             | `IfNotPresent`                          |
| `nexus.imagePullSecret`                     | Secret to download Nexus image from private registry      | `nil`             |
| `nexus.env`                                 | Nexus environment variables         | `[{install4jAddVmParams: -Xms1200M -Xmx1200M -XX:MaxDirectMemorySize=2G -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap}]` |
| `nexus.resources`                           | Nexus resource requests and limits  | `{}`                                    |
| `nexus.dockerPort`                          | Port to access docker               | `5003`                                  |
| `nexus.nexusPort`                           | Internal port for Nexus service     | `8081`                                  |
| `nexus.service.type`                        | Service for Nexus                   |`NodePort`                                |
| `nexus.service.clusterIp`                   | Specific cluster IP when service type is cluster IP. Use None for headless service |`nil`   |
| `nexus.securityContext`                     | Security Context (for enabling official image use `fsGroup: 2000`) | `{}`     |
| `nexus.labels`                              | Service labels                      | `{}`                                    |
| `nexus.podAnnotations`                      | Pod Annotations                     | `{}`
| `nexus.livenessProbe.initialDelaySeconds`   | LivenessProbe initial delay         | 30                                      |
| `nexus.livenessProbe.periodSeconds`         | Seconds between polls               | 30                                      |
| `nexus.livenessProbe.failureThreshold`      | Number of attempts before failure   | 6                                       |
| `nexus.livenessProbe.timeoutSeconds`        | Time in seconds after liveness probe times out    | `nil`                     |
| `nexus.livenessProbe.path`                  | Path for LivenessProbe              | /                                       |
| `nexus.readinessProbe.initialDelaySeconds`  | ReadinessProbe initial delay        | 30                                      |
| `nexus.readinessProbe.periodSeconds`        | Seconds between polls               | 30                                      |
| `nexus.readinessProbe.failureThreshold`     | Number of attempts before failure   | 6                                       |
| `nexus.readinessProbe.timeoutSeconds`       | Time in seconds after readiness probe times out    | `nil`                    |
| `nexus.readinessProbe.path`                 | Path for ReadinessProbe             | /                                       |
| `nexus.hostAliases`                         | Aliases for IPs in /etc/hosts       | []                                      |
| `nexusProxy.enabled`                        | Enable nexus proxy                  | `true`                                  |
| `nexusProxy.svcName`                        | Nexus proxy service name            | `nil`                                  |
| `nexusProxy.targetPort`                     | Container Port for Nexus proxy      | `8080`                                  |
| `nexusProxy.port`                           | Port for exposing Nexus             | `8080`                                  |
| `nexusProxy.imageName`                      | Proxy image                         | `quay.io/travelaudience/docker-nexus-proxy` |
| `nexusProxy.imageTag`                       | Proxy image version                 | `2.5.0`                                 |
| `nexusProxy.imagePullPolicy`                | Proxy image pull policy             | `IfNotPresent`                          |
| `nexusProxy.resources`                      | Proxy resource requests and limits  | `{}`                                    |
| `nexusProxy.env.nexusHttpHost`              | Nexus url to access Nexus           | `nil`                                   |
| `nexusProxy.env.nexusDockerHost`            | Containers url to be used with docker | `nil`                                 |
| `nexusProxy.env.enforceHttps`               | Allow only https access or not      | `false`                                 |
| `nexusProxy.env.cloudIamAuthEnabled`        | Enable GCP IAM authentication in Nexus proxy  | `false`                       |
| `nexusProxyRoute.enabled`     | Set to true to create route for additional service | `false` |
| `nexusProxyRoute.labels`      | Labels to be added to proxy route            | `{}` |
| `nexusProxyRoute.annotations` | Annotations to be added to proxy route       | `{}` |
| `nexusProxyRoute.path`        | Host name of Route e.g jenkins.example.com   |  nil |
| `persistence.enabled`                       | Create a volume for storage         | `true`                                  |
| `persistence.accessMode`                    | ReadWriteOnce or ReadOnly           | `ReadWriteOnce`                         |
| `persistence.storageClass`                  | Storage class of Nexus PVC          | `nil`                                   |
| `persistence.storageSize`                   | Size of Nexus data volume           | `8Gi`                                   |
| `persistence.annotations`                   | Persistent Volume annotations       | `{}`                                    |
| `persistence.existingClaim`                 | Existing persistent volume name     | `nil`                                   |
| `nexusBackup.enabled`                       | Nexus backup process                | `false`                                 |
| `nexusBackup.imageName`                     | Nexus backup image                  | `quay.io/travelaudience/docker-nexus-backup` |
| `nexusBackup.imageTag`                      | Nexus backup image version          | `1.5.0`                                 |
| `nexusBackup.imagePullPolicy`               | Backup image pull policy            | `IfNotPresent`                          |
| `nexusBackup.env.targetBucket`              | Required if `nexusBackup` is enabled. Google Cloud Storage bucker for backups format `gs://BACKUP_BUCKET`  | `nil`  |
| `nexusBackup.nexusAdminPassword`            | Nexus admin password used by the backup container to access Nexus API. This password should match the one that gets chosen by the user to replace the default admin password after the first login  | `admin123`                |
| `nexusBackup.persistence.enabled`           | Create a volume for backing Nexus configuration  | `true`                     |
| `nexusBackup.persistence.accessMode`        | ReadWriteOnce or ReadOnly           | `ReadWriteOnce`                         |
| `nexusBackup.persistence.storageClass`      | Storage class of Nexus backup PVC   | `nil`                                   |
| `nexusBackup.persistence.storageSize`       | Size of Nexus backup data volume    | `8Gi`                                   |
| `nexusBackup.persistence.annotations`       | PV annotations for backup           | `{}`                                    |
| `nexusBackup.persistence.existingClaim`     | Existing PV name for backup         | `nil`                                   |
| `nexusBackup.resources`                     | Backup resource requests and limits | `{}`                                    |
| `ingress.enabled`                           | Create an ingress for Nexus         | `true`                                  |
| `ingress.annotations`                       | Annotations to enhance ingress configuration  | `{}`                          |
| `ingress.tls.enabled`                       | Enable TLS                          | `true`                                 |
| `ingress.tls.secretName`                    | Name of the secret storing TLS cert, `false` to use the Ingress' default certificate | `nexus-tls`                             |
| `ingress.path`                              | Path for ingress rules. GCP users should set to `/*` | `/`                    |
| `tolerations`                               | tolerations list                    | `[]`                                    |
| `config.enabled`                            | Enable configmap                    | `false`                                 |
| `config.mountPath`                          | Path to mount the config            | `/sonatype-nexus-conf`                  |
| `config.data`                               | Configmap data                      | `nil`                                   |
| `deployment.annotations`                    | Annotations to enhance deployment configuration  | `{}`                       |
| `deployment.initContainers`                 | Init containers to run before main containers  | `nil`                        |
| `deployment.postStart.command`              | Command to run after starting the nexus container  | `nil`                    |
| `deployment.additionalContainers`           | Add additional Container         | `nil`                                      |
| `deployment.additionalVolumes`              | Add additional Volumes           | `nil`                                      |
| `deployment.additionalVolumeMounts`         | Add additional Volume mounts     | `nil`                                      |
| `secret.enabled`                            | Enable secret                    | `false`                                    |
| `secret.mountPath`                          | Path to mount the secret         | `/etc/secret-volume`                       |
| `secret.readOnly`                           | Secret readonly state            | `true`                                     |
| `secret.data`                               | Secret data                      | `nil`                                      |
| `service.enabled`                           | Enable additional service        | `nil`                                      |
| `service.name`                              | Service name                     | `nil`                                      |
| `service.portName`                          | Service port name                | `nil`                                      |
| `service.labels`                            | Service labels                   | `nil`                                      |
| `service.annotations`                       | Service annotations              | `nil`                                      |
| `service.loadBalancerSourceRanges`          | Service LoadBalancer source IP whitelist | `nil`                              |
| `service.targetPort`                        | Service port                     | `nil`                                      |
| `service.port`                              | Port for exposing service        | `nil`                                      |
| `serviceAccount.create`                     | Automatically create a service account | `true`                               |
| `serviceAccount.name`                       | Service account to use 				   | `nil`								  |
| `serviceAccount.annotations`                | Service account annotations			   | `nil`	   							  |
| `route.enabled`         | Set to true to create route for additional service | `false` |
| `route.name`            | Name of route                                      | `docker` |
| `route.portName`        | Target port name of service                        | `docker` |
| `route.labels`          | Labels to be added to route                        | `{}` |
| `route.annotations`     | Annotations to be added to route                   | `{}` |
| `route.path`            | Host name of Route e.g jenkins.example.com         | nil |

If `nexusProxy.env.cloudIamAuthEnabled` is set to `true` the following variables need to be configured

| Parameter                        | Description                        | Default                                              |
| -----------------------------    | ---------------------------------- | ---------------------------------------------------- |
| `nexusProxy.env.clientId`        | GCP OAuth client ID                | `nil`                                                |
| `nexusProxy.env.clientSecret`    | GCP OAuth client Secret            | `nil`                                                |
| `nexusProxy.env.organizationId`  | GCP organization ID                | `nil`                                                |
| `nexusProxy.env.redirectUrl`     | OAuth callback url. example `https://nexus.example.com/oauth/callback` | `nil`            |
| `nexusProxy.env.requiredMembershipVerification` | Whether users presenting valid JWT tokens must still be verified for membership within the GCP organization. | `true`    |
| `nexusProxy.secrets.keystore`    | base-64 encoded value of the keystore file needed for the proxy to sign user tokens. Example: cat keystore.jceks | base64 | `nil`  |
| `nexusProxy.secrets.password`    | Password to the Java Keystore file | `nil`                                                |

```bash
$ helm install --name my-release --set persistence.enabled=false stable/sonatype-nexus
```
The above example turns off the persistence. Data will not be kept between restarts or deployments

Alternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example,

```bash
$ helm install --name my-release -f my-values.yaml stable/sonatype-nexus
```

### Persistence

By default a PersistentVolumeClaim is created and mounted into the `/nexus-data` directory. In order to disable this functionality
you can change the `values.yaml` to disable persistence which will use an `emptyDir` instead.

> *"An emptyDir volume is first created when a Pod is assigned to a Node, and exists as long as that Pod is running on that node. When a Pod is removed from a node for any reason, the data in the emptyDir is deleted forever."*

You must enable StatefulSet (`statefulset.enabled=true`) for true data persistence. If using Deployment approach, you can not recover data after restart or delete of helm chart. Statefulset will make sure that it picks up the same old volume which was used by the previous life of the nexus pod, helping you recover your data. When enabling statefulset, its required to enable the persistence.

### Recommended settings

As a minimum for running in production, the following settings are advised:

```yaml
nexusProxy:
  env:
    nexusDockerHost: container.example.com
    nexusHttpHost: nexus.example.com

nexusBackup:
  env:
    targetBucket: "gs://my-nexus-backup"
  persistence:
    storageClass: standard

ingress:
  enabled: true
  annotations:
    kubernetes.io/ingress.class: gce
    kubernetes.io/tls-acme: true

persistence:
  storageClass: standard
  storageSize: 1024Gi

resources:
  requests:
    cpu: 250m
    # Based on https://support.sonatype.com/hc/en-us/articles/115006448847#mem
    # and https://twitter.com/analytically/status/894592422382063616:
    #   Xms == Xmx
    #   Xmx <= 4G
    #   MaxDirectMemory >= 2G
    #   Xmx + MaxDirectMemory <= RAM * 2/3 (hence the request for 4800Mi)
    #   MaxRAMFraction=1 is not being set as it would allow the heap
    #     to use all the available memory.
    memory: 4800Mi
```

## After Installing the Chart
After installing the chart a couple of actions need still to be done in order to use nexus. Please follow the instructions below.

### Nexus Configuration
The following steps need to be executed in order to use Nexus:

- [Configure Nexus](https://github.com/travelaudience/kubernetes-nexus/blob/master/docs/admin/configuring-nexus.md)
- [Configure Backups](https://github.com/travelaudience/kubernetes-nexus/blob/master/docs/admin/configuring-nexus.md#configure-backup)

and if GCP IAM authentication is enabled, please also check:
- [Enable GCP IAM authentication in Nexus ](https://github.com/travelaudience/kubernetes-nexus/blob/master/docs/admin/configuring-nexus-proxy.md#enable-gcp-iam-auth)

### Nexus Usage
To see how to use Nexus with different tools like Docker, Maven, Python, and so on please check:

- [Nexus Usage](https://github.com/travelaudience/kubernetes-nexus#usage)

### Disaster Recovery
In a disaster recovery scenario, the latest backup made by the nexus-backup container should be restored. In order to achieve this please follow the procedure described below:
- [Restore Backups](https://github.com/travelaudience/kubernetes-nexus#restore)


text:
module Database.HaskellDB.PrimQuery (
		  -- * Type Declarations

		  -- ** Types
		  TableName, Attribute, Scheme, Assoc, Name

		  -- ** Data types
		 , PrimQuery(..), RelOp(..), SpecialOp(..)
		 , PrimExpr(..), OrderExpr(..)
                 , BinOp(..), UnOp(..), OrderOp(..), AggrOp(..)
	         , Literal(..)

		  -- * Function declarations
		 , extend, times
		 , attributes, attrInExpr, attrInOrder
		 , substAttr
		 , isAggregate, isConstant
		 , foldPrimQuery, foldPrimExpr
		 ) where

import Data.List ((\\), union)
import Control.Exception (assert)
import System.Time (CalendarTime, formatCalendarTime)
import System.Locale (defaultTimeLocale, iso8601DateFormat)
import Text.PrettyPrint.HughesPJ

-----------------------------------------------------------
-- data definitions
-- PrimQuery is the data type of relational expressions.
-- Since 'Project' takes an association, it is actually a
-- projection- and rename-operator at once.
-----------------------------------------------------------

type TableName  = String
type Attribute  = String
type Name = String
type Scheme     = [Attribute]
type Assoc      = [(Attribute,PrimExpr)]

data PrimQuery  = BaseTable TableName Scheme
                | Project   Assoc PrimQuery
                | Restrict  PrimExpr PrimQuery
                | Group Assoc PrimQuery
                | Binary    RelOp PrimQuery PrimQuery
                | Special   SpecialOp PrimQuery
                | Empty
		deriving (Show)

data RelOp      = Times
                | Union
                | UnionAll
                | Intersect
                | Divide
                | Difference
                deriving (Show)

data SpecialOp  = Order [OrderExpr]
		| Top Int
		| Offset Int
		deriving (Show)

data OrderExpr = OrderExpr OrderOp PrimExpr
		deriving (Show)

data OrderOp = OpAsc | OpDesc
		deriving (Show)

data PrimExpr   = AttrExpr  Attribute
                | BinExpr   BinOp PrimExpr PrimExpr
                | UnExpr    UnOp PrimExpr
                | AggrExpr  AggrOp PrimExpr
                | ConstExpr Literal
		| CaseExpr [(PrimExpr,PrimExpr)] PrimExpr
                | ListExpr [PrimExpr]
                | ParamExpr (Maybe Name) PrimExpr
                | FunExpr Name [PrimExpr]
                | CastExpr Name PrimExpr -- ^ Cast an expression to a given type.
                deriving (Read,Show)

data Literal = NullLit
	     | DefaultLit            -- ^ represents a default value
	     | BoolLit Bool
	     | StringLit String
	     | IntegerLit Integer
	     | DoubleLit Double
	     | DateLit CalendarTime
	     | OtherLit String       -- ^ used for hacking in custom SQL
	       deriving (Read,Show)

data BinOp      = OpEq | OpLt | OpLtEq | OpGt | OpGtEq | OpNotEq
                | OpAnd | OpOr
                | OpLike | OpIn
                | OpOther String

                | OpCat
                | OpPlus | OpMinus | OpMul | OpDiv | OpMod
                | OpBitNot | OpBitAnd | OpBitOr | OpBitXor
                | OpAsg
                deriving (Show,Read)

data UnOp	= OpNot
		| OpIsNull | OpIsNotNull
		| OpLength
		| UnOpOther String
		deriving (Show,Read)

data AggrOp     = AggrCount | AggrSum | AggrAvg | AggrMin | AggrMax
                | AggrStdDev | AggrStdDevP | AggrVar | AggrVarP
                | AggrOther String
                deriving (Show,Read)

-- | Creates a projection of some attributes while
--   keeping all other attributes in the relation visible too.
extend :: Assoc -> PrimQuery -> PrimQuery
extend assoc query
	= Project (assoc ++ assoc') query
        where
          assoc'  = assocFromScheme (attributes query)

-- | Takes the cartesian product of two queries.
times :: PrimQuery -> PrimQuery -> PrimQuery
times (Empty) query	= query
times query (Empty)     = query
times query1 query2     =
    assert (length (attributes query1 \\ attributes query2) ==
		   length (attributes query1))
    Binary Times query1 query2

-- | Returns the schema (the attributes) of a query
attributes :: PrimQuery -> Scheme
attributes (Empty)              = []
attributes (BaseTable nm attrs) = attrs
attributes (Project assoc q)    = map fst assoc
attributes (Restrict expr q)    = attributes q
attributes (Special op q)	= attributes q
attributes (Binary op q1 q2)    = case op of
                                    Times       -> attr1 `union` attr2
                                    Union       -> attr1
                                    UnionAll    -> attr1
                                    Intersect   -> attr1
                                    Divide      -> attr1
                                    Difference  -> attr1
                                where
                                  attr1         = attributes q1
                                  attr2         = attributes q2
attributes (Group _ qry) = attributes qry

-- | Returns a one-to-one association of a
--   schema. ie. @assocFromScheme ["name","city"]@ becomes:
--   @[("name",AttrExpr "name"), ("city",AttrExpr "city")]@
assocFromScheme :: Scheme -> Assoc
assocFromScheme scheme
		= map (\attr -> (attr,AttrExpr attr)) scheme

-- | Returns all attributes in an expression.
attrInExpr :: PrimExpr -> Scheme
attrInExpr      = concat . foldPrimExpr (attr,scalar,binary,unary,aggr,_case,list,param,func, cast)
                where
                  attr name     = [[name]]
                  scalar s      = [[]]
                  binary op x y = x ++ y
                  unary op x    = x
                  aggr op x	= x
		  _case cs el   = concat (uncurry (++) (unzip cs)) ++ el
                  list xs       = concat xs
                  param _ _ = [[]]
                  func _ es = concat es
                  cast _ expr = expr

-- | Returns all attributes in a list of ordering expressions.
attrInOrder :: [OrderExpr] -> Scheme
attrInOrder os = concat [attrInExpr e | OrderExpr _ e <- os]

-- | Substitute attribute names in an expression.
substAttr :: Assoc -> PrimExpr -> PrimExpr
substAttr assoc
    = foldPrimExpr (attr,ConstExpr,BinExpr,UnExpr,AggrExpr,CaseExpr,ListExpr,ParamExpr,FunExpr,CastExpr)
        where
          attr name     = case (lookup name assoc) of
                            Just x      -> x
                            Nothing     -> AttrExpr name

-- | Determines if a primitive expression represents a constant
-- or is an expression only involving constants.
isConstant :: PrimExpr -> Bool
isConstant x = countAttr x == 0
  where
    countAttr = foldPrimExpr (const 1, const 0, binary, unary, aggr, _case, list,
                                    const2 1, const2 1, cast)
      where
        _case cs el = sum (map (uncurry (+)) cs) + el
        list = sum
        const2 a _ _ = a
        binary _ x y = x + y
        unary _ x = x
        aggr _ x = x
        cast _ n = n

isAggregate :: PrimExpr -> Bool
isAggregate x = countAggregate x > 0

countAggregate :: PrimExpr -> Int
countAggregate
	= foldPrimExpr (const 0, const 0, binary, unary, aggr, _case, list,(\_ _ -> 0), (\_ n -> sum n), cast)
	where
          binary op x y	 	= x + y
          unary op x		= x
          aggr op x		= x + 1
	  _case cs el           = sum (map (uncurry (+)) cs) + el
          list xs               = sum xs
          cast _ e = e

-- | Fold on 'PrimQuery'
foldPrimQuery :: (t, TableName -> Scheme -> t, Assoc -> t -> t,
                  PrimExpr -> t -> t, RelOp -> t -> t -> t,
                  Assoc -> t -> t, SpecialOp -> t -> t) -> PrimQuery -> t
foldPrimQuery (empty,table,project,restrict,binary,group,special)
        = fold
        where
          fold (Empty)  = empty
          fold (BaseTable name schema)
                        = table name schema
          fold (Project assoc query)
                        = project assoc (fold query)
          fold (Restrict expr query)
                        = restrict expr (fold query)
          fold (Binary op query1 query2)
                        = binary op (fold query1) (fold query2)
          fold (Group assocs query)
                        = group assocs (fold query)
          fold (Special op query)
          		= special op (fold query)
-- | Fold on 'PrimExpr'
foldPrimExpr :: (Attribute -> t, Literal -> t, BinOp -> t -> t -> t,
                 UnOp -> t -> t, AggrOp -> t -> t,
		 [(t,t)] -> t -> t, [t] -> t, Maybe Name -> t -> t, Name -> [t] -> t, Name -> t -> t) -> PrimExpr -> t
foldPrimExpr (attr,scalar,binary,unary,aggr,_case,list,param,fun,cast)
        = fold
        where
          fold (AttrExpr name) = attr name
          fold (ConstExpr s)   = scalar s
          fold (BinExpr op x y)= binary op (fold x) (fold y)
          fold (UnExpr op x)   = unary op (fold x)
          fold (AggrExpr op x) = aggr op (fold x)
	  fold (CaseExpr cs el) = _case (map (both fold) cs) (fold el)
          fold (ListExpr xs) = list (map fold xs)
          fold (ParamExpr n value) = param n (fold value)
          fold (FunExpr n exprs) = fun n (map fold exprs)
          fold (CastExpr n expr) = cast n (fold expr)

          both f (x,y) = (f x, f y)


text:
<?php

declare(strict_types=1);

uses()->group('management', 'management.guardian');

beforeEach(function(): void {
    $this->endpoint = $this->api->mock()->guardian();
});

test('getFactors() issues an appropriate request', function(): void {
    $this->endpoint->getFactors();

    expect($this->api->getRequestMethod())->toEqual('GET');
    expect($this->api->getRequestUrl())->toEndWith('/api/v2/guardian/factors');
    expect($this->api->getRequestQuery())->toBeEmpty();
});

test('getEnrollment() issues an appropriate request', function(): void {
    $id = uniqid();

    $this->endpoint->getEnrollment($id);

    expect($this->api->getRequestMethod())->toEqual('GET');
    expect($this->api->getRequestUrl())->toEndWith('/api/v2/guardian/enrollments/' . $id);
    expect($this->api->getRequestQuery())->toBeEmpty();
});

test('deleteEnrollment() issues an appropriate request', function(): void {
    $id = uniqid();

    $this->endpoint->deleteEnrollment($id);

    expect($this->api->getRequestMethod())->toEqual('DELETE');
    expect($this->api->getRequestUrl())->toEndWith('/api/v2/guardian/enrollments/' . $id);
    expect($this->api->getRequestQuery())->toBeEmpty();
});


text:
/*
 *  Gruntfile.js
 *  This nasty looking Javascript file actually helps Grunt
 *  automate the building of Business Casual. I know, I'm
 *  surprised it works, too.
 *
 *  © 2014 Jonathan Ballands
 */

module.exports = function(grunt) {

    grunt.initConfig({

        pkg: grunt.file.readJSON("package.json"),

        uglify: {
            dist: {
                files: {
                    "js/business-casual.min.js": ["js/business-casual.js"]
                }
            }
        },

        less: {
            options: {
                compress: true,
                yuicompress: true,
                optimization: 2,

            },
            dist: {
                files: {
                    "css/business-casual.css": ["less/business-casual.less"]
                }
            }
        }

    });

    grunt.loadNpmTasks("grunt-contrib-uglify");
    grunt.loadNpmTasks("grunt-contrib-less");
    grunt.loadNpmTasks("grunt-contrib-watch");

    grunt.registerTask("default", ["uglify", "less"]);

};


text:
<?php

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
    'Symfony\\Component\\VarDumper\\' => array($vendorDir . '/symfony/var-dumper'),
    'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'),
    'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'),
    'Intervention\\Image\\' => array($vendorDir . '/intervention/image/src/Intervention/Image'),
    'Illuminate\\Support\\' => array($vendorDir . '/illuminate/support'),
    'Illuminate\\Pagination\\' => array($vendorDir . '/illuminate/pagination'),
    'Illuminate\\Database\\' => array($vendorDir . '/illuminate/database'),
    'Illuminate\\Contracts\\' => array($vendorDir . '/illuminate/contracts'),
    'Illuminate\\Container\\' => array($vendorDir . '/illuminate/container'),
    'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
    'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
    'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
    'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
    'Carbon\\' => array($vendorDir . '/nesbot/carbon/src/Carbon'),
);


text:
namespace Inlinq.Sort
{
    interface ISortRebind<T, TSort>
    {
        TSort Rebind<TNextSort, TNextData>(TNextSort nextSort, TNextData nextData)
            where TNextSort : ISecondarySort<T, TNextData>;
    }
}


text:
<?php

declare(strict_types=1);

namespace PentagonalProject\App\Rest\Interfaces;

/**
 * Interface SignValidatorInterface
 * @package PentagonalProject\App\Rest\Interfaces
 */
interface SignValidatorInterface
{
    /**
     * @param SignInterface $sign
     *
     * @return bool
     */
    public function verify(SignInterface $sign) : bool;

    /**
     * @return SignInterface
     */
    public function getSign() : SignInterface;
}


text:
# Customizing components

You can easily customize the appearance of a Material-UI component.

As components can be used in different contexts, there are several approaches to this. Going from the narrowest use-case to the broadest, these are:

1. [Конкретное изменение для единичного случая](#1-specific-variation-for-a-one-time-situation)
2. [Динамическое изменение для единичного случая](#2-dynamic-variation-for-a-one-time-situation)
3. [Особый вариант компонента](#3-specific-variation-of-a-component) использумый в различных контекстах
4. [Material Design варианты](#4-material-design-variations) как у компонента кнопка
5. [Глобальное изменение темы](#5-global-theme-variation)

## 1. Конкретное изменение для единичного случая

Возможно, вам придется изменить стиль компонента в конкретном месте. Для этого вам предоставляются следующие методы:

### Overriding styles with class names

Первый способ переопределения стиля компонента - использовать **имена классов**. Каждый компонент предоставляет свойство `className` которое всегда применяется к корневому элементу.

В этом примере компонент высшего-порядка [`withStyles()`](/styles/basics/#higher-order-component-api) используется для внедрения пользовательских стилей в DOM и передачи имени класса компоненту `ClassNames` через его свойство `classes`. Для создания стилей вы можете воспользоваться [любым доступным стилевым решением](/guides/interoperability/), вплоть до обычного CSS, но вы обязаны принимать во внимание [порядок внедрения CSS](/styles/advanced/#css-injection-order), поскольку CSS внедренный в DOM через Material-UI имеет максимально возможную специфичность, так как `<link>` внедряется в самом конце раздела `<head />` для гарантии корректного отображения компонентов.

{{"demo": "pages/customization/components/ClassNames.js"}}

### Overriding styles with classes

Когда ` className ` свойства недостаточно, и вам нужен доступ ко вложенным элементам, вы можете воспользоваться свойством объекта `classes` для настройки всех CSS, внедренных через Material-UI для данного компонента.

The list of classes for each component is documented in the component API page, you should refer to the **CSS section** and **rule name column**. Для примера можете взглянуть на [Button CSS API](/api/button/#css). Кроме того, вы можете воспользоваться [встроенными в браузер инструментами разработчика](#using-the-dev-tools).

В этом примере также используется ` withStyles() ` (см. выше), но теперь ` ClassesNesting ` присваивает свойству `classes` компонета `Button` обьект сопоставляющий **имена переопределяемых классов** (стилевые правила) с **именам использумых классов CSS ** (значениями). Существующие классы компонента будут по прежнему внедряться, поэтому необходимо указать только те стили, которые вы хотите добавить или переопределить.

Обратите внимание, что в дополнение к стилю кнопки, стиль текста кнопки был изменен на стиль с заглавными буквами:

{{"demo": "pages/customization/components/ClassesNesting.js"}}

### Overriding styles with global class names

[Follow this section](/styles/advanced/#with-material-ui-core).

### Использование инструментов разработчика

Инструменты разработчика браузера могут сэкономить вам много времени. В режиме разработки имена классов Material-UI [следуют простому шаблону](/styles/advanced/#class-names): ` Mui[имя компонента]-[имя стилевого правила]-[UUID]`.

Вернемся к упомянутому выше примеру. Как вы можете переопределить текст кнопки?

![Инструменты разработчика](/static/images/customization/dev-tools.png)

Используя инструменты разработчика, вы знаете, что вам нужно нацелиться на компонент `Button` и стилевое правило `label`:

```jsx
<Button classes={{ label: 'my-class-name' }} />
```

### Краткая запись

Приведенный выше пример кода может быть сокращен за счет использования **того же CSS API ** в качестве дочернего компонента. В этом примере компонент высшего порядка `withStyles()` внедряет свойство `classes`, используемое затем [компонентом `Button` ](/api/button/#css).

```jsx
const StyledButton = withStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    borderRadius: 3,
    border: 0,
    color: 'white',
    height: 48,
    padding: '0 30px',
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
  },
  label: {
    textTransform: 'capitalize',
  },
})(Button);
```

{{"demo": "pages/customization/components/ClassesShorthand.js"}}

### Pseudo-classes

The components special states, like *hover*, *focus*, *disabled* and *selected*, are styled with a higher CSS specificity. [Специфичность - это весовой коэффициент](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) применяемый к данной декларации CSS.

In order to override the components special states, **you need to increase specificity**. Вот пример с *отключеным* состоянием и компонентом кнопка использующим **псевдокласс** (`:disabled`):

```css
.Button {
  color: black;
}
.Button:disabled { /* Increase the specificity */
  color: white;
}
```

```jsx
<Button disabled className="Button">
```

Иногда вы не можете использовать **псевдо-класс**, так как это состояние в платформе отсутствует. В качестве примера можно привести компонент пункт меню и состояние *выбрано*. Aside from accessing nested elements, the `classes` property can be used to customize the special states of Material-UI components:

```css
.MenuItem {
  color: black;
}
.MenuItem.selected { /* Increase the specificity */
  color: blue;
}
```

```jsx
<MenuItem selected classes={{ root: 'MenuItem', selected: 'selected' }}>
```

#### Почему я должен повышать специфичность для переопределения отдельного состояния компонента?

Спецификация CSS, по определению, обязывает псевдоклассы повышать специфичность. For consistency, Material-UI increases the specificity of its custom pseudo-classes. This has one important advantage, it allows you to cherry-pick the state you want to customize.

#### Can I use a different API that requires fewer boilerplate?

Instead of providing values to the `classes` prop API, you can rely on [the global class names](/styles/advanced/#with-material-ui-core) generated by Material-UI. It implements all these custom pseudo-classes:

| classes key  | Global class name |
|:------------ |:----------------- |
| checked      | Mui-checked       |
| disabled     | Mui-disabled      |
| error        | Mui-error         |
| focused      | Mui-focused       |
| focusVisible | Mui-focusVisible  |
| required     | Mui-required      |
| expanded     | Mui-expanded      |
| selected     | Mui-selected      |

```css
.MenuItem {
  color: black;
}
.MenuItem.Mui-selected { /* Increase the specificity */
  color: blue;
}
```

```jsx
<MenuItem selected className="MenuItem">
```

### Используйте `$ruleName` для ссылки на правило в той же таблице стилей

Плагин [jss-nested](https://github.com/cssinjs/jss-nested) (доступный по умолчанию) позволяет упростить процесс повышения специфичности.

```js
const styles = {
  root: {
    '&$disabled': {
      color: 'white',
    },
  },
  disabled: {},
};
```

компилируется в:

```css
.root-x.disable-x {
  color: white;
}
```

⚠  Чтобы это сработало, вам нужно применить к DOM оба сгенерированных имени класса (`root` & `disabled`).

```jsx
<Button
  disabled
  classes={{
    root: classes.root, // class name, e.g. `root-x`
    disabled: classes.disabled, // class name, e.g. `disabled-x`
  }}
>
```

{{"demo": "pages/customization/components/ClassesState.js"}}

### Overriding with inline-styles

Второй способ переопределить стиль компонента – использовать подход **встроенного стиля**. Каждый компонент предоставляет свойство `style`. Эти свойства всегда применяются к корневому элементу.

Вам не нужно беспокоиться о специфичности CSS, так как встроенный стиль имеет приоритет над обычным CSS.

{{"demo": "pages/customization/components/InlineStyle.js"}}

[Когда я должен использовать встраиваемый стиль, а когда классы?](/getting-started/faq/#when-should-i-use-inline-style-vs-classes)

## 2. Динамическое изменение для единичного случая

You have learned how to override the style of a Material-UI component in the previous section. Теперь давайте посмотрим, как мы можем сделать эти переопределения динамическими. Here are five alternatives; each has it's pros and cons.

### Динамический CSS

{{"demo": "pages/customization/components/DynamicCSS.js"}}

### Ответвление имени класса

{{"demo": "pages/customization/components/DynamicClassName.js"}}

### CSS переменные

{{"demo": "pages/customization/components/DynamicCSSVariables.js"}}

### Inline-styles

{{"demo": "pages/customization/components/DynamicInlineStyle.js"}}

### Вложенные темы

{{"demo": "pages/customization/components/DynamicThemeNesting.js"}}

## 3. Особый вариант компонента

Возможно вам потребуется создать вариант компонента и использовать его в разных контекстах, например раскрашенную кнопку на странице вашего товара, но вы, вероятно, захотите сохранить свой код [*компактным*](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).

Наилучший подход состоит в том, чтобы следовать варианту 1, а затем воспользоваться преимуществами композиции React, экспортируя настроенный компонент для использования там, где он вам нужен.

{{"demo": "pages/customization/components/Component.js", "hideEditButton": true}}

## 4. Material Design варианты

Спецификация Material Design допускает существование некоторых компонентов в различных вариантах. Так, например, кнопки реализованы в разных формах: [text](https://material.io/design/components/buttons.html#text-button) (прежде "flat"), [contained](https://material.io/design/components/buttons.html#contained-button) (прежде "raised"), [FAB](https://material.io/design/components/buttons-floating-action-button.html) и другие.

Material-UI старается реализовать все эти варианты. Пожалуйста, обратитесь к разделу документации [Поддерживаемые компоненты](/getting-started/supported-components/), чтобы узнать текущее состояние реализации всех компонентов Material Design.

## 5. Глобальное изменение темы

In order to promote consistency between components, and manage the user interface appearance as a whole, Material-UI provides a mechanism to apply global changes.

The demos of this section covers how to the change the button's font size.

### Настраиваемые параметры темы

You can adjust the [theme configuration variables](/customization/theming/#theme-configuration-variables).

```jsx
const theme = createMuiTheme({
  typography: {
    button: {
      fontSize: '1rem',
    },
  },
});
```

{{"demo": "pages/customization/components/ThemeVariables.js"}}

### Глобальное переопределение CSS

Вы также можете настроить все экземпляры компонента с помощью CSS. Components expose [global class names](/styles/advanced/#with-material-ui-core) to enable this. Это очень похоже на настройку Bootstrap.

```jsx
const GlobalCss = withStyles({
  // @global is handled by jss-plugin-global.
  '@global': {
    // You should target [class*="MuiButton-root"] instead if you nest themes.
    '.MuiButton-root': {
      fontSize: '1rem',
    },
  },
})(() => null);

// …

<GlobalCss />
```

{{"demo": "pages/customization/components/GlobalCssOverride.js", "iframe": true, "height": 70}}

### Глобальное переопределение темы

Вы можете воспользоваться `переопределением` ключевых параметров `темы`, чтобы потенциально изменить любой стиль, внедренный Material-UI в DOM. Дальнейшие подробности об этом в разделе документации [темы](/customization/globals/#css).

```jsx
const theme = createMuiTheme({
  overrides: {
    MuiButton: {
      root: {
        fontSize: '1rem',
      },
    },
  },
});
```

{{"demo": "pages/customization/components/GlobalThemeOverride.js"}}


text:
package Pod::Abstract;
use strict;
use warnings;

use Pod::Abstract::Node;
use Pod::Abstract::Path;
use Pod::Abstract::Parser;
use IO::String;

our $VERSION = '0.20';

=head1 NAME

Pod::Abstract - Abstract document tree for Perl POD documents

=head1 SYNOPSIS

 use Pod::Abstract;
 use Pod::Abstract::BuildNode qw(node);

 # Get all the first level headings, and put them in a verbatim block
 # at the start of the document
 my $pa = Pod::Abstract->load_filehandle(\*STDIN);
 my @headings = $pa->select('/head1@heading');
 my @headings_text = map { $_->pod } @headings;
 my $headings_node = node->verbatim(join "\n",@headings_text);

 $pa->unshift( node->cut );
 $pa->unshift( $headings_node );
 $pa->unshift( node->pod );

 print $pa->pod;

=head1 DESCRIPTION

POD::Abstract provides a means to load a POD (or POD compatible)
document without direct reference to it's syntax, and perform
manipulations on the abstract syntax tree.

This can be used to support additional features for POD, to format
output, to compile into alternative formats, etc.

=head2 WHY?

If you've ever asked yourself "What does Pod do for me?", this module
is intended to answer that question.

While Pod looks like a simple format, the specification calls for a
number of special cases to be handled, and that makes any software
that works on Pod as text more complex than it needs to be.

In addition to this, Pod does not lend itself to a natural structured
model. This makes it difficult to manipulate without damaging the
validity of the document.

Pod::Abstract solves these problems by loading the document into a
structured tree, and providing consistent traversal, searching,
manpulation and re-serialisation. Pod related utilities are easy to
write using Pod::Abstract.

The design goal of Pod::Abstract is to do the hard work for the
programmer - the library should work for you, and as such it should be
significantly easier than string mashing what you want out of a Pod
document.

=head2 PROCESSING MODEL

The intent with POD::Abstract is to provide a means to decorate a
parse tree, rather than manipulate text, to allow other software to
add features and functionality to POD based documenation systems.

If you wish to write modules that interact nicely with other
POD::Abstract modules, then you should provide a POD::Abstract -E<gt>
POD::Abstract translation. Leave any document element that your
program is not interested in directly untouched in the parse tree, and
if you have data that could be useful to other packages, decorate the
parse tree with that data even if you don't see any direct way to use
it in the output.

In this way, when you want one more feature for POD, rather than write
or fork a whole translator, a single inline "decorator" can be added.

The C<paf> utility provides a good starting point, which also allows
you to hook in to an existing filter/transform library. Simply add a
C<Pod::Abstract::Filter> class to the namespace and it should start
working as a C<paf> command.

=head2 EXAMPLE

Suppose you are frustrated by the verbose list syntax used by regular
POD. You might reasonably want to define a simplified list format for
your own use, except POD formatters won't support it.

With Pod::Abstract you can write an inline filter to convert:

 * item 1
 * item 2
 * item 3

into:

 =over

 =item *

 item 1

 =item *

 item 2

 =item *

 item 3

 =back

This transformation can be simply performed on the document tree. If
your formatter does not use Pod::Abstract, you can simply pipe out POD
and use a regular formatter. If your formatter supports Pod::Abstract
though, then you can feed in the syntax tree directly without having
to re-serialise and parse the document.

In addition to this, because the source document is still valid Pod,
you aren't breaking compatibility with regular perldoc just by making
Pod::Abstract transformations.

=head2 POD SUPPORT

Pod::Abstract aims to support all POD rules defined in perlpodspec
(even the ones I don't like), except for those directly related to
formatting output, or which cannot be implemented generically.

=head1 COMPONENTS

Pod::Abstract is comprised of:

=over

=item *

The parser, which loads a document tree for you.

You should access this through C<Pod::Abstract>, not directly

=item *

The document tree, which is the root node you are given by the
parser. Calling B<pod> on the root node should always give you back
your original document.

See L<Pod::Abstract::Node>

=item *

L<Pod::Abstract::Path>, the node selection expression language. This
is generally called by doing
C<< $node->select(PATH_EXP) >>. Pod::Abstract::Path is the most complex
and powerful component of this module, and if you're not using it you
should be. ;)

This allows you to ask questions like:

"In the first head1 that starts with "A", find me the head2 matching
'foo' with bold text somewhere in the preceding paragraph or heading"

 /head1[@heading=~{^A}](0)/head2[@heading=~{foo}i]<<head2 :paragraph[//:B]

You probably don't need anything that complex, but it's there if you
do.

=item *

The node builder, L<Pod::Abstract::BuildNode>

=back

=head1 METHODS

=cut

=head2 load_file

 my $pa = Pod::Abstract->load_file( FILENAME );

Read the POD document in the named file. Returns the root node of the
document.

=cut

sub load_file {
    my $class = shift;
    my $filename = shift;

    my $p = Pod::Abstract::Parser->new;
    $p->parse_from_file($filename);
    $p->root->coalesce_body(":verbatim");
    $p->root->coalesce_body(":text");
    $_->detach foreach $p->root->select('//:verbatim[ . =~ {^[\s]*$}]');
    return $p->root;
}

=head2 load_filehandle

 my $pa = Pod::Abstract->load_file( FH );

Load a POD document from the provided filehandle reference. Returns
the root node of the document.

=cut

sub load_filehandle {
    my $class = shift;
    my $fh = shift;

    my $p = Pod::Abstract::Parser->new;
    $p->parse_from_filehandle($fh);
    $p->root->coalesce_body(":verbatim");
    $p->root->coalesce_body(":text");
    $_->detach foreach $p->root->select('//:verbatim[ . =~ {^[\s]*$}]');
    return $p->root;
}

=head2 load_string

 my $pa = Pod::Abstract->load_string( STRING );

Loads a POD document from a scalar string value. Returns the root node
of the document.

=cut

sub load_string {
    my $class = shift;
    my $str = shift;

    my $fh = IO::String->new($str);
    return $class->load_filehandle($fh);
}

=head1 AUTHOR

Ben Lilburne <bnej@mac.com>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009 Ben Lilburne

This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;


text:
package nl.sense_os.commonsense.login.client.openidconnect;

import nl.sense_os.commonsense.common.client.communication.CommonSenseApi;
import nl.sense_os.commonsense.common.client.communication.SessionManager;
import nl.sense_os.commonsense.lib.client.model.httpresponse.LoginResponse;
import nl.sense_os.commonsense.login.client.LoginClientFactory;
import nl.sense_os.commonsense.login.client.login.LoginPlace;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

/**
 * Activities are started and stopped by an ActivityManager associated with a container Widget.
 */
public class OpenIdConnectActivity extends AbstractActivity implements OpenIdConnectView.Presenter {
	/**
	 * Used to obtain views, eventBus, placeController. Alternatively, could be injected via GIN.
	 */
	private LoginClientFactory clientFactory;

	private String email;

	public OpenIdConnectActivity(OpenIdConnectPlace place, LoginClientFactory clientFactory) {
		this.email = place.getEmail();
		this.clientFactory = clientFactory;
	}

	@Override
	public void cancel() {
		clientFactory.getPlaceController().goTo(new LoginPlace(""));
	}

	@Override
	public void connectAccount(String username, String password) {

		// log in to get session ID
		RequestCallback callback = new RequestCallback() {

			@Override
			public void onError(Request request, Throwable exception) {
				onLoginError(0, exception);
			}

			@Override
			public void onResponseReceived(Request request, Response response) {
				onLoginResponse(response);
			}
		};
		CommonSenseApi.login(callback, username, password);
	}

	/**
	 * Connects the current CommonSense user account with a Google account, for easy logging in with
	 * OpenID.
	 */
	private void googleConnect() {
		CommonSenseApi.googleConnect();
	}

	private void onAuthenticationFailure() {
		// TODO Auto-generated method stub

	}

	private void onLoginError(int code, Throwable error) {
		// TODO Auto-generated method stub

	}

	private void onLoginResponse(Response response) {
		final int statusCode = response.getStatusCode();
		if (Response.SC_OK == statusCode) {
			onLoginSuccess(response.getText());
		} else if (Response.SC_FORBIDDEN == statusCode) {
			onAuthenticationFailure();
		} else {
			onLoginError(statusCode, new Throwable(response.getStatusText()));
		}
	}

	private void onLoginSuccess(String response) {
		if (response != null) {

			// try to get "session_id" object
			String sessionId = null;
			LoginResponse jso = LoginResponse.create(response).cast();
			if (null != jso) {
				sessionId = jso.getSessionId();
			}

			if (null != sessionId) {
				SessionManager.setSessionId(sessionId);
				googleConnect();

			} else {
				onLoginError(0, new Exception("Did not receive session ID"));
			}

		} else {
			onLoginError(0, new Exception("No response content"));
		}

	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		OpenIdConnectView view = clientFactory.getOpenIdConnectView();
		view.setEmail(email);
		view.setPresenter(this);
		containerWidget.setWidget(view.asWidget());
	}
}


text:
from direct.gui.DirectGui import *
from direct.directnotify import DirectNotifyGlobal
import string
from otp.otpbase import OTPGlobals
from otp.otpbase import OTPLocalizer
NoButtons = 0
Acknowledge = 1
CancelOnly = 2
TwoChoice = 3
YesNo = 4
TwoChoiceCustom = 5

class OTPDialog(DirectDialog):

    def __init__(self, parent=None, style=NoButtons, **kw):
        if parent is None:
            parent = aspect2d
        self.style = style
        buttons = None
        if self.style != NoButtons:
            buttons = loader.loadModel(self.path)
        if self.style == TwoChoiceCustom:
            okImageList = (buttons.find('**/ChtBx_OKBtn_UP'), buttons.find('**/ChtBx_OKBtn_DN'), buttons.find('**/ChtBx_OKBtn_Rllvr'))
            cancelImageList = (buttons.find('**/CloseBtn_UP'), buttons.find('**/CloseBtn_DN'), buttons.find('**/CloseBtn_Rllvr'))
            buttonImage = [okImageList, cancelImageList]
            buttonValue = [DGG.DIALOG_OK, DGG.DIALOG_CANCEL]
            if 'buttonText' in kw:
                buttonText = kw['buttonText']
                del kw['buttonText']
            else:
                buttonText = [OTPLocalizer.DialogOK, OTPLocalizer.DialogCancel]
        elif self.style == TwoChoice:
            okImageList = (buttons.find('**/ChtBx_OKBtn_UP'), buttons.find('**/ChtBx_OKBtn_DN'), buttons.find('**/ChtBx_OKBtn_Rllvr'))
            cancelImageList = (buttons.find('**/CloseBtn_UP'), buttons.find('**/CloseBtn_DN'), buttons.find('**/CloseBtn_Rllvr'))
            buttonImage = [okImageList, cancelImageList]
            buttonText = [OTPLocalizer.DialogOK, OTPLocalizer.DialogCancel]
            buttonValue = [DGG.DIALOG_OK, DGG.DIALOG_CANCEL]
        elif self.style == YesNo:
            okImageList = (buttons.find('**/ChtBx_OKBtn_UP'), buttons.find('**/ChtBx_OKBtn_DN'), buttons.find('**/ChtBx_OKBtn_Rllvr'))
            cancelImageList = (buttons.find('**/CloseBtn_UP'), buttons.find('**/CloseBtn_DN'), buttons.find('**/CloseBtn_Rllvr'))
            buttonImage = [okImageList, cancelImageList]
            buttonText = [OTPLocalizer.DialogYes, OTPLocalizer.DialogNo]
            buttonValue = [DGG.DIALOG_OK, DGG.DIALOG_CANCEL]
        elif self.style == Acknowledge:
            okImageList = (buttons.find('**/ChtBx_OKBtn_UP'), buttons.find('**/ChtBx_OKBtn_DN'), buttons.find('**/ChtBx_OKBtn_Rllvr'))
            buttonImage = [okImageList]
            buttonText = [OTPLocalizer.DialogOK]
            buttonValue = [DGG.DIALOG_OK]
        elif self.style == CancelOnly:
            cancelImageList = (buttons.find('**/CloseBtn_UP'), buttons.find('**/CloseBtn_DN'), buttons.find('**/CloseBtn_Rllvr'))
            buttonImage = [cancelImageList]
            buttonText = [OTPLocalizer.DialogCancel]
            buttonValue = [DGG.DIALOG_CANCEL]
        elif self.style == NoButtons:
            buttonImage = []
            buttonText = []
            buttonValue = []
        else:
            self.notify.error('No such style as: ' + str(self.style))
        optiondefs = (('buttonImageList', buttonImage, DGG.INITOPT),
         ('buttonTextList', buttonText, DGG.INITOPT),
         ('buttonValueList', buttonValue, DGG.INITOPT),
         ('buttonPadSF', 2.2, DGG.INITOPT),
         ('text_font', DGG.getDefaultFont(), None),
         ('text_wordwrap', 12, None),
         ('text_scale', 0.07, None),
         ('buttonSize', (-.05, 0.05, -.05, 0.05), None),
         ('button_pad', (0, 0), None),
         ('button_relief', None, None),
         ('button_text_pos', (0, -0.1), None),
         ('fadeScreen', 0.5, None),
         ('image_color', OTPGlobals.GlobalDialogColor, None),
         ('image', DGG.getDefaultDialogGeom(), None),
         ('relief', None, None))
        self.defineoptions(kw, optiondefs)
        DirectDialog.__init__(self, parent)
        self.initialiseoptions(OTPDialog)
        if buttons is not None:
            buttons.removeNode()
        return

class GlobalDialog(OTPDialog):
    notify = DirectNotifyGlobal.directNotify.newCategory('GlobalDialog')

    def __init__(self, message='', doneEvent=None, style=NoButtons, okButtonText=OTPLocalizer.DialogOK,
                 cancelButtonText=OTPLocalizer.DialogCancel, **kw):

        if not hasattr(self, 'path'):
            self.path = 'phase_3/models/gui/dialog_box_buttons_gui'

        if doneEvent is None and style != NoButtons:
            self.notify.error('Boxes with buttons must specify a doneEvent.')

        self.__doneEvent = doneEvent

        if style == NoButtons:
            buttonText = []
        elif style == Acknowledge:
            buttonText = [okButtonText]
        elif style == CancelOnly:
            buttonText = [cancelButtonText]
        else:
            buttonText = [okButtonText, cancelButtonText]

        optiondefs = (
            ('dialogName', 'globalDialog', DGG.INITOPT),
            ('buttonTextList', buttonText, DGG.INITOPT),
            ('text', message, None),
            ('command', self.handleButton, None)
        )

        self.defineoptions(kw, optiondefs)
        OTPDialog.__init__(self, style=style)
        self.initialiseoptions(GlobalDialog)
        return

    def handleButton(self, value):
        if value == DGG.DIALOG_OK:
            self.doneStatus = 'ok'
            messenger.send(self.__doneEvent)
        elif value == DGG.DIALOG_CANCEL:
            self.doneStatus = 'cancel'
            messenger.send(self.__doneEvent)