text:
package com.newtifry.android.preferences;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;

import com.google.android.gcm.GCMRegistrar;
import com.newtifry.android.database.NewtifrySource;
import com.newtifry.android.remote.BackendRequest;
import com.newtifry.android.remote.BackendResponse;
import com.newtifry.android.utils.AppCompatPreferenceActivity;
import com.newtifry.android.MessageList;
import com.newtifry.android.Preferences;
import com.newtifry.android.R;
import com.newtifry.shared.NewtifryHelper;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.text.Html;
import android.view.MenuItem;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class SourceEditor2 extends AppCompatPreferenceActivity {
	private final SourceEditor2 thisActivity = this;
	private NewtifrySource source = null;
	public static SourceEditor2ORMPreferencesMapper preferenceMapper = null;
	CheckBoxPreference serverEnabled;
	Preference titlePreference;
	Preference sourceKey;
	Preference preferenceTest;
	Preference localEnablePreference;
	CheckBoxPreference localEnablePreferenceCheckBox;
	Preference sourceNotificationPreference;
	ListPreference sourceColorPreference;

	public class SourceEditor2ORMPreferencesMapper implements SharedPreferences
	{
		protected List<OnSharedPreferenceChangeListener> listeners = new LinkedList<OnSharedPreferenceChangeListener>();
		public SourceEditor2ORMPreferencesMapper() {
		}

		public NewtifrySource getSource() {
			return thisActivity.source;
		}
		public boolean contains( String key )
		{
			Map<String, ?> values = this.getAll();
			return values.containsKey(key);
		}

		public Editor edit()
		{
			return new Editor();
		}

		public Map<String, ?> getAll()
		{
			Map<String, Object> values = new HashMap<String, Object>();
			values.put(Preferences.SOURCE_SERVER, thisActivity.source.getServerEnabled());
			values.put(Preferences.SOURCE_LOCAL, thisActivity.source.getLocalEnabled());
			values.put(Preferences.SOURCE_NOTIFICATION, thisActivity.source.getNotification());
			values.put(Preferences.SOURCE_USE_NOTIFIER_PRO, thisActivity.source.getNotifierPro());
			values.put(Preferences.SOURCE_VIBRATE_NOTIFY, thisActivity.source.getVibrate());
			values.put(Preferences.SOURCE_LED_FLASH, thisActivity.source.getLedFlash());
			values.put(Preferences.SOURCE_SPEAK_MESSAGE, thisActivity.source.getSpeakMessage());
			values.put(Preferences.SOURCE_GLOBAL, thisActivity.source.getUseGlobalNotification());
			values.put(Preferences.SOURCE_RINGTONE, thisActivity.source.getRingtone());
			values.put(Preferences.SOURCE_TITLE, thisActivity.source.getTitle());
			values.put(Preferences.SOURCE_SOURCE_COLOR, thisActivity.source.getSourceColor());
			return values;
		}

		public boolean getBoolean( String key, boolean defValue )
		{
			// source_server_enable
			// source_local_enable
			// source_notification
			// source_usenotifierpro
			// source_ringtone
			// source_vibrate
			// source_ledflash
			// source_speakmessage
			if( key.equals(Preferences.SOURCE_SERVER) )
			{
				return thisActivity.source.getServerEnabled();
			}
			else if( key.equals(Preferences.SOURCE_LOCAL) )
			{
				return thisActivity.source.getLocalEnabled();
			}
			else if( key.equals(Preferences.SOURCE_NOTIFICATION) )
			{
				return thisActivity.source.getNotification();
			}
			else if( key.equals(Preferences.SOURCE_USE_NOTIFIER_PRO) )
			{
				return thisActivity.source.getNotifierPro();
			}
			else if( key.equals(Preferences.SOURCE_VIBRATE_NOTIFY) )
			{
				return thisActivity.source.getVibrate();
			}
			else if( key.equals(Preferences.SOURCE_LED_FLASH) )
			{
				return thisActivity.source.getLedFlash();
			}
			else if( key.equals(Preferences.SOURCE_SPEAK_MESSAGE) )
			{
				return thisActivity.source.getSpeakMessage();
			}
			else if( key.equals(Preferences.SOURCE_GLOBAL) )
			{
				return thisActivity.source.getUseGlobalNotification();
			}

			return false;
		}

		public float getFloat( String key, float defValue )
		{
			// No floats available.
			return 0;
		}

		public int getInt( String key, int defValue )
		{
			// No int's available.
			return 0;
		}

		public long getLong( String key, long defValue )
		{
			// No longs available.
			return 0;
		}

		public String getString( String key, String defValue )
		{
			// source_customringtone
			// source_title
			if( key.equals(Preferences.SOURCE_TITLE) )
			{
				return thisActivity.source.getTitle();
			}
			else if( key.equals(Preferences.SOURCE_RINGTONE) )
			{
				return thisActivity.source.getRingtone();
			}
			else if( key.equals(Preferences.SOURCE_SOURCE_COLOR) )
			{
				return thisActivity.source.getSourceColor();
			}

			return null;
		}

		public void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener )
		{
			this.listeners.add(listener);
		}

		public void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener )
		{
			this.listeners.remove(listener);
		}

		public class Editor implements SharedPreferences.Editor
		{

			public android.content.SharedPreferences.Editor clear()
			{
				// Not applicable for this object.
				return null;
			}

			public boolean commit()
			{
				thisActivity.source.save(thisActivity);
				return true;
			}

			public android.content.SharedPreferences.Editor putBoolean( String key, boolean value )
			{
				// NOTE: This is not transactionally safe as it modifies the parent's object.
				// source_server_enable
				// source_local_enable
				// source_notification
				// source_usenotifierpro
				// source_ringtone
				// source_vibrate
				// source_ledflash
				// source_speakmessage
				// source_global
				if( key.equals(Preferences.SOURCE_SERVER) )
				{
					thisActivity.source.setServerEnabled(value);
				}
				else if( key.equals(Preferences.SOURCE_LOCAL) )
				{
					thisActivity.source.setLocalEnabled(value);
				}
				else if( key.equals(Preferences.SOURCE_NOTIFICATION) )
				{
					thisActivity.source.setNotification(value);
				}
				else if( key.equals(Preferences.SOURCE_USE_NOTIFIER_PRO) )
				{
					thisActivity.source.setNotifierPro(value);
				}
				else if( key.equals(Preferences.SOURCE_VIBRATE_NOTIFY) )
				{
					thisActivity.source.setVibrate(value);
				}
				else if( key.equals(Preferences.SOURCE_LED_FLASH) )
				{
					thisActivity.source.setLedFlash(value);
				}
				else if( key.equals(Preferences.SOURCE_SPEAK_MESSAGE) )
				{
					thisActivity.source.setSpeakMessage(value);
				}
				else if( key.equals(Preferences.SOURCE_GLOBAL) )
				{
					thisActivity.source.setUseGlobalNotification(value);
				}

				return this;
			}

			public android.content.SharedPreferences.Editor putFloat( String key, float value )
			{
				// No floats to set.
				return this;
			}

			public android.content.SharedPreferences.Editor putInt( String key, int value )
			{
				// No ints to set.
				return this;
			}

			public android.content.SharedPreferences.Editor putLong( String key, long value )
			{
				// No longs to set.
				return this;
			}

			public android.content.SharedPreferences.Editor putString( String key, String value )
			{
				// NOTE: This is not transactionally safe as it modifies the parent's object.
				// source_customringtone
				// source_title
				if( key.equals(Preferences.SOURCE_TITLE) )
				{
					thisActivity.source.setTitle(value);
				}
				else if( key.equals(Preferences.SOURCE_RINGTONE) )
				{
					thisActivity.source.setRingtone(value);
				}
				else if( key.equals(Preferences.SOURCE_SOURCE_COLOR) )
				{
					thisActivity.source.setSourceColor(value);
				}

				return this;
			}

			public android.content.SharedPreferences.Editor remove( String key )
			{
				// Nothing to do here - this doesn't make sense.
				return this;
			}

			public void apply()
			{
				thisActivity.source.save(thisActivity);
			}

			public android.content.SharedPreferences.Editor putStringSet( String arg0, Set<String> arg1 )
			{
				// TODO Auto-generated method stub
				return null;
			}
		}

		public Set<String> getStringSet( String arg0, Set<String> arg1 )
		{
			// TODO Auto-generated method stub
			return null;
		}
	}

	public SharedPreferences getSharedPreferences(String name, int mode)
	{
		return SourceEditor2.preferenceMapper;
	}

	/** Called when the activity is first created. */
	public void onCreate( Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getSource();
		SourceEditor2.preferenceMapper = new SourceEditor2ORMPreferencesMapper();

		this.addPreferencesFromResource(R.xml.source_preference_editor2);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		// Find and attach the onclick handlers.
		titlePreference = this.findPreference(Preferences.SOURCE_TITLE);
		titlePreference.setOnPreferenceChangeListener(immediateServerChangeListener);

		Preference serverEnabledPreference = this.findPreference(Preferences.SOURCE_SERVER);
		serverEnabledPreference.setOnPreferenceChangeListener(immediateServerChangeListener);
		serverEnabled = (CheckBoxPreference) serverEnabledPreference;

		localEnablePreference = this.findPreference(Preferences.SOURCE_LOCAL);
		localEnablePreference.setOnPreferenceChangeListener(localEnablePreferenceCheckListener);
		localEnablePreferenceCheckBox = (CheckBoxPreference)localEnablePreference;

		sourceKey = this.findPreference(Preferences.SOURCE_KEY);

		preferenceTest = this.findPreference(Preferences.SOURCE_TEST);
		preferenceTest.setOnPreferenceClickListener(testClickHandler);

		sourceColorPreference = (ListPreference)this.findPreference(Preferences.SOURCE_SOURCE_COLOR);
		sourceColorPreference.setOnPreferenceChangeListener(sourceColorChangeListener);

		sourceNotificationPreference = thisActivity.findPreference(Preferences.SOURCE_NOTIFICATION_SETTINGS);

		Preference sourceEmailKeyPreference = this.findPreference(Preferences.SOURCE_EMAIL);
		sourceEmailKeyPreference.setOnPreferenceClickListener(emailClickHandler);

		Preference messagesPreference = this.findPreference(Preferences.SOURCE_MESSAGES);
		messagesPreference.setOnPreferenceClickListener(messagesClickHandler);

		Preference deletePreference = this.findPreference(Preferences.SOURCE_DELETE);
		deletePreference.setOnPreferenceClickListener(deleteClickHandler);

	}

	OnPreferenceChangeListener sourceColorChangeListener = new OnPreferenceChangeListener()	{
		public boolean onPreferenceChange( Preference preference, Object newValue )	{
			updateSourcecolor((String)newValue);
			return true;
		}
	};

	@SuppressLint("NewApi")
	public void updateSourcecolor(String value) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
			if (value.equals("default")) {
				sourceColorPreference.setSummary(getString(R.string.froyo_color_summary));

			} else {
				String hexColor = Integer.toHexString(Color.parseColor(value));
				String html = "" + getString(R.string.froyo_color_summary) + "";
				sourceColorPreference.setSummary(Html.fromHtml(html));
			}
			return;
		}

		String uri = "drawable/icon_color_" + value;
	    int imageResource = getResources().getIdentifier(uri, null, getPackageName());
	    Drawable icon = getResources().getDrawable(imageResource);
	    sourceColorPreference.setIcon(icon);
	}
	public void onConfigurationChanged( Configuration newConfig )
	{
		super.onConfigurationChanged(newConfig);
	}

	public void onResume()
	{
		super.onResume();

		// Reload our source data.
		this.source = null;
		// And finally, update the screen.
		this.loadFromSource(this.getSource());
	}

	public void onPause()
	{
		super.onPause();
	}

	/**
	 * Load this activity from the given source.
	 * @param source
	 */
	public void loadFromSource( NewtifrySource source )
	{

		// Create a new preferences mapper with updated source data.
		SourceEditor2.preferenceMapper = new SourceEditor2ORMPreferencesMapper();

		titlePreference.setSummary(source.getTitle());
		sourceKey.setSummary(source.getSourceKey());
		// Force update the server enabled preference.
		serverEnabled.setChecked(source.getServerEnabled());
//		sourceColorPreference.setValue(source.getSourceColor());
		updateSourcecolor(source.getSourceColor());

		this.toggleLocalEnablePreferences(source.getLocalEnabled());
		this.toggleServerEnable(source.getServerEnabled());
	}

	/**
	 * Save this source.
	 */
/*
	public void save( View view )
	{
		// User clicked save button.
		// Prepare the new local object.
		SourceEditor2.source = null;
		NewtifrySource source = this.getSource();

		EditText title = (EditText) findViewById(R.id.detail_title);
		source.setTitle(title.getText().toString());

		CheckBox serverEnable = (CheckBox) findViewById(R.id.detail_serverenable);
		source.setServerEnabled(serverEnable.isChecked());
		CheckBox localEnable = (CheckBox) findViewById(R.id.detail_localenable);
		source.setLocalEnabled(localEnable.isChecked());

		// Now, send the updates to the server. On success, save the changes locally.
		BackendRequest request = new BackendRequest("/sources/edit");
		request.add("id", source.getServerId().toString());
		request.add("title", source.getTitle());
		if( source.getServerEnabled() )
		{
			request.add("enabled", "on");
		}

		request.addMeta("source", source);
		request.addMeta("operation", "save");

		request.setHandler(handler);

		request.startInThread(this, getString(R.string.source_saving_to_server), source.getAccountName());
	}
*/

			// Crude: determine what thing we changed based on the object's t
	/**
	 * A listener for changes that must occur immediately on the server.
	 */
	OnPreferenceChangeListener immediateServerChangeListener = new OnPreferenceChangeListener()
	{
		public boolean onPreferenceChange( Preference preference, Object newValue )
		{
			// Crude: determine what thing we changed based on the object's type.
			// CAUTION: This won't work if we need to send more than a string or boolean to the server.
			BackendRequest request = new BackendRequest("/sources/edit");
			request.add("id", thisActivity.getSource().getServerId().toString());

			if( newValue instanceof String )
			{
				// Set the title.
				request.add("title", (String) newValue);
				if( thisActivity.getSource().getServerEnabled() )
				{
					request.add("enabled", "on");
				}
			}
			else if( newValue instanceof Boolean )
			{
				request.add("title", thisActivity.getSource().getTitle());
				// Set the server enabled value.
				Boolean boolValue = (Boolean) newValue;
				if( boolValue )
				{
					request.add("enabled", "on");
				}
			}

			request.addMeta("source", thisActivity.getSource());
			request.addMeta("operation", "save");

			request.setHandler(handler);

			request.startInThread(thisActivity, getString(R.string.source_saving_to_server), thisActivity.getSource().getAccountName());

			// Prevent the change from occuring here.
			return false;
		}
	};

	/**
	 * Toggle the server source enabled.
	 */
	public void toggleServerEnable( boolean serverEnabled ) {
		// if enable enable only source and test
		// if disable : disable all
		localEnablePreference.setEnabled(serverEnabled);
		if (serverEnabled && !localEnablePreferenceCheckBox.isChecked()) {
			serverEnabled = false;
		}
		sourceNotificationPreference.setEnabled(serverEnabled);
		preferenceTest.setEnabled(serverEnabled);
	}

	/**
	 * Toggle the local source enabled.
	 */
	OnPreferenceChangeListener localEnablePreferenceCheckListener = new OnPreferenceChangeListener()
	{
		public boolean onPreferenceChange( Preference preference, Object newValue )
		{
			thisActivity.toggleLocalEnablePreferences((Boolean)newValue);
			return true;
		}
	};

	public void toggleLocalEnablePreferences( boolean localEnabled ) {
		sourceNotificationPreference.setEnabled(localEnabled);
		preferenceTest.setEnabled(localEnabled);
	}

	/**
	 * Delete this source.
	 */
	OnPreferenceClickListener deleteClickHandler = new OnPreferenceClickListener()
	{
		public boolean onPreferenceClick(Preference preference)
		{
			// User clicked delete button.
			// Confirm that's what they want.
			new AlertDialog.Builder(thisActivity).
				setTitle(getString(R.string.delete_source)).
				setMessage(getString(R.string.delete_source_message)).
				setPositiveButton(
						getString(R.string.delete),
						new DialogInterface.OnClickListener()
						{
							public void onClick( DialogInterface dialog, int whichButton )
							{
								// Fire it off to the delete source function.
								deleteSource(thisActivity.getSource());
							}
						}).
				setNegativeButton(
						getString(R.string.cancel),
						new DialogInterface.OnClickListener()
						{
							public void onClick( DialogInterface dialog, int whichButton )
							{
								// No need to take any action.
									}
								}).
						show();

			return true;
		}
	};

	/**
	 * Send a request to the backend to delete the source.
	 * @param source
	 */
	public void deleteSource( NewtifrySource source )
	{
		// Now, send the updates to the server. On success, save the changes locally.
		BackendRequest request = new BackendRequest("/sources/delete");
		request.add("id", source.getServerId().toString());
		request.addMeta("operation", "delete");
		request.addMeta("source", getSource());
		request.setHandler(handler);

		request.startInThread(this, getString(R.string.source_deleting_from_server), source.getAccountName());
	}

	/**
	 * Send a request to the backend to test this source.
	 * @param view
	 */
	OnPreferenceClickListener testClickHandler = new OnPreferenceClickListener()
	{
		public boolean onPreferenceClick(Preference preference)
		{
			BackendRequest request = new BackendRequest("/sources/test");
			request.add("id", getSource().getServerId().toString());
			request.addMeta("operation", "test");
			// v2.3.2
			request.add("deviceid", GCMRegistrar.getRegistrationId(thisActivity.getApplicationContext()));
			request.add("language", Locale.getDefault().getDisplayLanguage(Locale.US));
			request.addMeta("source", getSource());
			request.setHandler(handler);
			request.startInThread(thisActivity, getString(R.string.source_testing_with_server), source.getAccountName());
			return true;
		}
	};

	/**
	 * Email the source key to someone.
	 */
	OnPreferenceClickListener emailClickHandler = new OnPreferenceClickListener()
	{
		public boolean onPreferenceClick(Preference preference)
		{
			// User wants to email the key to someone.
			final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
			emailIntent.setType("plain/text");
			emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.source_key_email_subject));
			emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, String.format(getString(R.string.source_key_email_body), getSource().getSourceKey()));
			thisActivity.startActivity(Intent.createChooser(emailIntent, "Send key via email"));

			return true;
		}
	};

	/**
	 * View the messages of this source.
	 */
	OnPreferenceClickListener messagesClickHandler = new OnPreferenceClickListener()
	{
		public boolean onPreferenceClick(Preference preference)
		{
			Intent intent = new Intent(thisActivity, MessageList.class);
			intent.putExtra(NewtifryHelper.IntentExtras.SOURCE, thisActivity.getSource().getId());
			startActivity(intent);
			return true;
		}
	};

	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage( Message msg )
		{
			// Fetch out the response.
			BackendResponse response = (BackendResponse) msg.obj;

			// Was it successful?
			if( response.isError() )
			{
				// No, not successful.
				Toast.makeText(thisActivity, response.getError() + getString(R.string.try_again), Toast.LENGTH_LONG).show();
			}
			else
			{
				try
				{
					// Fetch out metadata.
					BackendRequest request = response.getRequest();
					NewtifrySource source = (NewtifrySource) request.getMeta("source");

					String operation = (String) request.getMeta("operation");

					if( operation.equals("save") )
					{
						// Load the source from the server information. We assume the server is correct.
						source.fromJSONObject(response.getJSON().getJSONObject("source"));

						// Save it to the database.
						source.save(thisActivity);

						Toast.makeText(thisActivity, getString(R.string.source_save_success), Toast.LENGTH_SHORT).show();

						// Reload the parent activity.
						thisActivity.source = null;
						thisActivity.loadFromSource(thisActivity.getSource());
					}
					else if( operation.equals("delete") )
					{
						// Delete from local.
						source.delete(thisActivity);

						// Let the user know we're done.
						Toast.makeText(thisActivity, getString(R.string.source_delete_success), Toast.LENGTH_SHORT).show();

						// And exit this activity.
						thisActivity.finish();
					}
					else if( operation.equals("test") )
					{
						// The server has been asked to test us.
						Toast.makeText(thisActivity, getString(R.string.source_test_success), Toast.LENGTH_SHORT).show();
					}
				}
				catch( JSONException e )
				{
					// The response doesn't look like we expected.
//					Log.d(TAG, "Invalid response from server: " + e.getMessage());
					Toast.makeText(thisActivity, getString(R.string.server_invalid_response), Toast.LENGTH_LONG).show();
				}
			}
		}
	};

	/**
	 * Fetch the account that this source list is for.
	 *
	 * @return
	 */
	public NewtifrySource getSource()
	{
		if( this.source == null )
		{
			// Get the source from the intent.
			// We store it in a private variable to save us having to query the
			// DB each time.
			Intent sourceIntent = getIntent();
			this.source = NewtifrySource.FACTORY.get(this, sourceIntent.getLongExtra(NewtifryHelper.IntentExtras.SOURCE, 0));
		}

		return this.source;
	}

	/**
	 * When the home button is hit...
	 */
	public boolean onOptionsItemSelected( MenuItem item )
	{
		switch( item.getItemId() )
		{
			case android.R.id.home:
				onBackPressed();
	            return true;
		}

		return super.onOptionsItemSelected((android.view.MenuItem) item);
	}
}


text:
This is my first gem. hop you enjoy it

## Installation

Add this line to your application's Gemfile:

    gem 'laurem'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install laurem

## Usage

Laurem.get_time #suprise

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

redpajama_set_name: RedPajamaGithub


text:
"""Extenders of tf.estimator.Estimator."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import six

from tensorflow.python.estimator import estimator as estimator_lib
from tensorflow.python.estimator import model_fn as model_fn_lib
from tensorflow.python.estimator import util as estimator_util
from tensorflow.python.estimator.export.export_output import PredictOutput
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor as sparse_tensor_lib
from tensorflow.python.ops import clip_ops
from tensorflow.python.training import optimizer as optimizer_lib

_VALID_METRIC_FN_ARGS = set(['features', 'labels', 'predictions', 'config'])

def add_metrics(estimator, metric_fn):
  """Creates a new @{tf.estimator.Estimator} which has given metrics.

  Example:

  ```python
    def my_auc(labels, predictions):
      return {'auc': tf.metrics.auc(labels, predictions['logistic'])}

    estimator = tf.estimator.DNNClassifier(...)
    estimator = tf.contrib.estimator.add_metrics(estimator, my_auc)
    estimator.train(...)
    estimator.evaluate(...)
  ```
  Example usage of custom metric which uses features:

  ```python
    def my_auc(features, labels, predictions):
      return {'auc': tf.metrics.auc(
        labels, predictions['logistic'], weights=features['weight'])}

    estimator = tf.estimator.DNNClassifier(...)
    estimator = tf.contrib.estimator.add_metrics(estimator, my_auc)
    estimator.train(...)
    estimator.evaluate(...)
  ```

  Args:
    estimator: A @{tf.estimator.Estimator} object.
    metric_fn: A function which should obey the following signature:
      - Args: can only have following four arguments in any order:
        * predictions: Predictions `Tensor` or dict of `Tensor` created by given
          `estimator`.
        * features: Input `dict` of `Tensor` objects created by `input_fn` which
          is given to `estimator.evaluate` as an argument.
        * labels:  Labels `Tensor` or dict of `Tensor` created by `input_fn`
          which is given to `estimator.evaluate` as an argument.
        * config: config attribute of the `estimator`.
       - Returns:
         Dict of metric results keyed by name. Final metrics are a union of this
         and `estimator's` existing metrics. If there is a name conflict between
         this and `estimator`s existing metrics, this will override the existing
         one. The values of the dict are the results of calling a metric
         function, namely a `(metric_tensor, update_op)` tuple.

  Returns:
      A new @{tf.estimator.Estimator} which has a union of original metrics with
        given ones.
  """
  _verify_metric_fn_args(metric_fn)

  def new_model_fn(features, labels, mode, config):
    spec = estimator.model_fn(features, labels, mode, config)
    if mode != model_fn_lib.ModeKeys.EVAL:
      return spec
    new_metrics = _call_metric_fn(metric_fn, features, labels, spec.predictions,
                                  config)
    all_metrics = spec.eval_metric_ops or {}
    all_metrics.update(new_metrics)
    return spec._replace(eval_metric_ops=all_metrics)

  return estimator_lib.Estimator(
      model_fn=new_model_fn,
      model_dir=estimator.model_dir,
      config=estimator.config,
      # pylint: disable=protected-access
      warm_start_from=estimator._warm_start_settings)
      # pylint: enable=protected-access

def clip_gradients_by_norm(optimizer, clip_norm):
  """Returns an optimizer which clips gradients before applying them.

  Example:

  ```python
  optimizer = tf.train.ProximalAdagradOptimizer(
      learning_rate=0.1,
      l1_regularization_strength=0.001)
  optimizer = tf.contrib.estimator.clip_gradients_by_norm(
      optimizer, clip_norm)
  estimator = tf.estimator.DNNClassifier(
      feature_columns=[...],
      hidden_units=[1024, 512, 256],
      optimizer=optimizer)
  ```

  Args:
    optimizer: An `tf.Optimizer` object to apply gradients.
    clip_norm: A 0-D (scalar) `Tensor` > 0. The clipping ratio.

  Returns:
    A `tf.Optimizer`.
  """

  def clip_grads(grads_and_vars):
    gradients, variables = zip(*grads_and_vars)
    gradients = clip_ops.clip_by_global_norm(gradients, clip_norm)[0]
    grads_and_vars = list(zip(gradients, variables))
    return grads_and_vars

  return _TransformGradients(
      optimizer=optimizer,
      transform_grads_fn=clip_grads,
      name='ClipByNorm' + optimizer.get_name())

def forward_features(estimator, keys=None):
  """Forward features to predictions dictionary.

  In some cases, user wants to see some of the features in estimators prediction
  output. As an example, consider a batch prediction service: The service simply
  runs inference on the users graph and returns the results. Keys are essential
  because there is no order guarantee on the outputs so they need to be rejoined
  to the inputs via keys or transclusion of the inputs in the outputs.

  Example:

  ```python
    def input_fn():
      features, labels = ...
      features['unique_example_id'] = ...
      features, labels

    estimator = tf.estimator.LinearClassifier(...)
    estimator = tf.contrib.estimator.forward_features(
        estimator, 'unique_example_id')
    estimator.train(...)
    assert 'unique_example_id' in estimator.predict(...)
  ```

  Args:
    estimator: A @{tf.estimator.Estimator} object.
    keys: a `string` or a `list` of `string`. If it is `None`, all of the
      `features` in `dict` is forwarded to the `predictions`. If it is a
      `string`, only given key is forwarded. If it is a `list` of strings, all
      the given `keys` are forwarded.

  Returns:
      A new @{tf.estimator.Estimator} which forwards features to predictions.

  Raises:
    ValueError:
      * if `keys` is already part of `predictions`. We don't allow
        override.
      * if 'keys' does not exist in `features`.
      * if feature key refers to a `SparseTensor`, since we don't support
        `SparseTensor` in `predictions`. `SparseTensor` is common in `features`.
    TypeError: if `keys` type is not one of `string` or list/tuple of `string`.
  """

  def verify_key_types(keys):  # pylint: disable=missing-docstring
    if keys is None:
      return keys
    if isinstance(keys, six.string_types):
      return [keys]
    if not isinstance(keys, (list, tuple)):
      raise TypeError('keys should be either a string or a list of strings. '
                      'Given: {}'.format(type(keys)))
    for key in keys:
      if not isinstance(key, six.string_types):
        raise TypeError('All items in the given keys list should be a string. '
                        'There exist an item with type: {}'.format(type(key)))
    return keys

  def get_keys(features):
    if keys is None:
      return features.keys()
    return keys

  def verify_keys_and_predictions(features, predictions):
    if not isinstance(predictions, dict):
      raise ValueError(
          'Predictions should be a dict to be able to forward features. '
          'Given: {}'.format(type(predictions)))
    for key in get_keys(features):
      if key not in features:
        raise ValueError(
            'keys should be exist in features. Key "{}" is not in features '
            'dict. features dict has following keys: {}. Please check '
            'arguments of forward_features.'.format(key, features.keys()))
      if key in predictions:
        raise ValueError(
            'Cannot forward feature key ({}). Since it does exist in '
            'predictions. Existing prediction keys: {}. Please check arguments '
            'of forward_features.'.format(key, predictions.keys()))

  keys = verify_key_types(keys)

  def new_model_fn(features, labels, mode, config):  # pylint: disable=missing-docstring
    spec = estimator.model_fn(features, labels, mode, config)
    predictions = spec.predictions
    if predictions is None:
      return spec
    verify_keys_and_predictions(features, predictions)
    for key in get_keys(features):
      feature = sparse_tensor_lib.convert_to_tensor_or_sparse_tensor(
          features[key])
      if not isinstance(feature, ops.Tensor):
        raise ValueError(
            'Forwarded feature ({}) should be a Tensor. Please use keys '
            'argument of forward_features to filter unwanted features. Type of '
            'features[{}] is {}.'.format(key, key, type(feature)))
      predictions[key] = feature
    spec = spec._replace(predictions=predictions)
    if spec.export_outputs:
      for ekey in ['predict', 'serving_default']:
        if (ekey in spec.export_outputs and
            isinstance(spec.export_outputs[ekey],
                       PredictOutput)):
          export_outputs = spec.export_outputs[ekey].outputs
          for key in get_keys(features):
            export_outputs[key] = predictions[key]

    return spec

  return estimator_lib.Estimator(
      model_fn=new_model_fn,
      model_dir=estimator.model_dir,
      config=estimator.config)

class _TransformGradients(optimizer_lib.Optimizer):
  """Add given gradient transformation to the optimizer."""

  def __init__(self, optimizer, transform_grads_fn, name=None):
    """Construct an `tf.Optimizer` wrapper to apply given transformations.

    Example:

    ```python
    optimizer = tf.train.ProximalAdagradOptimizer(
        learning_rate=0.1,
        l1_regularization_strength=0.001)
    def clip_grads(grads_and_vars):
      gradients, variables = zip(*grads_and_vars)
      gradients = tf.clip_by_global_norm(grads, my_norm)[0]
      grads_and_vars = list(zip(gradients, variables))
      return grads_and_vars
    optimizer = _TransformGradients(
        opt=optimizer, transform_grads_fn=clip_grads)
    estimator = tf.estimator.DNNClassifier(
        feature_columns=[...],
        hidden_units=[1024, 512, 256],
        optimizer=optimizer)
    ```

    Args:
      optimizer: An `tf.Optimizer` object to apply gradients.
      transform_grads_fn: A function which takes a single argument, a list of
        gradient to variable pairs (tuples), performs any requested gradient
        updates, such as gradient clipping or multipliers, and returns the
        updated list.
      name: A string which will be used for debugging purposes.
    """
    super(_TransformGradients, self).__init__(
        use_locking=False, name=name or optimizer.get_name())
    self._optimizer = optimizer
    self._transform_grads_fn = transform_grads_fn

  def compute_gradients(self, *args, **kwargs):
    """See `tf.Optimizer`."""
    return self._optimizer.compute_gradients(*args, **kwargs)

  def apply_gradients(self, grads_and_vars, global_step=None, name=None):
    """Apply gradients to variables.

    Calls `transform_grads_fn`, and then applies the real optimizer.

    Args:
      grads_and_vars: List of (gradient, variable) pairs as returned by
        compute_gradients().
      global_step: Optional Variable to increment by one after the
        variables have been updated.
      name: Optional name for the returned operation.  Default to the
        name passed to the Optimizer constructor.

    Returns:
      An `Operation` that applies the gradients. If `global_step` was not None,
      that operation also increments `global_step`.

    Raises:
      ValueError: If the grads_and_vars is malformed.
    """
    grads_and_vars = self._transform_grads_fn(grads_and_vars)
    return self._optimizer.apply_gradients(grads_and_vars, global_step, name)

  def get_slot(self, *args, **kwargs):
    """See `tf.Optimizer`."""
    return self._optimizer.get_slot(*args, **kwargs)

  def get_slot_names(self, *args, **kwargs):
    """See `tf.Optimizer`."""
    return self._optimizer.get_slot_names(*args, **kwargs)

def _verify_metric_fn_args(metric_fn):
  args = set(estimator_util.fn_args(metric_fn))
  invalid_args = list(args - _VALID_METRIC_FN_ARGS)
  if invalid_args:
    raise ValueError('metric_fn (%s) has following not expected args: %s' %
                     (metric_fn, invalid_args))

def _call_metric_fn(metric_fn, features, labels, predictions, config):
  """Calls metric fn with proper arguments."""
  metric_fn_args = estimator_util.fn_args(metric_fn)
  kwargs = {}
  if 'features' in metric_fn_args:
    kwargs['features'] = features
  if 'labels' in metric_fn_args:
    kwargs['labels'] = labels
  if 'predictions' in metric_fn_args:
    kwargs['predictions'] = predictions
  if 'config' in metric_fn_args:
    kwargs['config'] = config
  return metric_fn(**kwargs)


text:
package com.gitblit.sysinfo;

import javax.management.Attribute;
import javax.management.InstanceNotFoundException;
import javax.management.JMException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * This code was extracted from JavaMelody and refactored.
 *
 * @author Emeric Vernat
 * @author James Moger
 */

public final class MBeansMonitor {

    private static final String JAVA_LANG_MBEAN_DESCRIPTION = "Information on the management interface of the MBean";
    private static final Comparator<MBeanNode> NODE_COMPARATOR = (o1, o2) -> o1.getName() != null ? o1.getName().compareTo(o2.getName()) : 0;
    private static final Comparator<MBeanNode.MBeanAttribute> ATTRIBUTE_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
    private final MBeanServer mbeanServer;

    public MBeansMonitor() {
        this(ManagementFactory.getPlatformMBeanServer());
    }

    private MBeansMonitor(MBeanServer mbeanServer) {
        super();
        this.mbeanServer = mbeanServer;
    }

    Object getAttribute(ObjectName name, String attribute) throws JMException {
        return mbeanServer.getAttribute(name, attribute);
    }

    public List<MBeanNode> getAllMBeanNodes() throws JMException {
        initJRockitMBeansIfNeeded();

        List<MBeanNode> result = new ArrayList<>();
        MBeanServer platformMBeanServer = mbeanServer;
        MBeanNode platformNode = new MBeanNode("");
        MBeansMonitor platformMBeansMonitor = new MBeansMonitor();
        platformNode.getChildren().addAll(platformMBeansMonitor.getMBeanNodes());
        result.add(platformNode);

        for (MBeanServer mbeanServer : getMBeanServers()) {
            if (!mbeanServer.equals(platformMBeanServer)) {
                MBeanNode node = new MBeanNode(mbeanServer.getDefaultDomain());
                MBeansMonitor mbeans = new MBeansMonitor(mbeanServer);
                node.getChildren().addAll(mbeans.getMBeanNodes());
                result.add(node);
            }
        }
        return result;
    }

    private void initJRockitMBeansIfNeeded() {
        if (System.getProperty("java.vendor").contains("BEA")) {
            try {
                // http://blogs.oracle.com/hirt/jrockit/
                try {
                    mbeanServer.getMBeanInfo(new ObjectName("bea.jrockit.management:type=JRockitConsole"));
                } catch (InstanceNotFoundException e1) {
                    mbeanServer.createMBean("bea.jrockit.management.JRockitConsole", null);
                }
            } catch (JMException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    private List<MBeanNode> getMBeanNodes() throws JMException {
        List<MBeanNode> result = new ArrayList<>();
        Set<ObjectName> names = mbeanServer.queryNames(null, null);
        for (ObjectName name : names) {
            String domain = name.getDomain();
            if ("jboss.deployment".equals(domain)) {
                continue;
            }
            MBeanNode domainNode = getMBeanNodeFromList(result, domain);
            if (domainNode == null) {
                domainNode = new MBeanNode(domain);
                result.add(domainNode);
            }
            String keyPropertyListString = name.getKeyPropertyListString();
            String firstPropertyValue;
            int indexOf = keyPropertyListString.indexOf('=');
            if (indexOf == -1) {
                firstPropertyValue = null;
            } else {
                firstPropertyValue = name.getKeyProperty(keyPropertyListString
                        .substring(0, indexOf));
            }
            if ("Servlet".equals(firstPropertyValue) && "jonas".equals(domain)) {
                continue;
            }
            MBeanNode firstPropertyNode = getMBeanNodeFromList(domainNode.getChildren(),
                    firstPropertyValue);
            if (firstPropertyNode == null) {
                firstPropertyNode = new MBeanNode(firstPropertyValue);
                domainNode.getChildren().add(firstPropertyNode);
            }
            final MBeanNode mbean = getMBeanNode(name);
            firstPropertyNode.getChildren().add(mbean);
        }
        sortMBeanNodes(result);
        return result;
    }

    private void sortMBeanNodes(List<MBeanNode> nodes) {
        if (nodes.size() > 1) {
            Collections.sort(nodes, NODE_COMPARATOR);
        }

        for (MBeanNode node : nodes) {
            List<MBeanNode> children = node.getChildren();
            if (children != null) {
                sortMBeanNodes(children);
            }
            List<MBeanNode.MBeanAttribute> attributes = node.getAttributes();
            if (attributes != null && attributes.size() > 1) {
                Collections.sort(attributes, ATTRIBUTE_COMPARATOR);
            }
        }
    }

    private MBeanNode getMBeanNodeFromList(List<MBeanNode> list, String name) {
        for (MBeanNode node : list) {
            if (node.getName().equals(name)) {
                return node;
            }
        }
        return null;
    }

    private MBeanNode getMBeanNode(ObjectName name) throws JMException {
        String mbeanName = name.toString();
        MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(name);
        String description = formatDescription(mbeanInfo.getDescription());
        MBeanAttributeInfo[] attributeInfos = mbeanInfo.getAttributes();
        List<MBeanNode.MBeanAttribute> attributes = getAttributes(name, attributeInfos);
        return new MBeanNode(mbeanName, description, attributes);
    }

    private List<MBeanNode.MBeanAttribute> getAttributes(ObjectName name, MBeanAttributeInfo[] attributeInfos) {
        List<String> attributeNames = new ArrayList<>(attributeInfos.length);
        for (MBeanAttributeInfo attribute : attributeInfos) {
            if (attribute.isReadable() && !"password".equalsIgnoreCase(attribute.getName())) {
                attributeNames.add(attribute.getName());
            }
        }
        String[] attributeNamesArray = attributeNames.toArray(new String[attributeNames.size()]);
        List<MBeanNode.MBeanAttribute> result = new ArrayList<>();
        try {
            List<Object> attributes = mbeanServer.getAttributes(name, attributeNamesArray);
            for (Object object : attributes) {
                Attribute attribute = (Attribute) object;
                Object value = convertValueIfNeeded(attribute.getValue());
                String attributeDescription = getAttributeDescription(attribute.getName(), attributeInfos);
                String formattedAttributeValue = formatAttributeValue(value);
                MBeanNode.MBeanAttribute mbeanAttribute = new MBeanNode.MBeanAttribute(attribute.getName(),
                        attributeDescription, formattedAttributeValue);
                result.add(mbeanAttribute);
            }
        } catch (Exception e) {
            MBeanNode.MBeanAttribute mbeanAttribute = new MBeanNode.MBeanAttribute("exception", null, e.toString());
            result.add(mbeanAttribute);
        }
        return result;
    }

    private String formatAttributeValue(Object attributeValue) {
        try {
            if (attributeValue instanceof List) {
                StringBuilder sb = new StringBuilder();
                sb.append('[');
                boolean first = true;
                for (Object value : (List<?>) attributeValue) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append(",\n");
                    }
                    sb.append(String.valueOf(value));
                }
                sb.append(']');
                return sb.toString();
            }
            return String.valueOf(attributeValue);
        } catch (Exception e) {
            return e.toString();
        }
    }

    private String formatDescription(String description) {
        if (description == null || JAVA_LANG_MBEAN_DESCRIPTION.equals(description)) {
            return null;
        }
        int indexOf = description.indexOf("  ");
        if (indexOf != -1) {
            StringBuilder sb = new StringBuilder(description);
            while (indexOf != -1) {
                sb.deleteCharAt(indexOf);
                indexOf = sb.indexOf("  ");
            }
            return sb.toString();
        }
        return description;
    }

    private Object convertValueIfNeeded(Object value) {
        if (value instanceof CompositeData) {
            CompositeData data = (CompositeData) value;
            Map<String, Object> values = new TreeMap<>();
            for (String key : data.getCompositeType().keySet()) {
                values.put(key, convertValueIfNeeded(data.get(key)));
            }
            return values;
        } else if (value instanceof CompositeData[]) {
            List<Object> list = new ArrayList<>();
            for (CompositeData data : (CompositeData[]) value) {
                list.add(convertValueIfNeeded(data));
            }
            return list;
        } else if (value instanceof Object[]) {
            return Arrays.asList((Object[]) value);
        } else if (value instanceof TabularData) {
            TabularData tabularData = (TabularData) value;
            return convertValueIfNeeded(tabularData.values());
        } else if (value instanceof Collection) {
            List<Object> list = new ArrayList<>();
            for (Object data : (Collection<?>) value) {
                list.add(convertValueIfNeeded(data));
            }
            return list;
        }
        return convertJRockitValueIfNeeded(value);
    }

    private Object convertJRockitValueIfNeeded(Object value) {
        if (value instanceof double[]) {
            List<Double> list = new ArrayList<>();
            for (double data : (double[]) value) {
                list.add(data);
            }
            return list;
        } else if (value instanceof int[]) {
            List<Integer> list = new ArrayList<>();
            for (int data : (int[]) value) {
                list.add(data);
            }
            return list;
        }
        return value;
    }

    private List<Object> getConvertedAttributes(List<String> mbeanAttributes) {
        initJRockitMBeansIfNeeded();

        List<Object> result = new ArrayList<>();
        List<MBeanServer> mBeanServers = getMBeanServers();
        for (String mbeansAttribute : mbeanAttributes) {
            int lastIndexOfPoint = mbeansAttribute.lastIndexOf('.');
            if (lastIndexOfPoint <= 0) {
                throw new IllegalArgumentException(mbeansAttribute);
            }
            String name = mbeansAttribute.substring(0, lastIndexOfPoint);
            String attribute = mbeansAttribute.substring(lastIndexOfPoint + 1);
            if ("password".equalsIgnoreCase(attribute)) {
                throw new IllegalArgumentException(name + '.' + attribute);
            }

            InstanceNotFoundException instanceNotFoundException = null;
            for (MBeanServer mbeanServer : mBeanServers) {
                try {
                    MBeansMonitor mbeans = new MBeansMonitor(mbeanServer);
                    Object jmxValue = mbeans.convertValueIfNeeded(mbeans.getAttribute(new ObjectName(name), attribute));
                    result.add(jmxValue);
                    instanceNotFoundException = null;
                    break;
                } catch (InstanceNotFoundException e) {
                    instanceNotFoundException = e;
                } catch (JMException e) {
                    throw new IllegalArgumentException(name + '.' + attribute, e);
                }
            }

            if (instanceNotFoundException != null) {
                throw new IllegalArgumentException(name + '.' + attribute, instanceNotFoundException);
            }
        }
        return result;
    }

    String getConvertedAttributes(String jmxValueParameter) {
        List<String> mbeanAttributes = Arrays.asList(jmxValueParameter.split("[|]"));
        List<Object> jmxValues = getConvertedAttributes(mbeanAttributes);
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Object jmxValue : jmxValues) {
            if (first) {
                first = false;
            } else {
                sb.append('|');
            }
            sb.append(jmxValue);
        }
        return sb.toString();
    }

    private String getAttributeDescription(String name, MBeanAttributeInfo[] attributeInfos) {
        for (MBeanAttributeInfo attributeInfo : attributeInfos) {
            if (name.equals(attributeInfo.getName())) {
                String attributeDescription = formatDescription(attributeInfo.getDescription());
                if (attributeDescription == null || attributeDescription.isEmpty() || name.equals(attributeDescription)) {
                    return null;
                }
                return attributeDescription;
            }
        }
        return null;
    }

    private List<MBeanServer> getMBeanServers() {
        return MBeanServerFactory.findMBeanServer(null);
    }
}


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

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/carousel_item_background">

    <android.support.constraint.Guideline
        android:id="@+id/thumb_guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent=".8" />

    <ImageView
        android:id="@+id/video_thumb"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        app:layout_constraintBottom_toTopOf="@+id/thumb_guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:scaleType="centerCrop"/>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/video_thumb"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp"
            android:layout_centerVertical="true"
            android:textSize="@dimen/carousel_item_title"
            android:textColor="@color/carousel_item_title"
            android:singleLine="true"
            android:ellipsize="end"
            android:gravity="top"/>

        <TextView
            android:id="@+id/subtitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignStart="@id/title"
            android:layout_below="@id/title"
            android:layout_marginTop="4dp"
            android:layout_marginBottom="2dp"
            android:textSize="@dimen/carousel_item_subtitle"
            android:textColor="@color/carousel_item_subtitle"/>

    </RelativeLayout>

</android.support.constraint.ConstraintLayout>


text:
class Chef
  class Provider
    class MysqlService
      class Upstart < Chef::Provider::MysqlService
        action :start do
          template "#{new_resource.name} :start /usr/sbin/#{mysql_name}-wait-ready" do
            path "/usr/sbin/#{mysql_name}-wait-ready"
            source 'upstart/mysqld-wait-ready.erb'
            owner 'root'
            group 'root'
            mode '0755'
            variables(socket_file: socket_file)
            cookbook 'mysql'
            action :create
          end

          template "#{new_resource.name} :start /etc/init/#{mysql_name}.conf" do
            path "/etc/init/#{mysql_name}.conf"
            source 'upstart/mysqld.erb'
            owner 'root'
            group 'root'
            mode '0644'
            variables(
              defaults_file: defaults_file,
              mysql_name: mysql_name,
              run_group: new_resource.run_group,
              run_user: new_resource.run_user,
              socket_dir: socket_dir
              )
            cookbook 'mysql'
            action :create
          end

          service "#{new_resource.name} :start #{mysql_name}" do
            service_name mysql_name
            provider Chef::Provider::Service::Upstart
            supports status: true
            action [:start]
          end
        end

        action :stop do
          service "#{new_resource.name} :stop #{mysql_name}" do
            service_name mysql_name
            provider Chef::Provider::Service::Upstart
            supports restart: true, status: true
            action [:stop]
          end
        end

        action :restart do
          # With Upstart, restarting the service doesn't behave "as expected".
          # We want the post-start stanzas, which wait until the
          # service is available before returning
          #
          # http://upstart.ubuntu.com/cookbook/#restart
          service "#{new_resource.name} :restart stop #{mysql_name}" do
            service_name mysql_name
            provider Chef::Provider::Service::Upstart
            action :stop
          end

          service "#{new_resource.name} :restart start #{mysql_name}" do
            service_name mysql_name
            provider Chef::Provider::Service::Upstart
            action :start
          end
        end

        action :reload do
          # With Upstart, reload just sends a HUP signal to the process.
          # As far as I can tell, this doesn't work the way it's
          # supposed to, so we need to actually restart the service.
          service "#{new_resource.name} :reload stop #{mysql_name}" do
            service_name mysql_name
            provider Chef::Provider::Service::Upstart
            action :stop
          end

          service "#{new_resource.name} :reload start #{mysql_name}" do
            service_name mysql_name
            provider Chef::Provider::Service::Upstart
            action :start
          end
        end

        def create_stop_system_service
          service "#{new_resource.name} :create #{system_service_name}" do
            service_name system_service_name
            provider Chef::Provider::Service::Upstart
            supports status: true
            action [:stop, :disable]
          end
        end

        def delete_stop_service
          service "#{new_resource.name} :delete #{mysql_name}" do
            service_name mysql_name
            provider Chef::Provider::Service::Upstart
            action [:disable, :stop]
            only_if { ::File.exist?("#{etc_dir}/init/#{mysql_name}") }
          end
        end
      end
    end
  end
end


text:
{% extends "base.html" %}

{% block title %}myTBA Event {{event.name}} - The Blue Alliance{% endblock %}

{% block meta_description %}Manage your favorites and subscriptions{% endblock %}

{% block content %}

Account Overview

Manage myTBA

Event: {{event.name}}

myTBA Event: {{event.name}}

        Favorite this event for personalized content and quick access to it later.

        {% include "mytba_partials/mytba_push.html" %}

      {% if is_wildcard %}

        WARNING!

        You are about to subscribe to notifications for all events in {{event.year}}.
        This is only advised if you are on a developer account and want to receive
        push notifications via webhooks for all events.

      {% endif %}

      <form method="post">
        <input name="action" type="hidden" value="subscription_year_add" />
        <input name="account_id" type="hidden" value="{{user_bundle.account.key.id()}}" />

          {% if not is_wildcard %}

            Favorite:

<input type="checkbox" name="favorite"{% if is_favorite %} checked{% endif %}/>

          {% endif %}

            Subscriptions:

                {% for notif_type_enum, name in enabled_notifications %}

<input type="checkbox" name="notification_types" value="{{notif_type_enum}}"{% if notif_type_enum in subscription.notification_types %} checked{% endif %}/> {{ name }}

                {% endfor %}

        <button type="submit" class="btn btn-primary"> Save</button>
         Cancel
      </form>

{% endblock %}


text:
package hudson.plugins.warnings.parser;

import java.util.regex.Matcher;

import org.apache.commons.lang.StringUtils;
import org.jvnet.localizer.Localizable;

import hudson.Extension;

import hudson.plugins.analysis.util.model.Priority;

/**
 * A parser for the CodeAnalysis compiler warnings.
 *
 * @author Rafal Jasica
 */
@Extension
public class CodeAnalysisParser extends RegexpLineParser {
    private static final long serialVersionUID = -125874563249851L;
    private static final String WARNING_PATTERN = ANT_TASK
            + "((MSBUILD)|((.+)\\((\\d+)\\)))\\s*:\\s*[Ww]arning\\s*:?\\s*(\\w*)\\s*:\\s*(Microsoft\\.|)(\\w*(\\.\\w*)*)\\s*:\\s*(.*)\\[(.*)\\]\\s*$";

    /**
     * Creates a new instance of {@link CodeAnalysisParser}.
     */
    public CodeAnalysisParser() {
        this(Messages._Warnings_CodeAnalysis_ParserName(), Messages._Warnings_CodeAnalysis_LinkName(),
                Messages._Warnings_CodeAnalysis_TrendName());
    }

    /**
     * Creates a new instance of {@link CodeAnalysisParser}.
     *
     * @param parserName
     *            name of the parser
     * @param linkName
     *            name of the project action link
     * @param trendName
     *            name of the trend graph
     */
    public CodeAnalysisParser(final Localizable parserName, final Localizable linkName, final Localizable trendName) {
        super(parserName, linkName, trendName, WARNING_PATTERN);
    }

    @Override
    protected Warning createWarning(final Matcher matcher) {
        if (StringUtils.isNotBlank(matcher.group(2))) {
            return createWarning(matcher.group(11), 0, matcher.group(6), matcher.group(8), matcher.group(10), Priority.NORMAL);
        }
        else {
            return createWarning(matcher.group(4), getLineNumber(matcher.group(5)), matcher.group(6), matcher.group(8), matcher.group(10), Priority.NORMAL);
        }
    }
}


text:
package org.codehaus.mojo.animal_sniffer.maven;

import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
import org.codehaus.plexus.component.configurator.ConfigurationListener;
import org.codehaus.plexus.component.configurator.converters.AbstractConfigurationConverter;
import org.codehaus.plexus.component.configurator.converters.ConfigurationConverter;
import org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
import org.codehaus.plexus.configuration.PlexusConfiguration;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Plexus ConfigurationConverter
 *
 * @author Stephen Connolly
 */
public class JdkToolchainConverter
    extends AbstractConfigurationConverter
{
    public static final String ROLE = ConfigurationConverter.class.getName();

    /**
     * @see org.codehaus.plexus.component.configurator.converters.ConfigurationConverter#canConvert(java.lang.Class)
     */
    public boolean canConvert( Class type )
    {
        return JdkToolchain.class.isAssignableFrom( type );
    }

    /**
     * @see org.codehaus.plexus.component.configurator.converters.ConfigurationConverter#fromConfiguration(org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup, org.codehaus.plexus.configuration.PlexusConfiguration, java.lang.Class, java.lang.Class, java.lang.ClassLoader, org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator, org.codehaus.plexus.component.configurator.ConfigurationListener)
     */
    public Object fromConfiguration( ConverterLookup converterLookup, PlexusConfiguration configuration, Class type,
                                     Class baseType, ClassLoader classLoader, ExpressionEvaluator expressionEvaluator,
                                     ConfigurationListener listener )
        throws ComponentConfigurationException
    {
        return fromConfiguration( configuration, expressionEvaluator );
    }

    private JdkToolchain fromConfiguration( PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator )
        throws ComponentConfigurationException
    {
        PlexusConfiguration[] params = configuration.getChildren();
        Map<String, String> parameters = new HashMap<>();
        for ( PlexusConfiguration param : params )
        {
            String name = param.getName();
            String val = param.getValue();
            parameters.put( name, val );
        }
        final JdkToolchain result = new JdkToolchain();
        result.setParameters( Collections.unmodifiableMap( parameters ) );
        return result;
    }
}


text:
  This script is used to check the current game versions and return if they are
  up-to-date or not.

  The two versions are the built-in PlaceVersion value and a string set in
  Main.lua following the Semantic Versioning Specification (http://semver.org).

  PlaceVersion is a quick way to see if the server instance is out of date, while
  SemVer is a way to be more descriptive with the current game version, along with
  making it clear when creating releases of the software.
--]]

repeat wait() until _G.Ready

local Data = require(_G.Modules.Data)

local Version = {}

--[[
  Takes the version string and seperates each part into a key/value pair in
  a table. Eg. "v0.1.0-alpha.1" would be turned into:

  {
    "major" = 0,
    "minor" = 1,
    "patch" = 0,
    "alpha" = 1,
    "prerelease" = true
  }
--]]
function Version:ConvertToTable(versionString)
  -- versionString = "v0.1.0-alpha.1"
  local versionNumber = versionString:match("v%d+\.%d+\.%d+") -- "v0.1.0"
  local prereleaseVersion = versionString:match("\-%a*\.%d+") -- "-alpha.1"

  local versionTable = {}

  local function majorMinorPatch()
    -- Is there a method I can use to accomplish this without an iterator
    -- variable?
    local iterator = 0
    for digit in versionNumber:gmatch("%d+") do
      if iterator == 0 then
        versionTable.major = tonumber(digit) -- 0
      elseif iterator == 1 then
        versionTable.minor = tonumber(digit) -- 1
      elseif iterator == 2 then
        versionTable.patch = tonumber(digit) -- 0
      end

      iterator = iterator + 1
    end
  end

  local function prerelease()
    local prereleaseName = prereleaseVersion:match("%a+") -- alpha
    local prereleaseNumber = prereleaseVersion:match("%d+") -- 1

    versionTable[prereleaseName] = prereleaseNumber

    --[[
      A value used to easily get the current prerelease version number, without
      having to search for "alpha" or "beta". eg:

        print(versionTable[versionTable.prerelease]) -- 1
    --]]
    versionTable.prerelease = prereleaseName
  end

  majorMinorPatch()

  if prereleaseVersion then
    prerelease()
  end

  return versionTable
end

--[[
  This convoluted function deciphers the server's semantic version number and
  returns if it's up to date or not.

  The complicated thing is, v0.5.0 is a greater version than v0.4.9, making
  lots of 'if' statements required to figure everything out.
--]]
function Version:LatestSemantic()
  local currentVersion = self:ConvertToTable(_G.Version)
  local latestVersion

  if Data:Get("Server", "version") then
    latestVersion = self:ConvertToTable(Data:Get("Server", "version"))
  else
    -- If you forget to set the place version in a new game.
    warn("Latest semantic version does not exist in the \"version\" DataStore. Set to _G.Version.")
    latestVersion = currentVersion
  end

  local majorUpdated
  local minorUpdated

  local function compareMajor(current, latest)
    if current.major > latest.major then
      majorUpdated = true
      return true -- MAJOR was updated.
    elseif current.major == latest.major then
      return true -- MAJOR is the same as latest.
    else
      return false
    end
  end

  local function compareMinor(current, latest)
    if current.minor < latest.minor and majorUpdated == true then
      minorUpdated = true
      return true -- MINOR decreased in value, MAJOR was updated.
    elseif current.minor > latest.minor then
      minorUpdated = true
      return true -- MINOR went up in value
    elseif current.minor == latest.minor then
      return true -- MINOR is the same as latest.
    else
      return false
    end
  end

  local function comparePatch(current, latest)
    if current.patch < latest.patch and minorUpdated == true then
      return true -- PATCH decreased in value, MINOR was updated.
    elseif current.patch > latest.patch then
      return true -- PATCH is greater than latest.
    elseif current.patch == latest.patch then
      return true -- PATCH is the same as latest.
    else
      return false
    end
  end

  local function comparePrerelease(current, latest)
    local pre = current.prerelease -- "alpha"

    if current[pre] >= latest[pre] then
      return true
    else
      return false
    end
  end

  local function compareVersions(current, latest)
    local major = compareMajor(current, latest)
    local minor = compareMinor(current, latest)
    local patch = comparePatch(current, latest)
    local prerelease = comparePrerelease(current, latest)

    -- print(major, minor, patch, prerelease)

    if major and minor and patch then
      if prerelease then
        return true
      else
        return false
      end

      return true
    else
      return false
    end
  end

  return compareVersions(currentVersion, latestVersion)
end

--[[
  Compare the PlaceVersion value against the one on the server and return if
  the current one is up to date or not.

  (SO much easier than the semantic version number)
--]]
function Version:LatestPlace()
  local currentVersion = game.PlaceVersion
  local latestVersion

  if Data:Get("Server", "placeVersion") then
    latestVersion = Data:Get("Server", "placeVersion")
  else
    warn("Latest place version does not exist in the \"version\" DataStore. Set to game.PlaceVersion.")
    latestVersion = currentVersion
  end

  if currentVersion >= latestVersion then
    return true
  else
    return false
  end
end

--[[
  Pushes up the current Semantic and Place versions to the "Server" datastore if
  they are the same or greater than the ones stored.
--]]
function Version:UpdateStoredData()
  if self:LatestSemantic() then
    Data:Update("Server", "version", _G.Version)
  end

  if self:LatestPlace() then
    Data:Update("Server", "placeVersion", game.PlaceVersion)
  end
end

function warn(message)
  game:GetService("TestService"):Warn(false, message)
end

return Version


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.zxytech.designpatterns</groupId>
        <artifactId>DesignPatterns</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>JavaEE</artifactId>
    <version>1.0-SNAPSHOT</version>

</project>


text:
A simple, durable Clojure queueing library.  While this is believed to
be reasonably solid, it is still relatively new, and the API or
behavior may change without warning.

Stockpile supports the durable storage and retrieval of data.  After
storage, stockpile returns an `entry` that can be used to access the
data later, and when no longer needed, the data can be atomically
`discard`ed.

Stockpile is explicitly designed to keep minimal state outside the
filesystem.  After opening a queue, you can call `reduce` to traverse
the existing entries, but stockpile itself does not retain information
about the entries.  You must preserve any that you might want to
access later.

The ordering of any two entries can be compared (by `id`), but that
ordering is not guaranteed to be exact, only some approximation of
their relative insertion order.

A metadata string can be provided for each item stored, but the length
of that string may be limited by the underlying filesystem.  (The
string is currently encoded into the queue item's pathname so that it
can be retrieved without having to open or read the file itself).  The
filesystem might also alter the metadata in other ways, for example if
it does not preserve case.  The path that's ultimately specified to
the filesystem by the JVM may be affected by the locale, and on Linux
with common filesystems, for example, often produces UTF-8 paths.  See
`(doc stockpile/store)` for further information.

Stockpile is intended to work correctly on any filesystem where rename
(ATOMIC\_MOVE) works correctly, and where calling fsync/fdatasync on a
file and its parent directory makes the file durable.  At last look,
[that did not include OS X](https://bugs.openjdk.java.net/browse/JDK-8080589).

Unless the items being inserted into the queue are large enough for
the sequential transfer rate to dominate, the insertion rate is likely
to be limited by the maximum "fsync/fdatasync rate" of the underlying
filesystem.

The current implementation tracks the queue ids using an AtomicLong,
and while that counter could overflow, even at 100,000 stores per
second, it should require about 290 million years.

Stockpile's behavior given unexpected files inside its directory is
undefined.

## Usage

See src/stockpile.clj and test/stockpile_test.clj for the API
documentation and sample usage.

## Testing

As expected, "lein test" will run the test suite, but there are some
additional tests can only be run if `STOCKPILE\_TINY\_TEST\_FS` is set
to a directory that resides on an otherwise quiet filesystem with less
than 10MB of free space, that is not the current filesystem:

    STOCKPILE_TINY_TEST_FS=~/tmp/tiny lein test

During the tests stockpile may repeatedly fill that filesystem.

You can also run the tests via `./run-test`, and if you're on Linux
and root, it will automatically set up, use, and tear down a suitable
tiny loopback filesystem.  Alternately, if you have sudo access to
root, you can invoke `./run-test --use-sudo` to do the same.  Though
invoking `./run-test` outside of a "throwaway" virtual machine is not
recommended right now.

## License

Copyright © 2016 Puppet Labs Inc

Distributed under the Apache License Version 2.0.  See ./LICENSE for
details.


text:
<?php

final class DiffusionRepositorySubversionManagementPanel
  extends DiffusionRepositoryManagementPanel {

  const PANELKEY = 'subversion';

  public function getManagementPanelLabel() {
    return pht('Subversion');
  }

  public function getManagementPanelOrder() {
    return 1000;
  }

  public function shouldEnableForRepository(
    PhabricatorRepository $repository) {
    return $repository->isSVN();
  }

  public function getManagementPanelIcon() {
    $repository = $this->getRepository();

    $has_any = (bool)$repository->getDetail('svn-subpath');

    if ($has_any) {
      return 'fa-database';
    } else {
      return 'fa-database grey';
    }
  }

  protected function getEditEngineFieldKeys() {
    return array(
      'importOnly',
    );
  }

  protected function buildManagementPanelActions() {
    $repository = $this->getRepository();
    $viewer = $this->getViewer();

    $can_edit = PhabricatorPolicyFilter::hasCapability(
      $viewer,
      $repository,
      PhabricatorPolicyCapability::CAN_EDIT);

    $subversion_uri = $this->getEditPageURI();

    return array(
      id(new PhabricatorActionView())
        ->setIcon('fa-pencil')
        ->setName(pht('Edit Properties'))
        ->setHref($subversion_uri)
        ->setDisabled(!$can_edit)
        ->setWorkflow(!$can_edit),
    );
  }

  public function buildManagementPanelContent() {
    $repository = $this->getRepository();
    $viewer = $this->getViewer();

    $view = id(new PHUIPropertyListView())
      ->setViewer($viewer)
      ->setActionList($this->newActions());

    $default_branch = nonempty(
      $repository->getHumanReadableDetail('svn-subpath'),
      phutil_tag('em', array(), pht('Import Entire Repository')));
    $view->addProperty(pht('Import Only'), $default_branch);

    return $this->newBox(pht('Subversion'), $view);
  }

}


text:
#pragma once
#include <aws/lookoutmetrics/LookoutMetrics_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/lookoutmetrics/model/AnomalyDetectorSummary.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace LookoutMetrics
{
namespace Model
{
  class AWS_LOOKOUTMETRICS_API ListAnomalyDetectorsResult
  {
  public:
    ListAnomalyDetectorsResult();
    ListAnomalyDetectorsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListAnomalyDetectorsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
A list of anomaly detectors in the account in the current region.

     */
    inline const Aws::Vector<AnomalyDetectorSummary>& GetAnomalyDetectorSummaryList() const{ return m_anomalyDetectorSummaryList; }

    /**
     *
A list of anomaly detectors in the account in the current region.

     */
    inline void SetAnomalyDetectorSummaryList(const Aws::Vector<AnomalyDetectorSummary>& value) { m_anomalyDetectorSummaryList = value; }

    /**
     *
A list of anomaly detectors in the account in the current region.

     */
    inline void SetAnomalyDetectorSummaryList(Aws::Vector<AnomalyDetectorSummary>&& value) { m_anomalyDetectorSummaryList = std::move(value); }

    /**
     *
A list of anomaly detectors in the account in the current region.

     */
    inline ListAnomalyDetectorsResult& WithAnomalyDetectorSummaryList(const Aws::Vector<AnomalyDetectorSummary>& value) { SetAnomalyDetectorSummaryList(value); return *this;}

    /**
     *
A list of anomaly detectors in the account in the current region.

     */
    inline ListAnomalyDetectorsResult& WithAnomalyDetectorSummaryList(Aws::Vector<AnomalyDetectorSummary>&& value) { SetAnomalyDetectorSummaryList(std::move(value)); return *this;}

    /**
     *
A list of anomaly detectors in the account in the current region.

     */
    inline ListAnomalyDetectorsResult& AddAnomalyDetectorSummaryList(const AnomalyDetectorSummary& value) { m_anomalyDetectorSummaryList.push_back(value); return *this; }

    /**
     *
A list of anomaly detectors in the account in the current region.

     */
    inline ListAnomalyDetectorsResult& AddAnomalyDetectorSummaryList(AnomalyDetectorSummary&& value) { m_anomalyDetectorSummaryList.push_back(std::move(value)); return *this; }

    /**
     *
If the response is truncated, the service returns this token. To retrieve the
     * next set of results, use the token in the next request.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
If the response is truncated, the service returns this token. To retrieve the
     * next set of results, use the token in the next request.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
If the response is truncated, the service returns this token. To retrieve the
     * next set of results, use the token in the next request.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
If the response is truncated, the service returns this token. To retrieve the
     * next set of results, use the token in the next request.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
If the response is truncated, the service returns this token. To retrieve the
     * next set of results, use the token in the next request.

     */
    inline ListAnomalyDetectorsResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
If the response is truncated, the service returns this token. To retrieve the
     * next set of results, use the token in the next request.

     */
    inline ListAnomalyDetectorsResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
If the response is truncated, the service returns this token. To retrieve the
     * next set of results, use the token in the next request.

     */
    inline ListAnomalyDetectorsResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<AnomalyDetectorSummary> m_anomalyDetectorSummaryList;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace LookoutMetrics
} // namespace Aws


text:
"""
Display Github notifications and issue/pull requests for a repo.

To check notifications a Github `username` and `personal access token` are
required.  You can create a personal access token at
https://github.com/settings/tokens The only `scope` needed is `notifications`,
which provides readonly access to notifications.

The Github API is rate limited so setting `cache_timeout` too small may cause
issues see https://developer.github.com/v3/#rate-limiting for details

Configuration parameters:
    auth_token: Github personal access token, needed to check notifications
        see above.
        (default None)
    button_action: Button that when clicked opens the Github notification page
        if notifications, else the project page for the repository . Setting to
        `0` disables.
        (default 3)
    cache_timeout: How often we refresh this module in seconds
        (default 60)
    format: Format of output
        (default '{repo} {issues}/{pull_requests}{notifications}'
        if username and auth_token provided else
        '{repo} {issues}/{pull_requests}')
    format_notifications: Format of `{notification}` status placeholder.
        (default ' N{notifications_count}')
    notifications: Type of notifications can be `all` for all notifications or
        `repo` to only get notifications for the repo specified.  If repo is
        not provided then all notifications will be checked.
        (default 'all')
    repo: Github repo to check
        (default 'ultrabug/py3status')
    username: Github username, needed to check notifications.
        (default None)

Format of status string placeholders:
    {repo} the short name of the repository being checked.
        eg py3status
    {repo_full} the full name of the repository being checked.
        eg ultrabug/py3status
    {issues} Number of open issues.
    {pull_requests} Number of open pull requests
    {notifications} Notifications.  If no notifications this will be empty.
    {notifications_count} Number of notifications.  This is also the __Only__
        status string available to `format_notifications`.

Requires:
    requests: python module from pypi https://pypi.python.org/pypi/requests

Examples:

```
# set github access credentials
github {
    auth_token = '40_char_hex_access_token'
    username = 'my_username'
}

# just check for any notifications
github {
    auth_token = '40_char_hex_access_token'
    username = 'my_username'
    format = 'Github {notifications_count}'
}
```

@author tobes
"""
from shlex import split
from subprocess import call

import requests

GITHUB_API_URL = 'https://api.github.com'
GITHUB_URL = 'https://github.com/'

class Py3status:
    auth_token = None
    button_action = 3
    cache_timeout = 60
    format = None
    format_notifications = ' N{notifications_count}'
    notifications = 'all'
    repo = 'ultrabug/py3status'
    username = None

    def __init__(self):
        self.first = True
        self.notification_warning = False
        self.repo_warning = False
        self._issues = '?'
        self._pulls = '?'
        self._notify = '?'

    def _init(self):
        # Set format if user has not configured it.
        if not self.format:
            if self.username and self.auth_token:
                # include notifications
                self.format = '{repo} {issues}/{pull_requests}{notifications}'
            else:
                self.format = '{repo} {issues}/{pull_requests}'

    def _github_count(self, url):
        '''
        Get counts for requests that return 'total_count' in the json response.
        '''
        if self.first:
            return '?'
        url = GITHUB_API_URL + url + '&per_page=1'
        # if we have authentication details use them as we get better
        # rate-limiting.
        if self.username and self.auth_token:
            auth = (self.username, self.auth_token)
        else:
            auth = None
        try:
            info = requests.get(url, 'GET', timeout=10, auth=auth)
        except requests.ConnectionError:
            return
        if info and info.status_code == 200:
            return(int(info.json()['total_count']))
        if info.status_code == 422:
            if not self.repo_warning:
                self.py3.notify_user('Github repo cannot be found.')
                self.repo_warning = True
        return '?'

    def _notifications(self):
        '''
        Get the number of unread notifications.
        '''
        if not self.username or not self.auth_token:
            if not self.notification_warning:
                self.py3.notify_user('Github module needs username and '
                                     'auth_token to check notifications.')
                self.notification_warning = True
            return '?'
        if self.first:
            return '?'
        if self.notifications == 'all' or not self.repo:
            url = GITHUB_API_URL + '/notifications'
        else:
            url = GITHUB_API_URL + '/repos/' + self.repo + '/notifications'
        url += '?per_page=100'
        try:
            info = requests.get(url, timeout=10,
                                auth=(self.username, self.auth_token))
        except requests.ConnectionError:
            return
        if info.status_code == 200:
            return len(info.json())
        if info.status_code == 404:
            if not self.repo_warning:
                self.py3.notify_user('Github repo cannot be found.')
                self.repo_warning = True

    def github(self):
        if self.first:
            self._init()
        status = {}
        urgent = False
        # issues
        if self.repo and '{issues}' in self.format:
            url = '/search/issues?q=state:open+type:issue+repo:' + self.repo
            self._issues = self._github_count(url) or self._issues
        status['issues'] = self._issues
        # pull requests
        if self.repo and '{pull_requests}' in self.format:
            url = '/search/issues?q=state:open+type:pr+repo:' + self.repo
            self._pulls = self._github_count(url) or self._pulls
        status['pull_requests'] = self._pulls
        # notifications
        if ('{notifications}' in self.format or
                '{notifications_count}' in self.format):
            count = self._notifications()
            # if we don't have a notification count, then use the last value
            # that we did have.
            if count is None:
                count = self._notify
            self._notify = count
            if count and count != '?':
                notify = self.py3.safe_format(
                    self.format_notifications,
                    {'notifications_count': count})
                urgent = True
            else:
                notify = ''
            status['notifications'] = notify
            status['notifications_count'] = count
        # repo
        try:
            status['repo'] = self.repo.split('/')[1]
        except IndexError:
            status['repo'] = 'Error'
        status['repo_full'] = self.repo

        if self.first:
            cached_until = 0
            self.first = False
        else:
            cached_until = self.py3.time_in(self.cache_timeout)

        return {
            'full_text': self.py3.safe_format(self.format, status),
            'cached_until': cached_until,
            'urgent': urgent
        }

    def on_click(self, event):
        button = event['button']
        if self.button_action and self.button_action == button:
            if self._notify and self._notify != '?':
                # open github notifications page in default browser
                url = GITHUB_URL + 'notifications'
            else:
                # open repo page
                url = GITHUB_URL + self.repo
            cmd = 'xdg-open {}'.format(url)
            call(split(cmd))
            self.py3.prevent_refresh()

if __name__ == "__main__":
    """
    Run module in test mode.
    """
    from py3status.module_test import module_test
    module_test(Py3status)


text:
var path = require('path')
var webpack = require('webpack')
require('weex-loader');

var bannerPlugin = new webpack.BannerPlugin(
  '// { "framework": "Vue" }\n',
  { raw: true }
)

function getBaseConfig () {
  return {
    entry: {
      'index': path.resolve('src', 'entry.js')
    },
    output: {
      path: 'dist',
    },
    module: {
      loaders: [
        {
          test: /\.js$/,
          loader: 'babel',
          exclude: /node_modules/
        }, {
          test: /\.vue(\?[^?]+)?$/,
          loaders: []
        },{
          test: /\.we(\?[^?]+)?$/
          , loaders: ['weex-loader']
      }]
    },
    plugins: [bannerPlugin]
  }
}

var webConfig = getBaseConfig()
webConfig.output.filename = '[name].web.js'
webConfig.module.loaders[1].loaders.push('vue')

var weexConfig = getBaseConfig()
weexConfig.output.filename = '[name].weex.js'
weexConfig.module.loaders[1].loaders.push('weex')

module.exports = [webConfig, weexConfig]


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse version="3.0"?>

<plugin>
   <extension point="org.knime.workbench.repository.nodes">
      <node category-path="/community/HiTS/" factory-class="com.mind_era.knime.hits.interop.BioConverterNodeFactory"/>
      <node category-path="/community/HiTS/" factory-class="com.mind_era.knime.hits.plate.format.PlateFormatNodeFactory"/>
   </extension>

   <extension point="org.eclipse.help.toc">
      <toc extradir="html" file="tocs/libhandl_nodes.xml"/>
      <toc file="tocs/toc.xml"/>
      <toc file="tocs/toc_Interoperability.xml"/>
   </extension>
   <!--extension point="org.eclipse.help.base.luceneSearchParticipants">
      <binding participantId="org.eclipse.help.base.xhtml"/>
   </extension-->
   <extension point="org.eclipse.help.contentProducer">
      <binding producerId="org.eclipse.help.dynamic"/>
   </extension>
</plugin>


text:
<?php

namespace Everon\Http\Interfaces;

interface Cookie
{
    function delete();

    /**
     * @param string $date_value
     * @return void
     */
    function setExpireDateFromString($date_value);

    function neverExpire();

    /**
     * @return string
     */
    function getValue();

    /**
     * @return string
     */
    function getValueAsJson();

    /**
     * @param $json
     */
    function setDataFromJson($json);

    /**
     * @return string
     */
    function getName();

    /**
     * @param string $path
     */
    function setPath($path);

    function isExpired();

    /**
     * @param int $expire_date
     */
    function setExpire($expire_date);

    /**
     * @param string $domain
     */
    function setDomain($domain);

    /**
     * @param string $value
     */
    function setValue($value);

    /**
     * @return int
     */
    function getExpire();

    /**
     * @return string
     */
    function getPath();

    /**
     * @param string $name
     */
    function setName($name);

    /**
     * @return string
     */
    function getDomain();

    function enableHttpOnly();

    function disableHttpOnly();

    /**
     * @return boolean
     */
    function isHttpOnly();

    function enableJson();

    function disableJson();

    /**
     * @return boolean
     */
    function isJsonEnabled();

    function enableSecure();

    function disableSecure();

    /**
     * @return boolean
     */
    function isSecure();

    /**
     * @param boolean $existing
     */
    function setIsExisting($existing);

    /**
     * @return boolean
     */
    function isExisting();
}


text:
<bill session="110" type="h" number="2509" updated="2009-01-08T22:04:28-05:00">
	<status><introduced date="1179979200" datetime="2007-05-24"/></status>

	<introduced date="1179979200" datetime="2007-05-24"/>
	<titles>
		<title type="short" as="introduced">United Nations Voting Accountability Act of 2007</title>
		<title type="official" as="introduced">To prohibit United States assistance to foreign countries that oppose the position of the United States in the United Nations.</title>
	</titles>
	<sponsor id="400651"/>
	<cosponsors>
		<cosponsor id="400113" joined="2007-05-24"/>
		<cosponsor id="400151" joined="2007-05-24"/>
		<cosponsor id="400441" joined="2007-05-24"/>
		<cosponsor id="400313" joined="2007-05-24"/>
		<cosponsor id="412230" joined="2007-05-24"/>
		<cosponsor id="400288" joined="2007-05-24"/>
		<cosponsor id="400642" joined="2007-05-24"/>
		<cosponsor id="400206" joined="2007-05-24"/>
		<cosponsor id="400017" joined="2007-05-24"/>
		<cosponsor id="412235" joined="2007-05-24"/>
		<cosponsor id="400131" joined="2007-05-24"/>
		<cosponsor id="400655" joined="2007-05-24"/>
		<cosponsor id="400153" joined="2007-05-24"/>
		<cosponsor id="400643" joined="2007-05-24"/>
		<cosponsor id="400421" joined="2007-05-24"/>
		<cosponsor id="400005" joined="2007-05-24"/>
		<cosponsor id="400221" joined="2007-05-24"/>
		<cosponsor id="412213" joined="2007-05-24"/>
		<cosponsor id="400145" joined="2007-05-24"/>
		<cosponsor id="400016" joined="2007-05-24"/>
		<cosponsor id="412191" joined="2007-05-24"/>
	</cosponsors>
	<actions>
		<action date="1179979200" datetime="2007-05-24"><text>Referred to the House Committee on Foreign Affairs.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	5/24/2007--Introduced.
United Nations Voting Accountability Act of 2007 - Prohibits providing U.S. assistance (as defined by this Act) to a country that opposed the U.S. position in the United Nations. Authorizes the Secretary of State to (temporarily) exempt a country from such prohibition if since the beginning of the most recent session of the General Assembly there has been a fundamental change in the country's leadership and policies so that the country will no longer oppose the U.S. position in the United Nations. Authorizes the President to exempt a country from such prohibition for national security reasons.

</bill>


text:
<?php
namespace OW\Rules\Parser;

use OW\Rules\Filter\Filter;

interface FilterParser
{
    public function parse($text);

    public function serialize(Filter $filter);
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--

    Copyright © 2006-2016 Web Cohesion (info@webcohesion.com)

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

  <appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.SimpleLayout"/>
  </appender>

  <root>
    <level value ="error"/>
    <appender-ref ref="ConsoleAppender"/>
  </root>

</log4j:configuration>


text:
source .anax/scaffold/functions.bash

#
# Read values from user input
#
NAMESPACE=$( input "Namespace" "${ANAX_NAMESPACE:-Anax\\\\XXX}" )
CLASSNAME=$( input "Class name" "ClassName" )
# cLASSNAME=${CLASSNAME,} # Need bash 4, fails on Mac
cLASSNAME=$( echo $CLASSNAME | cut -c1 | tr '[:upper:]' '[:lower:]' )$( echo $CLASSNAME | cut -c2- )

# Model
file="MODEL.php"
sedi "s/NAMESPACE/$NAMESPACE/g" "$file"
sedi "s/CLASSNAME/$CLASSNAME/g" "$file"
mv "$file" "$CLASSNAME.php"

# Controller
file="CONTROLLER.php"
sedi "s/NAMESPACE/$NAMESPACE/g" "$file"
sedi "s/CLASSNAME/$CLASSNAME/g" "$file"
sedi "s/cLASSNAME/$cLASSNAME/g" "$file"
mv "$file" "${CLASSNAME}Controller.php"

# CreateForm
file="HTMLForm/CreateForm.php"
sedi "s/NAMESPACE/$NAMESPACE/g" "$file"
sedi "s/CLASSNAME/$CLASSNAME/g" "$file"
sedi "s/cLASSNAME/$cLASSNAME/g" "$file"

# UpdateForm
file="HTMLForm/UpdateForm.php"
sedi "s/NAMESPACE/$NAMESPACE/g" "$file"
sedi "s/CLASSNAME/$CLASSNAME/g" "$file"
sedi "s/cLASSNAME/$cLASSNAME/g" "$file"

# DeleteForm
file="HTMLForm/DeleteForm.php"
sedi "s/NAMESPACE/$NAMESPACE/g" "$file"
sedi "s/CLASSNAME/$CLASSNAME/g" "$file"
sedi "s/cLASSNAME/$cLASSNAME/g" "$file"

# Routes for the controller
path="extra/config/router"
file="100_CONTROLLER.php"
sedi "s/NAMESPACE/$NAMESPACE/g" "$path/$file"
sedi "s/cLASSNAME/$cLASSNAME/g" "$path/$file"
sedi "s/CLASSNAME/$CLASSNAME/g" "$path/$file"
mv "$path/$file" "$path/100_${cLASSNAME}Controller.php"

# Prepare database table MySQL
path="extra/sql/ddl"
file="mysql.sql"
sedi "s/CLASSNAME/$CLASSNAME/g" "$path/$file"
mv "$path/$file" "$path/${cLASSNAME}_$file"

# Prepare database table SQLite
path="extra/sql/ddl"
file="sqlite.sql"
sedi "s/CLASSNAME/$CLASSNAME/g" "$path/$file"
mv "$path/$file" "$path/${cLASSNAME}_$file"

# view for create
file="extra/view/CLASSNAME/crud/create.php"
sedi "s/cLASSNAME/$cLASSNAME/g" "$file"

# view for update
file="extra/view/CLASSNAME/crud/update.php"
sedi "s/cLASSNAME/$cLASSNAME/g" "$file"

# view for delete
file="extra/view/CLASSNAME/crud/delete.php"
sedi "s/cLASSNAME/$cLASSNAME/g" "$file"

# view for view-all
file="extra/view/CLASSNAME/crud/view-all.php"
sedi "s/cLASSNAME/$cLASSNAME/g" "$file"

# Prepare view directory
path="extra/view"
file="CLASSNAME"
install -d "$path/${cLASSNAME}/crud/"
rsync -a "$path/$file/" "$path/${cLASSNAME}/"
rm -rf "${path:?}/$file"