text:
package de.uni_passau.facultyinfo.client.fragment;

import java.util.List;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import de.uni_passau.facultyinfo.client.R;
import de.uni_passau.facultyinfo.client.activity.DisplayTimeTableEntryActivity;
import de.uni_passau.facultyinfo.client.activity.EditTimeTableActivity;
import de.uni_passau.facultyinfo.client.model.access.AccessFacade;
import de.uni_passau.facultyinfo.client.model.dto.TimetableEntry;
import de.uni_passau.facultyinfo.client.util.ColorHelper;

public class TimetableFragment extends Fragment {

	private View rootView;

	private int dayC;
	private int timeslotId;

	OnLongClickListener onLongClickListener;

	public TimetableFragment() {
		// Empty constructor required for fragment subclasses
	}

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

		getActivity().getActionBar().setTitle(
				getActivity().getApplicationContext().getString(
						R.string.title_timetable));
		getActivity().getActionBar().setNavigationMode(
				ActionBar.NAVIGATION_MODE_STANDARD);

		onLongClickListener = new View.OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				System.out.println("onLongClick");
				editEventTT(v);
				return true;
			}
		};

		return rootView;

	}

	@Override
	public void onResume() {
		((TextView) rootView.findViewById(R.id.mo810)).setText(null);
		((TextView) rootView.findViewById(R.id.mo1012)).setText(null);
		((TextView) rootView.findViewById(R.id.mo1214)).setText(null);
		((TextView) rootView.findViewById(R.id.mo1416)).setText(null);
		((TextView) rootView.findViewById(R.id.mo1618)).setText(null);
		((TextView) rootView.findViewById(R.id.mo1820)).setText(null);

		((TextView) rootView.findViewById(R.id.di810)).setText(null);
		((TextView) rootView.findViewById(R.id.di1012)).setText(null);
		((TextView) rootView.findViewById(R.id.di1214)).setText(null);
		((TextView) rootView.findViewById(R.id.di1416)).setText(null);
		((TextView) rootView.findViewById(R.id.di1618)).setText(null);
		((TextView) rootView.findViewById(R.id.di1820)).setText(null);

		((TextView) rootView.findViewById(R.id.mi810)).setText(null);
		((TextView) rootView.findViewById(R.id.mi1012)).setText(null);
		((TextView) rootView.findViewById(R.id.mi1214)).setText(null);
		((TextView) rootView.findViewById(R.id.mi1416)).setText(null);
		((TextView) rootView.findViewById(R.id.mi1618)).setText(null);
		((TextView) rootView.findViewById(R.id.mi1820)).setText(null);

		((TextView) rootView.findViewById(R.id.don810)).setText(null);
		((TextView) rootView.findViewById(R.id.don1012)).setText(null);
		((TextView) rootView.findViewById(R.id.don1214)).setText(null);
		((TextView) rootView.findViewById(R.id.don1416)).setText(null);
		((TextView) rootView.findViewById(R.id.don1618)).setText(null);
		((TextView) rootView.findViewById(R.id.don1820)).setText(null);

		((TextView) rootView.findViewById(R.id.fr810)).setText(null);
		((TextView) rootView.findViewById(R.id.fr1012)).setText(null);
		((TextView) rootView.findViewById(R.id.fr1214)).setText(null);
		((TextView) rootView.findViewById(R.id.fr1416)).setText(null);
		((TextView) rootView.findViewById(R.id.fr1618)).setText(null);
		((TextView) rootView.findViewById(R.id.fr1820)).setText(null);

		((TextView) rootView.findViewById(R.id.mo810))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mo1012))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mo1214))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mo1416))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mo1618))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mo1820))
				.setOnLongClickListener(onLongClickListener);

		((TextView) rootView.findViewById(R.id.di810))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.di1012))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.di1214))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.di1416))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.di1618))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.di1820))
				.setOnLongClickListener(onLongClickListener);

		((TextView) rootView.findViewById(R.id.mi810))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mi1012))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mi1214))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mi1416))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mi1618))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.mi1820))
				.setOnLongClickListener(onLongClickListener);

		((TextView) rootView.findViewById(R.id.don810))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.don1012))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.don1214))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.don1416))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.don1618))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.don1820))
				.setOnLongClickListener(onLongClickListener);

		((TextView) rootView.findViewById(R.id.fr810))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.fr1012))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.fr1214))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.fr1416))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.fr1618))
				.setOnLongClickListener(onLongClickListener);
		((TextView) rootView.findViewById(R.id.fr1820))
				.setOnLongClickListener(onLongClickListener);

		((TextView) rootView.findViewById(R.id.mo810))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mo1012))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mo1214))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mo1416))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mo1618))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mo1820))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));

		((TextView) rootView.findViewById(R.id.di810))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.di1012))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.di1214))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.di1416))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.di1618))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.di1820))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));

		((TextView) rootView.findViewById(R.id.mi810))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mi1012))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mi1214))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mi1416))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mi1618))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.mi1820))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));

		((TextView) rootView.findViewById(R.id.don810))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.don1012))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.don1214))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.don1416))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.don1618))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.don1820))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));

		((TextView) rootView.findViewById(R.id.fr810))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.fr1012))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.fr1214))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.fr1416))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.fr1618))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));
		((TextView) rootView.findViewById(R.id.fr1820))
				.setBackgroundColor(android.graphics.Color
						.parseColor("#FFFFFF"));

		new TimetableEntryLoader().execute();
		super.onResume();
	}

	protected void editEventTT(View v) {
		System.out.println("editEventTT");

		if (v.getId() == (rootView.findViewById(R.id.mo810).getId())
				|| v.getId() == (rootView.findViewById(R.id.mo1012).getId())
				|| v.getId() == (rootView.findViewById(R.id.mo1214).getId())
				|| v.getId() == (rootView.findViewById(R.id.mo1416).getId())
				|| v.getId() == (rootView.findViewById(R.id.mo1618).getId())
				|| v.getId() == (rootView.findViewById(R.id.mo1820).getId())) {
			dayC = TimetableEntry.MONDAY;
		} else if (v.getId() == (rootView.findViewById(R.id.di810).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1012).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1214).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1416).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1618).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1820).getId())) {
			dayC = TimetableEntry.TUESDAY;
		} else if (v.getId() == (rootView.findViewById(R.id.mi810).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1012).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1214).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1416).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1618).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1820).getId())) {
			dayC = TimetableEntry.WEDNESDAY;
		} else if (v.getId() == (rootView.findViewById(R.id.don810).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1012).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1214).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1416).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1618).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1820).getId())) {
			dayC = TimetableEntry.THURSDAY;
		} else if (v.getId() == (rootView.findViewById(R.id.fr810).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1012).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1214).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1416).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1618).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1820).getId())) {
			dayC = TimetableEntry.FRIDAY;
		}

		if (v.getId() == (rootView.findViewById(R.id.mo810).getId())
				|| v.getId() == (rootView.findViewById(R.id.di810).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi810).getId())
				|| v.getId() == (rootView.findViewById(R.id.don810).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr810).getId())) {
			timeslotId = TimetableEntry.FROM_08_TO_10;
		} else if (v.getId() == (rootView.findViewById(R.id.mo1012).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1012).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1012).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1012).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1012).getId())) {
			timeslotId = TimetableEntry.FROM_10_TO_12;
		} else if (v.getId() == (rootView.findViewById(R.id.mo1214).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1214).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1214).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1214).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1214).getId())) {
			timeslotId = TimetableEntry.FROM_12_TO_14;
		} else if (v.getId() == (rootView.findViewById(R.id.mo1416).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1416).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1416).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1416).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1416).getId())) {
			timeslotId = TimetableEntry.FROM_14_TO_16;
		} else if (v.getId() == (rootView.findViewById(R.id.mo1618).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1618).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1618).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1618).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1618).getId())) {
			timeslotId = TimetableEntry.FROM_16_TO_18;
		} else if (v.getId() == (rootView.findViewById(R.id.mo1820).getId())
				|| v.getId() == (rootView.findViewById(R.id.di1820).getId())
				|| v.getId() == (rootView.findViewById(R.id.mi1820).getId())
				|| v.getId() == (rootView.findViewById(R.id.don1820).getId())
				|| v.getId() == (rootView.findViewById(R.id.fr1820).getId())) {
			timeslotId = TimetableEntry.FROM_18_TO_20;
		}

		(new TimetableEntrySearcher(true)).execute();
	}

	public static final class CreateEventTT extends DialogFragment {
		private View rootView;
		private int timeslotId;
		private int dayC;

		public CreateEventTT() {
			super();
		}

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			if (rootView != null) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						getActivity());
				builder.setMessage(R.string.create_event_TT_dialog)
						.setPositiveButton(R.string.create,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										Intent intent = new Intent(rootView
												.getContext(),
												EditTimeTableActivity.class);
										intent.putExtra("timeslotId",
												timeslotId);
										intent.putExtra("dayId", dayC);
										intent.putExtra("new", true);
										intent.putExtra("toOverview", true);
										intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										startActivity(intent);
									}
								})
						.setNegativeButton(R.string.cancel,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
									}
								});
				return builder.create();
			} else {
				throw new NullPointerException();
			}
		}
	}

	protected class TimetableEntryLoader extends
			AsyncTask<Void, Void, List<TimetableEntry>> {

		@Override
		protected List<TimetableEntry> doInBackground(Void... unused) {
			System.out.println("doInBackground");
			AccessFacade accessFacade = new AccessFacade();

			List<TimetableEntry> timetableEntries = accessFacade
					.getTimetableAccess().getTimetableEntries();

			return timetableEntries;
		}

		@Override
		protected void onPostExecute(List<TimetableEntry> timetableEntries) {
			System.out.println("onPostExecute");

			for (TimetableEntry timetableEntry : timetableEntries) {
				System.out.println("for");
				if (timetableEntry.getDayOfWeek() == TimetableEntry.MONDAY) {
					if (timetableEntry.getTime() == TimetableEntry.FROM_08_TO_10) {
						prepareCell(R.id.mo810, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_10_TO_12) {
						prepareCell(R.id.mo1012, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_12_TO_14) {
						prepareCell(R.id.mo1214, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_14_TO_16) {
						prepareCell(R.id.mo1416, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_16_TO_18) {
						prepareCell(R.id.mo1618, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_18_TO_20) {
						prepareCell(R.id.mo1820, timetableEntry);
					}
				} else if (timetableEntry.getDayOfWeek() == TimetableEntry.TUESDAY) {
					if (timetableEntry.getTime() == TimetableEntry.FROM_08_TO_10) {
						prepareCell(R.id.di810, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_10_TO_12) {
						prepareCell(R.id.di1012, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_12_TO_14) {
						prepareCell(R.id.di1214, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_14_TO_16) {
						prepareCell(R.id.di1416, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_16_TO_18) {
						prepareCell(R.id.di1618, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_18_TO_20) {
						prepareCell(R.id.di1820, timetableEntry);
					}
				} else if (timetableEntry.getDayOfWeek() == TimetableEntry.WEDNESDAY) {
					if (timetableEntry.getTime() == TimetableEntry.FROM_08_TO_10) {
						prepareCell(R.id.mi810, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_10_TO_12) {
						prepareCell(R.id.mi1012, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_12_TO_14) {
						prepareCell(R.id.mi1214, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_14_TO_16) {
						prepareCell(R.id.mi1416, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_16_TO_18) {
						prepareCell(R.id.mi1618, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_18_TO_20) {
						prepareCell(R.id.mi1820, timetableEntry);
					}
				} else if (timetableEntry.getDayOfWeek() == TimetableEntry.THURSDAY) {
					if (timetableEntry.getTime() == TimetableEntry.FROM_08_TO_10) {
						prepareCell(R.id.don810, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_10_TO_12) {
						prepareCell(R.id.don1012, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_12_TO_14) {
						prepareCell(R.id.don1214, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_14_TO_16) {
						prepareCell(R.id.don1416, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_16_TO_18) {
						prepareCell(R.id.don1618, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_18_TO_20) {
						prepareCell(R.id.don1820, timetableEntry);
					}
				} else if (timetableEntry.getDayOfWeek() == TimetableEntry.FRIDAY) {
					if (timetableEntry.getTime() == TimetableEntry.FROM_08_TO_10) {
						prepareCell(R.id.fr810, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_10_TO_12) {
						prepareCell(R.id.fr1012, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_12_TO_14) {
						prepareCell(R.id.fr1214, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_14_TO_16) {
						prepareCell(R.id.fr1416, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_16_TO_18) {
						prepareCell(R.id.fr1618, timetableEntry);
					} else if (timetableEntry.getTime() == TimetableEntry.FROM_18_TO_20) {
						prepareCell(R.id.fr1820, timetableEntry);
					}
				}
			}

		}

		private void prepareCell(int id, TimetableEntry entry) {
			System.out.println("prepareCell");
			ColorHelper colorHelper = new ColorHelper();
			TextView view = (TextView) rootView.findViewById(id);
			view.setText(entry.getTitle());
			view.setBackgroundColor(colorHelper.getColor(entry.getColor())
					.getBackgroundColor());
			view.setTextColor(colorHelper.getColor(entry.getColor())
					.getFontColor());
		}
	}

	protected class TimetableEntrySearcher extends
			AsyncTask<Void, Void, List<TimetableEntry>> {

		boolean edit = false;

		private TimetableEntrySearcher(boolean edit) {
			super();
			this.edit = edit;
			System.out.println("TimetableEntrySearcher(boolean edit)");
		}

		@Override
		protected List<TimetableEntry> doInBackground(Void... unused) {
			System.out.println("TimetableEntrySearcher->doInBackground");
			AccessFacade accessFacade = new AccessFacade();

			List<TimetableEntry> timetableEntries = accessFacade
					.getTimetableAccess().getTimetableEntries();

			return timetableEntries;
		}

		@Override
		protected void onPostExecute(List<TimetableEntry> timetableEntries) {
			boolean exists = false;

			for (TimetableEntry timetableEntry : timetableEntries) {
				if (timetableEntry.getTime() == timeslotId
						&& timetableEntry.getDayOfWeek() == dayC) {
					exists = true;
					break;
				}
			}
			if (!exists) {
				System.out.println("Anlegen");
				// CreateEventTT dialog = new CreateEventTT();
				// dialog.setAttributes(rootView, timeslotId, dayC);
				// dialog.show(TimetableFragment.this.getFragmentManager(),
				// "createEventTT");
				Intent intent = new Intent(rootView.getContext(),
						EditTimeTableActivity.class);
				intent.putExtra("timeslotId", timeslotId);
				intent.putExtra("dayId", dayC);
				intent.putExtra("new", true);
				intent.putExtra("toOverview", true);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			} else {
				if (edit) {
					Intent intent = new Intent(rootView.getContext(),
							EditTimeTableActivity.class);
					intent.putExtra("timeslotId", timeslotId);
					intent.putExtra("dayId", dayC);
					intent.putExtra("new", false);
					intent.putExtra("toOverview", true);
					startActivity(intent);
				} else {
					Intent intent = new Intent(rootView.getContext(),
							DisplayTimeTableEntryActivity.class);
					intent.putExtra("dayId", dayC);
					intent.putExtra("timeslotId", timeslotId);
					startActivity(intent);
				}
			}
		}
	}

}


text:
'format es6';

export default class LogSpy {
  constructor () {
    this.debugCalled = false;
    this.debugMessage = undefined;
    this.errorCalled = false;
    this.errorMessage = undefined;
    this.errorErrorMessage = undefined;
  }

  debug ( message ) {
    this.debugCalled = true;
    this.debugMessage = message;
  }

  error ( message, error ) {
    this.errorCalled = true;
    this.errorMessage = message;

    if ( error && error.message ) {
      this.errorErrorMessage = error.message;
    }
  }

  debugCalledWith ( debugMessage ) {
    return this.debugCalled &&
      ( this.debugMessage === debugMessage );
  }

  errorCalledWith ( message, errorMessage ) {
    let result = this.errorCalled &&
      ( this.errorMessage === message );

    if ( errorMessage ) {
      result = result && ( this.errorErrorMessage === errorMessage );
    }

    return result;
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Dashboard.Logic.Telemetry
{
    using System;
    using System.Threading;

    using ViewModel;

    /// <summary>
    /// Task for updating the displayed date and time in the main view-model.
    /// </summary>
    internal class DateTimeProvider : IDisposable
    {
        /// <summary>
        /// The update period for disabling the timer
        /// </summary>
        private const int Infinite = -1;

        /// <summary>
        /// The update period in seconds
        /// </summary>
        private const int Period = 1;

        /// <summary>
        /// The timer
        /// </summary>
        private readonly Timer m_Timer;

        /// <summary>
        /// Indicates whether the instance is disposed or not
        /// </summary>
        private bool m_IsDisposed = false;

        /// <summary>
        /// Initializes an instance of the <see cref="DateTimeProvider"/>
        /// </summary>
        /// <param name="container"></param>
        public DateTimeProvider(Container container)
        {
            m_Timer = new Timer(Callback, container, Infinite, Infinite);
        }

        /// <summary>
        /// Disposes the instance
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Starts the update task
        /// </summary>
        public void Start()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException(nameof(DateTimeProvider));
            }

            m_Timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(Period));
        }

        /// <summary>
        /// Stops the update task
        /// </summary>
        public void Stop()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException(nameof(DateTimeProvider));
            }

            m_Timer.Change(Infinite, Infinite);
        }

        /// <summary>
        /// Disposes the instance references
        /// </summary>
        /// <param name="disposing"><c>true</c> to dispose references</param>
        protected virtual void Dispose(bool disposing)
        {
            if (m_IsDisposed)
            {
                return;
            }

            if (disposing)
            {
                m_Timer.Dispose();
            }
            m_IsDisposed = true;
        }

        /// <summary>
        /// The timer callback for updating the main view-model
        /// </summary>
        /// <param name="state">The IoC container for resolving needed objects</param>
        private void Callback(object state)
        {
            var container = state as Container;
            if (container == null)
            {
                return;
            }

            var viewModel = container.ResolveNamed<MainViewModel>(MainViewModel.Name);
            if (viewModel == null)
            {
                return;
            }

            DispatcherHelper.RunOnUIThread(() =>
            {
                viewModel.CurrentDateTime = DateTime.Now;
            });
        }
    }
}


text:
import {Component, OnInit, ViewChild} from "@angular/core";
import { Observable } from "rxjs";
import { Meteor } from 'meteor/meteor';

import template from "./user-box.component.html";
import style from "./user-box.component.less";

@Component({
    selector: "user-box",
    template,
    styles: [ style ]
})
export class UserBoxComponent implements OnInit {

    constructor() {

    }

    ngOnInit() {

    }
}


text:
package team111;
import battlecode.common.Direction;
import battlecode.common.MapLocation;
import battlecode.common.RobotController;
import battlecode.common.RobotType;
import battlecode.common.TerrainTile;

public class BugNav{
	public MapLocation destination;
	public MapLocation my_location;

	private Direction current_heading = Direction.NONE;
	private Direction evaluate_heading = Direction.NONE;

	static int bugging_directional_looks[] = new int[]{1,0,-1,-2,-3,-4,-5,-6,-7};
	static int non_bugging_directional_looks[] = new int[]{0,1,-1};
	private final Direction[] directions = {Direction.NORTH, Direction.NORTH_EAST, Direction.EAST, Direction.SOUTH_EAST, Direction.SOUTH, Direction.SOUTH_WEST, Direction.WEST, Direction.NORTH_WEST};

	public boolean i_am_not_bugging = true;
	public boolean i_have_stopped_bugging = false;
	public boolean i_have_started_bugging = false;
	public boolean complete = false;
	public int bugging_direction = 1;
	public int turns_bugging = 0;
	private int bugging_threshold = 20;
	public int navigator_state = 0; // 0= pre-bugging, 1 = bugging, 2 = post bugging, 3 = reached destination

	RobotController robot_controller;

	public BugNav(MapLocation the_location,MapLocation the_destination,RobotController theRC){
		my_location = the_location;
		destination = the_destination;
		current_heading = my_location.directionTo(destination);
		robot_controller = theRC;
	}

	public Direction get_next_move(){
//in-efficient overlap here if not bugging, then bugging in same 'turn'. tests 0,-1,1 twice
		if(i_am_not_bugging){
			for(int directionalOffset:non_bugging_directional_looks){
				evaluate_heading = directions[(current_heading.ordinal()+(directionalOffset*bugging_direction)+8)%8];
				if(can_move(evaluate_heading))
					return evaluate_heading;
			}
			i_have_started_bugging = true;
			navigator_state = 1;
		}
		i_am_not_bugging = false;
		turns_bugging++;
		for(int directionalOffset:bugging_directional_looks){
			evaluate_heading = directions[(current_heading.ordinal()+(directionalOffset*bugging_direction)+8)%8];
			if(can_move(evaluate_heading))
				return evaluate_heading;
		}
		evaluate_heading = Direction.NONE;
		return evaluate_heading;
	}

	public void applyMove(){
		current_heading = evaluate_heading;
		my_location = my_location.add(current_heading);
		if(my_location.equals(destination)){
			complete = true;
		}

		i_have_started_bugging = false;
		i_have_stopped_bugging = false;

		if(i_am_not_bugging){
			current_heading = my_location.directionTo(destination);
		} else{
			if (current_heading.equals(my_location.directionTo(destination))){
				i_am_not_bugging = true;
				i_have_stopped_bugging = true;
				navigator_state = 2;
				turns_bugging = 0;
			}
			if(turns_bugging > bugging_threshold)
				bugging_direction *= -1;
		}
		if(complete)
			navigator_state = 3;
	}

	public boolean can_move(Direction move_direction){
		if(terrain_is_impassable(move_direction))
			return false;
		if(space_is_occupied(move_direction))
			return false;
		return true;
	}

	public boolean terrain_is_impassable(Direction move_direction){
		MapLocation next_move = my_location.add(move_direction);
		TerrainTile test_terrain = robot_controller.senseTerrainTile(next_move);
		if(test_terrain.equals(TerrainTile.NORMAL))
			return false;
		if(test_terrain.equals(TerrainTile.OFF_MAP))
			return true;
		if(test_terrain.equals(TerrainTile.VOID) && (robot_controller.getType().equals(RobotType.DRONE) || robot_controller.getType().equals(RobotType.MISSILE)))
			return false;
		if(test_terrain.equals(TerrainTile.VOID))
			return true;

		return false;
	}

	//Not even sure if this should be checked here....
	public boolean space_is_occupied(Direction move_direction){
		try{
			return robot_controller.isLocationOccupied(my_location.add(move_direction));
		}catch(Exception e){
			System.out.println("Exception in bug space_is_occupied");
		}
		return false;
	}

	public void set_bugging_threshold(int new_threshold){
		bugging_threshold = new_threshold;
	}

	public void bug_clockwise(){
		bugging_direction = 1;
	}
	public void bug_anti_clockwise(){
		bugging_direction = -1;
	}
	public void flip_bugging_wall(){
		bugging_direction *= -1;
	}

	public boolean has_arrived_at_destination(){
		if(my_location.equals(destination))
			return true;
		return false;
	}

	public MapLocation current_evaluation_location(){
		return my_location;
	}
}


text:
import {HTTPVerb} from "../HTTPVerb";
import {RouterResourceRegistry} from "../RouterResourceRegistry";

export class HttpMethodDecorator {

    public static ANY(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.ANY});
    }

    public static CONNECT(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.CONNECT});
    }

    public static DELETE(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.DELETE});
    }

    public static GET(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.GET});
    }

    public static HEAD(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.HEAD});
    }

    public static OPTIONS(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.OPTIONS});
    }

    public static PATCH(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.PATCH});
    }

    public static POST(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.POST});
    }

    public static PUT(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.PUT});
    }

    public static TRACE(paths: string[]) {
        return HttpMethodDecorator.register.bind({paths, verb: HTTPVerb.TRACE});
    }

    private static register(this: { paths: string[], verb: HTTPVerb },
                            target: any,
                            propertyKey: string) {
        RouterResourceRegistry.registerHandler(this.verb, this.paths, target, propertyKey);
    }
}
export const ANY = HttpMethodDecorator.ANY;
export const CONNECT = HttpMethodDecorator.CONNECT;
export const DELETE = HttpMethodDecorator.DELETE;
export const GET = HttpMethodDecorator.GET;
export const HEAD = HttpMethodDecorator.HEAD;
export const OPTIONS = HttpMethodDecorator.OPTIONS;
export const PATCH = HttpMethodDecorator.PATCH;
export const POST = HttpMethodDecorator.POST;
export const PUT = HttpMethodDecorator.PUT;
export const TRACE = HttpMethodDecorator.TRACE;


text:
import Nock from '@fancy-test/nock'
import {expect, test as otest} from '@oclif/test'
import * as nock from 'nock'

import {BuildpackInstallationsStub as Stubber} from '../../helpers/buildpack-installations-stub'
nock.disableNetConnect()
const test = otest.register('nock', Nock)

describe('buildpacks:set', () => {
  describe('URL', () => {
    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api)
      Stubber.put(api, [
        'https://github.com/heroku/heroku-buildpack-ruby',
      ])
    })
    .stdout()
    .stderr()
    .command(['buildpacks:set', 'https://github.com/heroku/heroku-buildpack-ruby', '-a', 'example'])
    .it('# with no buildpacks sets the buildpack URL', ctx => {
      expect(ctx.stderr).to.equal('')
      expect(ctx.stdout).to.equal(
        `Buildpack set. Next release on example will use https://github.com/heroku/heroku-buildpack-ruby.
Run git push heroku main to create a new release using this buildpack.
`)
    })

    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api, [
        'https://github.com/foobar/foobar',
      ])
    })
    .command(['buildpacks:set', 'https://github.com/foobar/foobar', '-a', 'example'])
    .catch('The buildpack https://github.com/foobar/foobar is already set on your app.')
    .it('# errors out when already exists')

    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api, [
        'https://github.com/foo/foo',
        'https://github.com/baz/baz',
        'https://github.com/biz/biz',
      ])
      Stubber.put(api, [
        'https://github.com/bar/bar',
        'https://github.com/baz/baz',
        'https://github.com/biz/biz',
      ])
    })
    .stdout()
    .stderr()
    .command(['buildpacks:set', 'https://github.com/bar/bar', '-a', 'example'])
    .it('# overwrites in the the first when no i is passed', ctx => {
      expect(ctx.stdout).to.equal(
        `Buildpack set. Next release on example will use:
  1. https://github.com/bar/bar
  2. https://github.com/baz/baz
  3. https://github.com/biz/biz
Run git push heroku main to create a new release using these buildpacks.
`)
    })
  })

  describe('-i INDEX URL', () => {
    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api)
      Stubber.put(api, [
        'https://github.com/heroku/heroku-buildpack-ruby',
      ])
    })
    .stdout()
    .stderr()
    .command(['buildpacks:set', 'https://github.com/heroku/heroku-buildpack-ruby', '-i', '1', '-a', 'example'])
    .it('# with no buildpacks sets the buildpack URL with index', ctx => {
      expect(ctx.stderr).to.equal('')
      expect(ctx.stdout).to.equal(
        `Buildpack set. Next release on example will use https://github.com/heroku/heroku-buildpack-ruby.
Run git push heroku main to create a new release using this buildpack.
`)
    })

    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api, [
        'https://github.com/heroku/heroku-buildpack-java',
      ])
      Stubber.put(api, [
        'https://github.com/heroku/heroku-buildpack-ruby',
      ])
    })
    .stdout()
    .stderr()
    .command(['buildpacks:set', 'https://github.com/heroku/heroku-buildpack-ruby', '-i', '1', '-a', 'example'])
    .it('# with one existing buildpack successfully overwrites an existing buildpack URL at index', ctx => {
      expect(ctx.stderr).to.equal('')
      expect(ctx.stdout).to.equal(
        `Buildpack set. Next release on example will use https://github.com/heroku/heroku-buildpack-ruby.
Run git push heroku main to create a new release using this buildpack.
`)
    })
    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api, [
        'https://github.com/heroku/heroku-buildpack-ruby',
      ])
    })
    .stdout()
    .stderr()
    .command(['buildpacks:set', 'https://github.com/heroku/heroku-buildpack-ruby', '-i', '1', '-a', 'example'])
    .catch('The buildpack https://github.com/heroku/heroku-buildpack-ruby is already set on your app.')
    .it('# with one existing buildpack unsuccessfully fails if buildpack is already set')

    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api, [
        'https://github.com/heroku/heroku-buildpack-java',
        'https://github.com/heroku/heroku-buildpack-nodejs',
      ])
      Stubber.put(api, [
        'https://github.com/heroku/heroku-buildpack-ruby',
        'https://github.com/heroku/heroku-buildpack-nodejs',
      ])
    })
    .stdout()
    .stderr()
    .command(['buildpacks:set', 'https://github.com/heroku/heroku-buildpack-ruby', '-i', '1', '-a', 'example'])
    .it('# with two existing buildpacks successfully overwrites an existing buildpack URL at index', ctx => {
      expect(ctx.stderr).to.equal('')
      expect(ctx.stdout).to.equal(
        `Buildpack set. Next release on example will use:
  1. https://github.com/heroku/heroku-buildpack-ruby
  2. https://github.com/heroku/heroku-buildpack-nodejs
Run git push heroku main to create a new release using these buildpacks.
`)
    })

    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api, [
        'https://github.com/heroku/heroku-buildpack-java',
        'https://github.com/heroku/heroku-buildpack-nodejs',
      ])
      Stubber.put(api, [
        'https://github.com/heroku/heroku-buildpack-java',
        'https://github.com/heroku/heroku-buildpack-nodejs',
        'https://github.com/heroku/heroku-buildpack-ruby',
      ])
    })
    .stdout()
    .stderr()
    .command(['buildpacks:set', 'https://github.com/heroku/heroku-buildpack-ruby', '-i', '3', '-a', 'example'])
    .it('# with two existing buildpacks successfully adds buildpack URL to the end of list', ctx => {
      expect(ctx.stderr).to.equal('')
      expect(ctx.stdout).to.equal(
        `Buildpack set. Next release on example will use:
  1. https://github.com/heroku/heroku-buildpack-java
  2. https://github.com/heroku/heroku-buildpack-nodejs
  3. https://github.com/heroku/heroku-buildpack-ruby
Run git push heroku main to create a new release using these buildpacks.
`)
    })

    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api, [
        'https://github.com/heroku/heroku-buildpack-java',
        'https://github.com/heroku/heroku-buildpack-nodejs',
      ])
      Stubber.put(api, [
        'https://github.com/heroku/heroku-buildpack-java',
        'https://github.com/heroku/heroku-buildpack-nodejs',
        'https://github.com/heroku/heroku-buildpack-ruby',
      ])
    })
    .stdout()
    .stderr()
    .command(['buildpacks:set', 'https://github.com/heroku/heroku-buildpack-ruby', '-i', '99', '-a', 'example'])
    .it('# with two existing buildpacks successfully adds buildpack URL to the very end of list', ctx => {
      expect(ctx.stderr).to.equal('')
      expect(ctx.stdout).to.equal(
        `Buildpack set. Next release on example will use:
  1. https://github.com/heroku/heroku-buildpack-java
  2. https://github.com/heroku/heroku-buildpack-nodejs
  3. https://github.com/heroku/heroku-buildpack-ruby
Run git push heroku main to create a new release using these buildpacks.
`)
    })

    test
    .nock('https://api.heroku.com', (api: nock.Scope) => {
      Stubber.get(api, [
        'https://github.com/heroku/heroku-buildpack-java',
        'https://github.com/heroku/heroku-buildpack-nodejs',
      ])
    })
    .stdout()
    .stderr()
    .command(['buildpacks:set', 'https://github.com/heroku/heroku-buildpack-java', '-i', '2', '-a', 'example'])
    .catch('The buildpack https://github.com/heroku/heroku-buildpack-java is already set on your app.')
    .it('# with two existing buildpacks unsuccessfully fails if buildpack is already set')

    test
    .command(['buildpacks:set', 'https://github.com/bar/bar', '-i', 'notaninteger', '-a', 'example'])
    .catch('Expected an integer but received: notaninteger')
    .it('# returns an error message when i is not an integer')

    test
    .command(['buildpacks:set', 'https://github.com/bar/bar', '-i', '-1', '-a', 'example'])
    .catch('Invalid index. Must be greater than 0.')
    .it('# returns an error message when i < 0')

    test
    .command(['buildpacks:set', '-a', 'example'])
    .catch(`Missing 1 required arg:
buildpack  namespace/name of the buildpack
See more help with --help`)
    .it('# handles a missing buildpack URL arg')
  })
})

//
//
//
// })


text:
<?php

namespace Sylius\Bundle\PayumBundle\Payum\Stripe\Action;

use Payum\Action\PaymentAwareAction;
use Payum\Bridge\Spl\ArrayObject;
use Payum\Exception\RequestNotSupportedException;
use Payum\Request\CaptureRequest;
use Payum\Request\SecuredCaptureRequest;
use Sylius\Bundle\CoreBundle\Model\OrderInterface;
use Sylius\Bundle\PayumBundle\Payum\Request\ObtainCreditCardRequest;

class CaptureOrderUsingCreditCardAction extends PaymentAwareAction
{
    /**
     * {@inheritdoc}
     */
    public function execute($request)
    {
        /** @var $request SecuredCaptureRequest */
        if (!$this->supports($request)) {
            throw RequestNotSupportedException::createActionNotSupported($this, $request);
        }

        /** @var OrderInterface $order */
        $order = $request->getModel();
        $payment = $order->getPayment();

        $details = $payment->getDetails();
        if (empty($details)) {
            $this->payment->execute($obtainCreditCardRequest = new ObtainCreditCardRequest($order));

            $details = array(
                'card' => array(
                    'number' => $obtainCreditCardRequest->getCreditCard()->getNumber(),
                    'expiryMonth' => $obtainCreditCardRequest->getCreditCard()->getExpiryMonth(),
                    'expiryYear' => $obtainCreditCardRequest->getCreditCard()->getExpiryYear(),
                    'cvv' => $obtainCreditCardRequest->getCreditCard()->getSecurityCode()
                ),
                'amount' => number_format($order->getTotal() / 100, 2),
                'currency' => $order->getCurrency(),
            );

            $payment->setDetails($details);
        }

        try {
            $request->setModel($payment);
            $this->payment->execute($request);

            $request->setModel($order);

            //TODO: when sensitive value object is used this would be removed. Require update to payum 0.7.
            $details = $payment->getDetails();
            unset($details['card']);
            $payment->setDetails($details);
        } catch (\Exception $e) {
            //TODO: when sensitive value object is used this would be removed. Require update to payum 0.7.
            $details = $payment->getDetails();
            unset($details['card']);
            $payment->setDetails($details);

            throw $e;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function supports($request)
    {
        return
            $request instanceof SecuredCaptureRequest &&
            $request->getModel() instanceof OrderInterface
        ;
    }
}


text:
package com.entropyshift.overseer.crypto.rsa;

import com.entropyshift.overseer.crypto.key.AsymmetricKeyInformation;

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

/**
 * Created by chaitanya.m on 1/12/17.
 */
public class RsaKeyInformation extends AsymmetricKeyInformation
{
    private String id;
    private String n;
    private String e;
    private String d;
    private String p;
    private String q;
    private String dp;
    private String dq;

    public String getN()
    {
        return n;
    }

    public void setN(String n)
    {
        this.n = n;
    }

    public String getE()
    {
        return e;
    }

    public void setE(String e)
    {
        this.e = e;
    }

    public String getD()
    {
        return d;
    }

    public void setD(String d)
    {
        this.d = d;
    }

    public String getP()
    {
        return p;
    }

    public void setP(String p)
    {
        this.p = p;
    }

    public String getQ()
    {
        return q;
    }

    public void setQ(String q)
    {
        this.q = q;
    }

    public String getDp()
    {
        return dp;
    }

    public void setDp(String dp)
    {
        this.dp = dp;
    }

    public String getDq()
    {
        return dq;
    }

    public void setDq(String dq)
    {
        this.dq = dq;
    }

    public String getQi()
    {
        return qi;
    }

    public void setQi(String qi)
    {
        this.qi = qi;
    }

    private String qi;

    public String getId()
    {
        return id;
    }

    public void setId(String id)
    {
        this.id = id;
    }

    public Map<String,Object> toMap()
    {
        Map<String, Object> result = new HashMap<>();
        result.put("n", this.getN());
        result.put("e", this.getE());
        result.put("d", this.getD());
        result.put("p", this.getP());
        result.put("q", this.getQ());
        result.put("dp", this.getDp());
        result.put("dq", this.getDq());
        result.put("qi", this.getQi());
        return result;
    }
}


text:
'use strict';

const fs = require('hexo-fs');
const Promise = require('bluebird');
const { extname } = require('path');
const { magenta } = require('picocolors');

const process = (name, ctx) => {
  return Promise.filter(ctx.model(name).toArray(), asset => fs.exists(asset.source).tap(exist => {
    if (!exist) return asset.remove();
  })).map(asset => {
    const { source } = asset;
    let { path } = asset;
    const data = {
      modified: asset.modified
    };

    if (asset.renderable && ctx.render.isRenderable(path)) {
      // Replace extension name if the asset is renderable
      const filename = path.substring(0, path.length - extname(path).length);

      path = `${filename}.${ctx.render.getOutput(path)}`;

      data.data = () => ctx.render.render({
        path: source,
        toString: true
      }).catch(err => {
        ctx.log.error({err}, 'Asset render failed: %s', magenta(path));
      });
    } else {
      data.data = () => fs.createReadStream(source);
    }

    return { path, data };
  });
};

function assetGenerator() {
  return Promise.all([
    process('Asset', this),
    process('PostAsset', this)
  ]).then(data => [].concat(...data));
}

module.exports = assetGenerator;


text:
<?php
namespace IpTraceable\Fixture;

use Gedmo\IpTraceable\IpTraceable;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class TitledArticle implements IpTraceable
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(name="title", type="string", length=128)
     */
    private $title;

    /**
     * @ORM\Column(name="text", type="string", length=128)
     */
    private $text;

    /**
     * @var string $updated
     *
     * @ORM\Column(name="chtext", type="string", length=45, nullable=true)
     * @Gedmo\IpTraceable(on="change", field="text")
     */
    private $chtext;

    /**
     * @var string $chtitle
     *
     * @ORM\Column(name="chtitle", type="string", length=45, nullable=true)
     * @Gedmo\IpTraceable(on="change", field="title")
     */
    private $chtitle;

    /**
     * @param string $chtext
     */
    public function setChtext($chtext)
    {
        $this->chtext = $chtext;
    }

    /**
     * @return string
     */
    public function getChtext()
    {
        return $this->chtext;
    }

    /**
     * @param string $chtitle
     */
    public function setChtitle($chtitle)
    {
        $this->chtitle = $chtitle;
    }

    /**
     * @return string
     */
    public function getChtitle()
    {
        return $this->chtitle;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setText($text)
    {
        $this->text = $text;
    }

    public function getText()
    {
        return $this->text;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }
}


text:
from leaderBoardApp import app
app.run(debug=True)


text:
package ch.asadzia.cognitive;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.net.URI;
import ch.asadzia.cognitive.ServiceResult.Sentiment;

public class SituationAnalysis extends MsCognitiveService{
    public SituationAnalysis(File data) {
        super(data);
    }

    //An example of bad situations to look after image analysis, tagging and description operation.
    private static String badSituation[] = {"gun","violence","T-1000", "threat", "weapon"};

    //An example of good situations to look after image analysis, tagging and description operation.
    private static String goodSituation[] = {"baby","flower","happy", "friend", "fun"};

    public ServiceResult process()
    {

        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/vision/v1.0/analyze");

            builder.setParameter("visualFeatures", "Categories,Tags,Description,Faces,Adult");

            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);
            request.setHeader("Content-Type", "application/octet-stream");
            request.setHeader("Ocp-Apim-Subscription-Key", apikey);

            // Request body
            FileEntity reqEntity = new FileEntity(imageData);
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null)
            {
                String responseStr = EntityUtils.toString(entity);

                if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
                    System.err.println(responseStr);
                    return null;
                }

                ServiceResult result = translateSituation(responseStr);

                System.out.println(responseStr);

                return result;
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }

        return null;
    }

    private ServiceResult translateSituation(String string){

        for (int i = 0; i < badSituation.length; i++) {
            if(string.contains(badSituation[i])){
                return new ServiceResult(Sentiment.NEGATIVE, badSituation[i]);
            }

        }

        for (int i = 0; i < goodSituation.length; i++) {
            if(string.contains(goodSituation[i])){
                return new ServiceResult(Sentiment.POSITIVE, goodSituation[i]);
            }

        }

        return new ServiceResult(Sentiment.NEUTRAL, "Not interesting");
    }

}


text:
package org.apache.hadoop.hbase.catalog;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.NotAllMetaRegionsOnlineException;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.PairOfSameType;
import org.apache.hadoop.hbase.util.Writables;

/**
 * Writes region and assignment information to .META..
 * TODO: Put MetaReader and MetaEditor together; doesn't make sense having
 * them distinct.
 */
public class MetaEditor {
  // TODO: Strip CatalogTracker from this class.  Its all over and in the end
  // its only used to get its Configuration so we can get associated
  // Connection.
  private static final Log LOG = LogFactory.getLog(MetaEditor.class);

  private static Put makePutFromRegionInfo(HRegionInfo regionInfo)
  throws IOException {
    Put put = new Put(regionInfo.getRegionName());
    put.add(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER,
        Writables.getBytes(regionInfo));
    return put;
  }

  /**
   * Put the passed p to the .META. table.
   * @param ct CatalogTracker on whose back we will ride the edit.
   * @param p Put to add to .META.
   * @throws IOException
   */
  static void putToMetaTable(final CatalogTracker ct, final Put p)
  throws IOException {
    put(MetaReader.getMetaHTable(ct), p);
  }

  /**
   * Put the passed p to the .META. table.
   * @param ct CatalogTracker on whose back we will ride the edit.
   * @param p Put to add to .META.
   * @throws IOException
   */
  static void putToRootTable(final CatalogTracker ct, final Put p)
  throws IOException {
    put(MetaReader.getRootHTable(ct), p);
  }

  /**
   * Put the passed p to a catalog table.
   * @param ct CatalogTracker on whose back we will ride the edit.
   * @param p Put to add
   * @throws IOException
   */
  static void putToCatalogTable(final CatalogTracker ct, final Put p)
  throws IOException {
    HTable t = MetaReader.getCatalogHTable(ct, p.getRow());
    put(t, p);
  }

  /**
   * @param t Table to use (will be closed when done).
   * @param p
   * @throws IOException
   */
  private static void put(final HTable t, final Put p) throws IOException {
    try {
      t.put(p);
    } finally {
      t.close();
    }
  }

  /**
   * Put the passed ps to the .META. table.
   * @param ct CatalogTracker on whose back we will ride the edit.
   * @param ps Put to add to .META.
   * @throws IOException
   */
  static void putsToMetaTable(final CatalogTracker ct, final List<Put> ps)
  throws IOException {
    HTable t = MetaReader.getMetaHTable(ct);
    try {
      t.put(ps);
    } finally {
      t.close();
    }
  }

  /**
   * Delete the passed d from the .META. table.
   * @param ct CatalogTracker on whose back we will ride the edit.
   * @param d Delete to add to .META.
   * @throws IOException
   */
  static void deleteFromMetaTable(final CatalogTracker ct, final Delete d)
      throws IOException {
    List<Delete> dels = new ArrayList<Delete>(1);
    dels.add(d);
    deleteFromMetaTable(ct, dels);
  }

  /**
   * Delete the passed deletes from the .META. table.
   * @param ct CatalogTracker on whose back we will ride the edit.
   * @param deletes Deletes to add to .META.  This list should support #remove.
   * @throws IOException
   */
  public static void deleteFromMetaTable(final CatalogTracker ct, final List<Delete> deletes)
      throws IOException {
    HTable t = MetaReader.getMetaHTable(ct);
    try {
      t.delete(deletes);
    } finally {
      t.close();
    }
  }

  /**
   * Execute the passed mutations against .META. table.
   * @param ct CatalogTracker on whose back we will ride the edit.
   * @param mutations Puts and Deletes to execute on .META.
   * @throws IOException
   */
  static void mutateMetaTable(final CatalogTracker ct, final List<Mutation> mutations)
      throws IOException {
    HTable t = MetaReader.getMetaHTable(ct);
    try {
      t.batch(mutations);
    } catch (InterruptedException e) {
      InterruptedIOException ie = new InterruptedIOException(e.getMessage());
      ie.initCause(e);
      throw ie;
    } finally {
      t.close();
    }
  }

  /**
   * Adds a META row for the specified new region.
   * @param regionInfo region information
   * @throws IOException if problem connecting or updating meta
   */
  public static void addRegionToMeta(CatalogTracker catalogTracker,
      HRegionInfo regionInfo)
  throws IOException {
    putToMetaTable(catalogTracker, makePutFromRegionInfo(regionInfo));
    LOG.info("Added region " + regionInfo.getRegionNameAsString() + " to META");
  }

  /**
   * Adds a META row for each of the specified new regions.
   * @param catalogTracker CatalogTracker
   * @param regionInfos region information list
   * @throws IOException if problem connecting or updating meta
   */
  public static void addRegionsToMeta(CatalogTracker catalogTracker,
      List<HRegionInfo> regionInfos)
  throws IOException {
    List<Put> puts = new ArrayList<Put>();
    for (HRegionInfo regionInfo : regionInfos) {
      puts.add(makePutFromRegionInfo(regionInfo));
    }
    putsToMetaTable(catalogTracker, puts);
    LOG.info("Added " + puts.size() + " regions in META");
  }

  /**
   * Offline parent in meta.
   * Used when splitting.
   * @param catalogTracker
   * @param parent
   * @param a Split daughter region A
   * @param b Split daughter region B
   * @throws NotAllMetaRegionsOnlineException
   * @throws IOException
   */
  public static void offlineParentInMeta(CatalogTracker catalogTracker,
      HRegionInfo parent, final HRegionInfo a, final HRegionInfo b)
  throws NotAllMetaRegionsOnlineException, IOException {
    HRegionInfo copyOfParent = new HRegionInfo(parent);
    copyOfParent.setOffline(true);
    copyOfParent.setSplit(true);
    Put put = new Put(copyOfParent.getRegionName());
    addRegionInfo(put, copyOfParent);
    put.add(HConstants.CATALOG_FAMILY, HConstants.SPLITA_QUALIFIER,
      Writables.getBytes(a));
    put.add(HConstants.CATALOG_FAMILY, HConstants.SPLITB_QUALIFIER,
      Writables.getBytes(b));
    putToMetaTable(catalogTracker, put);
    LOG.info("Offlined parent region " + parent.getRegionNameAsString() +
      " in META");
  }

  public static void addDaughter(final CatalogTracker catalogTracker,
      final HRegionInfo regionInfo, final ServerName sn)
  throws NotAllMetaRegionsOnlineException, IOException {
    Put put = new Put(regionInfo.getRegionName());
    addRegionInfo(put, regionInfo);
    if (sn != null) addLocation(put, sn);
    putToMetaTable(catalogTracker, put);
    LOG.info("Added daughter " + regionInfo.getRegionNameAsString() +
      (sn == null? ", serverName=null": ", serverName=" + sn.toString()));
  }

  /**
   * Updates the location of the specified META region in ROOT to be the
   * specified server hostname and startcode.
   *

   * Uses passed catalog tracker to get a connection to the server hosting
   * ROOT and makes edits to that region.
   *
   * @param catalogTracker catalog tracker
   * @param regionInfo region to update location of
   * @param sn Server name
   * @throws IOException
   * @throws ConnectException Usually because the regionserver carrying .META.
   * is down.
   * @throws NullPointerException Because no -ROOT- server connection
   */
  public static void updateMetaLocation(CatalogTracker catalogTracker,
      HRegionInfo regionInfo, ServerName sn)
  throws IOException, ConnectException {
    updateLocation(catalogTracker, regionInfo, sn);
  }

  /**
   * Updates the location of the specified region in META to be the specified
   * server hostname and startcode.
   *

   * Uses passed catalog tracker to get a connection to the server hosting
   * META and makes edits to that region.
   *
   * @param catalogTracker catalog tracker
   * @param regionInfo region to update location of
   * @param sn Server name
   * @throws IOException
   */
  public static void updateRegionLocation(CatalogTracker catalogTracker,
      HRegionInfo regionInfo, ServerName sn)
  throws IOException {
    updateLocation(catalogTracker, regionInfo, sn);
  }

  /**
   * Updates the location of the specified region to be the specified server.
   *

   * Connects to the specified server which should be hosting the specified
   * catalog region name to perform the edit.
   *
   * @param catalogTracker
   * @param regionInfo region to update location of
   * @param sn Server name
   * @throws IOException In particular could throw {@link java.net.ConnectException}
   * if the server is down on other end.
   */
  private static void updateLocation(final CatalogTracker catalogTracker,
      HRegionInfo regionInfo, ServerName sn)
  throws IOException {
    Put put = new Put(regionInfo.getRegionName());
    addLocation(put, sn);
    putToCatalogTable(catalogTracker, put);
    LOG.info("Updated row " + regionInfo.getRegionNameAsString() +
      " with server=" + sn);
  }

  /**
   * Deletes the specified region from META.
   * @param catalogTracker
   * @param regionInfo region to be deleted from META
   * @throws IOException
   */
  public static void deleteRegion(CatalogTracker catalogTracker,
      HRegionInfo regionInfo)
  throws IOException {
    Delete delete = new Delete(regionInfo.getRegionName());
    deleteFromMetaTable(catalogTracker, delete);
    LOG.info("Deleted region " + regionInfo.getRegionNameAsString() + " from META");
  }

  /**
   * Deletes the specified regions from META.
   * @param catalogTracker
   * @param regionsInfo list of regions to be deleted from META
   * @throws IOException
   */
  public static void deleteRegions(CatalogTracker catalogTracker,
      List<HRegionInfo> regionsInfo) throws IOException {
    List<Delete> deletes = new ArrayList<Delete>(regionsInfo.size());
    for (HRegionInfo hri: regionsInfo) {
      deletes.add(new Delete(hri.getRegionName()));
    }
    deleteFromMetaTable(catalogTracker, deletes);
    LOG.info("Deleted from META, regions: " + regionsInfo);
  }

  /**
   * Adds and Removes the specified regions from .META.
   * @param catalogTracker
   * @param regionsToRemove list of regions to be deleted from META
   * @param regionsToAdd list of regions to be added to META
   * @throws IOException
   */
  public static void mutateRegions(CatalogTracker catalogTracker,
      final List<HRegionInfo> regionsToRemove, final List<HRegionInfo> regionsToAdd)
      throws IOException {
    List<Mutation> mutation = new ArrayList<Mutation>();
    if (regionsToRemove != null) {
      for (HRegionInfo hri: regionsToRemove) {
        mutation.add(new Delete(hri.getRegionName()));
      }
    }
    if (regionsToAdd != null) {
      for (HRegionInfo hri: regionsToAdd) {
        mutation.add(makePutFromRegionInfo(hri));
      }
    }
    mutateMetaTable(catalogTracker, mutation);
    if (regionsToRemove != null && regionsToRemove.size() > 0) {
      LOG.debug("Deleted from META, regions: " + regionsToRemove);
    }
    if (regionsToAdd != null && regionsToAdd.size() > 0) {
      LOG.debug("Add to META, regions: " + regionsToAdd);
    }
  }

  /**
   * Deletes daughters references in offlined split parent.
   * @param catalogTracker
   * @param parent Parent row we're to remove daughter reference from
   * @throws NotAllMetaRegionsOnlineException
   * @throws IOException
   */
  public static void deleteDaughtersReferencesInParent(CatalogTracker catalogTracker,
      final HRegionInfo parent)
  throws NotAllMetaRegionsOnlineException, IOException {
    Delete delete = new Delete(parent.getRegionName());
    delete.deleteColumns(HConstants.CATALOG_FAMILY, HConstants.SPLITA_QUALIFIER);
    delete.deleteColumns(HConstants.CATALOG_FAMILY, HConstants.SPLITB_QUALIFIER);
    deleteFromMetaTable(catalogTracker, delete);
    LOG.info("Deleted daughters references, qualifier=" + Bytes.toStringBinary(HConstants.SPLITA_QUALIFIER) +
      " and qualifier=" + Bytes.toStringBinary(HConstants.SPLITB_QUALIFIER) +
      ", from parent " + parent.getRegionNameAsString());
  }

  public static HRegionInfo getHRegionInfo(
      Result data) throws IOException {
    byte [] bytes =
      data.getValue(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER);
    if (bytes == null) return null;
    HRegionInfo info = Writables.getHRegionInfo(bytes);
    LOG.info("Current INFO from scan results = " + info);
    return info;
  }

  /**
   * Returns the daughter regions by reading from the corresponding columns of the .META. table
   * Result. If the region is not a split parent region, it returns PairOfSameType(null, null).
   */
  public static PairOfSameType<HRegionInfo> getDaughterRegions(Result data) throws IOException {
    HRegionInfo splitA = Writables.getHRegionInfoOrNull(
        data.getValue(HConstants.CATALOG_FAMILY, HConstants.SPLITA_QUALIFIER));
    HRegionInfo splitB = Writables.getHRegionInfoOrNull(
        data.getValue(HConstants.CATALOG_FAMILY, HConstants.SPLITB_QUALIFIER));
    return new PairOfSameType<HRegionInfo>(splitA, splitB);
  }

  private static Put addRegionInfo(final Put p, final HRegionInfo hri)
  throws IOException {
    p.add(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER,
        Writables.getBytes(hri));
    return p;
  }

  private static Put addLocation(final Put p, final ServerName sn) {
    p.add(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER,
      Bytes.toBytes(sn.getHostAndPort()));
    p.add(HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER,
      Bytes.toBytes(sn.getStartcode()));
    return p;
  }
}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import os

from pants_test.pants_run_integration_test import PantsRunIntegrationTest
from pants_test.subsystem.subsystem_util import subsystem_instance
from pants_test.testutils.file_test_util import exact_files

from pants.contrib.go.subsystems.go_distribution import GoDistribution

class GoThriftGenIntegrationTest(PantsRunIntegrationTest):

  def test_go_thrift_gen_simple(self):
    with self.temporary_workdir() as workdir:
      args = ['gen',
              'contrib/go/testprojects/src/thrift/thrifttest:fleem']
      pants_run = self.run_pants_with_workdir(args, workdir)
      self.assert_success(pants_run)
      with subsystem_instance(GoDistribution.Factory) as factory:
        go_dist = factory.create()
        go_dist.create_go_cmd('env', args=['GOOS']).check_output().strip()
        go_dist.create_go_cmd('env', args=['GOARCH']).check_output().strip()
        expected_files = {
          'src/go/thrifttest/duck/constants.go',
          'src/go/thrifttest/duck/ttypes.go',
        }

        # Fetch the hash for task impl version.
        go_thrift_contents = os.listdir(os.path.join(workdir, 'gen', 'go-thrift'))
        self.assertEqual(len(go_thrift_contents), 1)

        root = os.path.join(workdir, 'gen', 'go-thrift', go_thrift_contents[0],
                            'contrib.go.testprojects.src.thrift.thrifttest.fleem', 'current')
        self.assertEquals(sorted(expected_files), sorted(exact_files(root)))

  def test_go_thrift_gen_and_compile(self):
    with self.temporary_workdir() as workdir:
      args = ['compile',
              'contrib/go/testprojects/src/go/usethrift']
      pants_run = self.run_pants_with_workdir(args, workdir)

      self.assert_success(pants_run)


text:
using System;
using System.Threading.Tasks;
using Common.Logging;
using JungleBus.Interfaces;
using Messages;

namespace ConsoleTestApp.FaultHandlers
{
    public class FaultHandler2 : IHandleMessageFaults<TestMessage>
    {
        private readonly IBus _bus;
        private readonly ILog _log;
        public FaultHandler2(IBus bus, ILog log)
        {
            _bus = bus;
            _log = log;
        }

        public Task Handle(TestMessage message, Exception ex)
        {
            _log.Info("Starting message fault Handler 2");
            return Task.CompletedTask;
        }
    }
}


text:
from hsonliner.models import User, Event, Participant, Token
from hsonliner.converters import DateConverter, TimeConverter

from flask import Flask, jsonify, request, Response
from datetime import datetime, timedelta
from functools import wraps

from sqlalchemy import func

app = Flask(__name__)
app.url_map.converters['date'] = DateConverter

def session_scope():
    return app.config['SESSION'].scope()

def update_with_attrs(query, obj, converter=None, attrs=None):
    attrs = attrs or []
    for attr in attrs:
        value = query.get(attr)
        if value is None:
            continue
        if converter is not None:
            value = converter.to_python(value)
        setattr(obj, attr, value)

def authenticate():
    """
        Sends a 401 response that enables basic auth
        from http://flask.pocoo.org/snippets/8/
    """

    return Response(
        response=(
            'Could not verify your access level for that URL.\n'
            'You have to login with proper credentials',
        ),
        status=401,
        headers={'WWW-Authenticate': 'Basic realm="Token Required"'}
    )

def login_required(func):

    @wraps(func)
    def inner(*args, **kwargs):
        auth = request.authorization
        if not auth:
            return authenticate()

        token_hash = auth.password
        user_id = auth.username

        with session_scope() as session:
            token = (
                session.query(Token)
                .filter(Token.hash==token_hash)
                .filter(Token.user_id==user_id)
                .scalar()
            )
            if token is None:
                return authenticate()
            user = session.query(User).get(token.user_id)
            if user is None:
                return authenticate()
            token.expire_date += timedelta(minutes=10)
            session.add(token)

        return func(user, *args, **kwargs)

    return inner

@app.route("/login/<string:name>", methods=['PATCH'])
def login(name):
    raw_pwsd = request.json['password']
    pswd = User.generate_hash(raw_pwsd, app.config['SALT'])
    with session_scope() as session:
        user_id = (session.query(User.id)
                   .filter_by(name=name, pswd=pswd).scalar())

    if user_id is None:
        return 'user not found', 404

    token = Token(
        user_id=user_id,
        expire_date=datetime.now() + timedelta(minutes=10)
    )

    token.generate_hash(name)

    with session_scope() as session:
        session.add(token)

    return jsonify({'id': user_id, 'token': token.hash})

@app.route("/<date:date>", methods=['GET'])
def get_event(date):
    with session_scope() as session:
        event = session.query(Event).filter_by(date=date).scalar()
    if event is None:
        return 'event not found', 404
    return jsonify(event.to_dict())

@app.route("/<date:date>", methods=['PUT', 'POST'])
@login_required
def update_event(user, date):
    with session_scope() as session:
        event = session.query(Event).filter_by(date=date).scalar()
    if event is None:
        if request.method == 'PUT':
            return 'event not found', 404
        event = Event(date=date)

    query = request.json
    update_with_attrs(query, event, attrs=['topic', 'description'])
    update_with_attrs(
        query, event,
        converter=TimeConverter,
        attrs=['time_start', 'time_end']
    )

    with session_scope() as session:
        session.add(event)
    return jsonify(event.to_dict())

@app.route("/<date:date>", methods=['DELETE'])
@login_required
def delete_event(user, date):
    with session_scope() as session:
        count = session.query(Event).filter_by(date=date).delete()
    if count == 0:
        return 'event not found', 404

@app.route("/", methods=['GET'])
def get_events():
    args = request.args
    from_date = DateConverter.get(args.get('from'))
    to_date = DateConverter.get(args.get('to'))

    with session_scope() as session:
        events = session.query(Event).order_by(Event.date.desc())
        if from_date is not None:
            events = events.filter(Event.date >= from_date)
        if to_date is not None:
            events = events.filter(Event.date <= to_date)
        events = events.limit(30)
    return jsonify({
        'results': [event.to_dict() for event in events]
    })

@app.route("/<date:date>/participant/", methods=['GET'])
def get_participants(date):
    with session_scope() as session:
        participants = (
            session.query(Participant)
            .join(Participant.event)
            .filter(Event.date == date)
        )
    return jsonify({
        'results': [participant.to_dict() for participant in participants]
    })

@app.route("/<date:date>/participant/<string:name>", methods=['GET'])
def get_participant(date, name):
    with session_scope() as session:
        participant = (
            session.query(Participant)
            .join(Participant.event)
            .filter(Event.date == date, Participant.name == name)
            .scalar()
        )
    if participant is None:
        return 'participant not found', 404
    return jsonify(participant.to_dict())

@app.route("/<date:date>/participant/<string:name>", methods=['DELETE'])
@login_required
def delete_participant(user, date, name):
    with session_scope() as session:
        participant_id = (
            session.query(Participant.id)
            .join(Participant.event)
            .filter(Event.date == date, Participant.name == name)
            .scalar()
        )
        if participant_id is None:
            return 'event not found', 404
        session.query(Participant).filter_by(id=participant_id).delete()
        return '', 200

@app.route("/<date:date>/participant/<string:name>", methods=['PUT', 'POST'])
@login_required
def update_participant(user, date, name):
    with session_scope() as session:
        participant = (
            session.query(Participant)
            .join(Participant.event)
            .filter(Event.date == date, Participant.name == name)
            .scalar()
        )
        if participant is None:
            if request.method == 'PUT':
                return 'participant not found', 404
            event_id = session.query(Event.id).filter_by(date=date).scalar()
            if event_id is None:
                return 'event not found', 404
            participant = Participant(
                name=name,
                event_id=event_id,
                user_id=user.id
            )

        #if participant.user_id != user.id:
        #    return 'is not your participant, bastard!', 403

    query = request.json
    try:
        participant.will_be = Participant.REV_WILL_BE_STATES[query['will_be']]
    except KeyError:
        return 'will_be value is not correct', 400

    with session_scope() as session:
        session.add(participant)
    return jsonify(participant.to_dict())


text:
package org.keycloak.it.storage.database;

import org.keycloak.it.junit5.extension.CLIResult;
import org.keycloak.it.junit5.extension.CLITest;
import org.keycloak.it.junit5.extension.WithDatabase;

@CLITest
@WithDatabase(alias = "oracle")
public class OracleTest extends BasicDatabaseTest {

    @Override
    protected void assertWrongUsername(CLIResult cliResult) {
        cliResult.assertMessage("ORA-01017: invalid username/password; logon denied");
    }

    @Override
    protected void assertWrongPassword(CLIResult cliResult) {
        cliResult.assertMessage("ORA-01017: invalid username/password; logon denied");
    }
}


text:
```
docker build -t catchlabs/redir .
sudo docker run -p 7000:80 -v /home/zenozeng/catch/simple-redir/config:/usr/src/app/config -t catchlabs/redir
```


text:
namespace SPALM.SPSF.Library.References
{
    using System;
    using System.Collections.Specialized;
    using System.Runtime.Serialization;
    using Microsoft.Practices.Common;
    using Microsoft.Practices.RecipeFramework;

    [Serializable]
  public class SolutionFolderWSPReference : UnboundRecipeReference, IAttributesConfigurable
    {
        public SolutionFolderWSPReference(string template)
            : base(template)
        {
        }

        public override bool IsEnabledFor(object target)
        {
            Helpers.Log("SolutionFolderWSPReference");

            try
            {
                //return Helpers.IsCustomizationProject(project);
                return Helpers.IsTargetInCustomizationProject(target);
            }
            catch (Exception)
            {
            }

            return false;
        }

        public override string AppliesTo
        {
            get { return "All WSP Solutions"; }
        }

        #region ISerializable Members

        /// <summary>
        /// Required constructor for deserialization.
        /// </summary>
        protected SolutionFolderWSPReference(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
          if (this.AssetName == "PageLayout")
          {
          }
        }

        #endregion ISerializable Members

        #region IAttributesConfigurable Members

        public void Configure(StringDictionary attributes)
        {
          if (this.AssetName == "PageLayout")
          {
          }
        }

        #endregion
    }
}


text:
Dockerfiles for various desktop apps

This is the repo for various Dockerfiles as discused on https://bytestuner.com


text:
<?php
use PhlyBlog\AuthorEntity;
use PhlyBlog\EntryEntity;

$author = new AuthorEntity();
$author->setId('matthew');
$author->setName("Matthew Weier O'Phinney");
$author->setEmail('matthew@zend.com');
$author->setUrl('http://mwop.net/');

$post = new EntryEntity();
$post->setTitle('Apigility 1.0.0beta3 Released!');
$post->setAuthor($author);
$post->setDraft(false);
$post->setPublic(true);
$post->setCreated(new DateTime('2014-04-30 15:30', new DateTimezone('America/Chicago')));
$post->setUpdated(new DateTime('2014-04-30 15:30', new DateTimezone('America/Chicago')));
$body =<<<'EOS'

We are pleased to announce the immediate availability of Apigility 1.0.0beta3!

http://apigility.org/download

This is our third -- and likely last! -- beta release of Apigility! The features in this release are mainly around stabilization.

EOS;
$post->setBody($body);

$extended =<<<'EOC'

Deployment and Console

Most of the work we've performed since beta2 was on zf-deploy, our packaging/deployment tool. We made the following changes:

First, the tool can now be used both within an application, as well as a  standalone phar file. When used as a standalone phar  file, you can now self update it with the self-update command; this will  check https://packages.zendframework.com/ for any new versions, and, if found,  do an "in-place" update of the tool. (Note: the library we use that provides  this functionality often emits PHP fatal errors; in practice, however, we've  noticed that the process works even when such errors are reported.)

Second, we were not happy with the argument handling we were using, nor with  the strong coupling of console argument parsing logic with the logic consuming  the arguments. We built a small microframework around Zend\Console's  RouteMatcher subcomponent that provides more flexibility around argument  handling, and are now shipping this in the module  zf-console.

In addition to these architectural changes, we also implemented two new features in the tool:

You can specify a directory with the "local" configuration you want to use in  the deployment package via the --configs argument.

You can specify a directory containing the ZPK skeleton you wish to use when  creating a ZPK (Zend Server deployment package); this directory should contain  a deployment.xml and any scripts you will be using.

With these changes, we feel that zf-deploy is ready for inclusion in a stable Apigility release!

Documentation Updates

We've received a number of documentation improvements since beta2, and added a few documents as well.

In particular:

An error was spotted in the "HAL for RPC services" recipe that made the code  unusable.

We've documented how to use the Zend Server SDK to deploy ZPK packages.

We've added a recipe for adding Apigility modules to an existing Zend  Framework 2 application.

We've added documentation on the new zf-console module.

Beta3 Updates

In addition to the deployment and console tooling, we made the following changes:

We updated the SendResponse listener in zf-api-problem to merge in any  headers set in the application response object before sending the API Problem  response. This ensures that any previously set headers are also set -- solving  several issues observed when using third-party modules for Cross Origin  Resource Sharing (CORS), as well as HTTP authentication.

The storage adapters we ship with zf-oauth now both allow you to specify  configuration via a storage_settings key; this change allows you to specify  custom tables for both the PDO and Mongo adapters.

We've updated the "api.enable" service to ensure it works with current  versions of Apigility (and no longer raises errors!).

We no longer display a resource class in the "Source Code" tab of a service if  a corresponding class does not exist (e.g., DB-Connected resource classes are  virtual services).

We've added the option to recursively delete the directory for a service to  the Admin API; the Admin UI now presents a checkbox with this option.

We've added the option to delete an entire API. By default, this only removes  the API's module from application configuration; however, you have the option  to recursively delete the API module as well (once again presented in the  Admin UI via a checkbox).

We now generate factories for RPC controllers and REST resource classes when  creating new services. This simplifies the story for dependency injection of  these classes.

Roadmap

At this time, we feel Apigility has become very stable, and that we have addressed the most pressing usability issues. We anticipate issuing a stable release next week (week of 5 May 2014).

As noted in previous beta announcements, reaching stability is only the first step, however! Features such as "Doctrine-Connected", "Mongo-Connected", and "DB-Autodiscovery" REST services are already either implemented or will be soon, and we will be debuting these in a 1.1 version in the very near future.

EOC;
$post->setExtended($extended);

return $post;


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Attendance Schema
 */
var AttendanceSchema = new Schema({
    // Document ID of child this Attendance belongs to
    childID: {
        type: String,
        required: ''
    },
    // TODO remove this, get info from associated Child document
    childName: {
        type: String,
        required: ''
    },
    // Date this Attendance occurred
    date: {
        day: {
            type: Number,
            required: ''
        },
        month: {
            type: Number,
            required: ''
        },
        year: {
            type: Number,
            required: ''
        }
    },
    // Indicates if the child attended the class (true) or was absent (false)
    attended:{
        type: Boolean,
        default: true
    },
    // If attended is false, this indicates if the absence was scheduled (true) or unscheduled (false)
    scheduledAbsent:{
        type: Boolean,
        default: false
    },
    //so i can filter if the kid has been signed out. Ya dig?
    signedOut:{
        type: Boolean,
        default: false
    },
    // Information about the signout for this Attendance
    signout: {
        // Exact time the child was signed out
        time:{
            type: String,
            default: null
        },
        // Name of person who signed the child out
        guardian:{
            type: String,
            default: ''
        }
    },
    // Indicates if this Attendance is for an Advent (true) or a regular class (false)
    isAdvent:{
        type: Boolean,
        default: false
    },
    // If isAdvent is true, this is the ID of the associated Advent document
    adventID:{
        type: String,
        default: ''
    },
    extraClass: {
        type: Boolean,
        default: false
    }

});

mongoose.model('Attendance', AttendanceSchema);


text:
FabOverload
===========

created at the GDG DevFest Berlin Hackathon


text:
'use strict';

const fs = require('fs');
const path = require('path');

module.exports = function (context) {
  return {
    ImportDeclaration: checkImportPath,
    ExportNamedDeclaration: checkImportPath,
  };

  function checkImportPath(node) {
    const { source } = node;

    // bail if the declaration doesn't have a source, e.g. "export { foo };"
    if (!source) {
      return;
    }

    const importPath = source.value;
    if (importPath.startsWith('./') || importPath.startsWith('../')) {
      const baseDir = path.dirname(context.getFilename());
      const resolvedPath = path.resolve(baseDir, importPath);

      if (
        fs.existsSync(resolvedPath) &&
        fs.statSync(resolvedPath).isDirectory()
      ) {
        context.report({
          node: source,
          message: 'It is not allowed to import from directory',
        });
      }
    }
  }
};


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs For Class LoggerLayoutSimple</title>
			<link rel="stylesheet" href="../../media/stylesheet.css" />

Class LoggerLayoutSimple

Description

					Description |
															Methods (details)

A simple layout.

Returns the log statement in a format consisting of the  level, followed by " - " and then the message.

For example the following php and properties files

require_once dirname(__FILE__).'/../../main/php/Logger.php';

Logger::configure(dirname(__FILE__).'/../resources/layout_simple.properties');

$logger = Logger::getRootLogger();

$logger->info("Hello World!");

log4php.appender.default = LoggerAppenderEcho

log4php.appender.default.layout = LoggerLayoutSimple

log4php.rootLogger = DEBUG, default

would result in:

<samp>INFO - Hello World!</samp>

version: $Revision: 883108 $

			Located in /layouts/LoggerLayoutSimple.php (line 41)

LoggerLayout
   |
   --LoggerLayoutSimple

Method Summary

			Description |
												Methods (details)

											LoggerLayoutSimple
										__construct
										()

											string
										format
											(LoggerLoggingEvent $event)

Methods

			Description |
																Methods (details)

		Constructor __construct (line 45)

Constructor

access: public

		LoggerLayoutSimple

			__construct

				()

		format (line 57)

Returns the log statement in a format consisting of the

level, followed by " - " and then the  message. For example,  <samp>INFO - "A message"</samp>

access: public

		string

			format

					(LoggerLoggingEvent $event)

				LoggerLoggingEvent
				$event

Redefinition of:

LoggerLayout::format()

Override this method to create your own layout format.

Inherited Methods

Inherited From LoggerLayout

													LoggerLayout::activateOptions()

													LoggerLayout::format()

													LoggerLayout::getContentType()

													LoggerLayout::getFooter()

													LoggerLayout::getHeader()

		Documentation generated on Fri, 27 Nov 2009 07:44:50 +0100 by phpDocumentor 1.4.3


text:
layout: post
title: Weight Loss Goals
categories: [blog]
---

I will keep this simple, for your sake and mine. My weight loss goals are very straight forward.

Goal 1: Get to 280 lbs by March 1, 2016. This is a fairly aggressive goal considering it was set on February 18, 2016 and my start weight was 288. I think I can do it though.

Goal 2: Lose 10 lbs per month through the end of the year. This puts me at 180 lbs on January 1, 2017.

That's it. 10 pounds a month is a lot, but very doable at my weight. At the beginning of each month I will re-evaluate my goals and see if I need to make any changes.

Final Goal: Don't get discouraged and quit if I miss a goal or two. I can do this.


text:
namespace Osmosis {
namespace Chain {
namespace Remote
{

class LabelOps
{
public:
	LabelOps( TCPSocket & socket ):
		_socket( socket )
	{}

	void set( const Hash & hash, const std::string & label )
	{
		BACKTRACE_BEGIN
		unsigned char buffer[ 1024 ];
		struct Tongue::Header * header = reinterpret_cast< struct Tongue::Header * >( buffer );
		struct Tongue::Label * labelHeader = reinterpret_cast< struct Tongue::Label * >( header + 1 );
		unsigned char * labelText = reinterpret_cast< unsigned char * >( labelHeader + 1 );
		struct Tongue::Hash * rawHash = reinterpret_cast< struct Tongue::Hash * >( labelText + label.size() );
		if ( reinterpret_cast< unsigned char * >( rawHash + 1 ) > buffer + sizeof( buffer ) )
			THROW( Error, "Label too long" );
		header->opcode = static_cast< unsigned char >( Tongue::Opcode::SET_LABEL );
		ASSERT( label.size() < ( 1 << 16 ) );
		labelHeader->length = static_cast< unsigned short >( label.size() );
		memcpy( labelText, label.c_str(), label.size() );
		* rawHash = hash.raw();
		size_t size = reinterpret_cast< unsigned char * >( rawHash + 1 ) - buffer;
		_socket.sendAll( buffer, size );
		Stream::AckOps( _socket ).wait( "setting label" );
		BACKTRACE_END_VERBOSE( "Hash " << hash << " Label " << label );
	}

	Hash get( const std::string & label )
	{
		BACKTRACE_BEGIN
		sendLabelCommand( label, Tongue::Opcode::GET_LABEL );
		try {
			Hash hash( _socket.recieveAll< struct Tongue::Hash >() );
			return hash;
		} catch ( boost::system::system_error & e ) {
			if ( e.code() == boost::asio::error::eof )
				THROW( Error, "Peer terminated connection instead of sending ack, when getting label '" <<
						label << " hash: maybe the label does not exist?" );
			throw;
		}
		BACKTRACE_END_VERBOSE( "Label " << label );
	}

	std::list< std::string > list( const std::string regex )
	{
		BACKTRACE_BEGIN
		sendLabelCommand( regex, Tongue::Opcode::LIST_LABELS );
		std::list< std::string > result;
		for ( Stream::Incoming incoming( _socket ); not incoming.done(); incoming.next() ) {
			std::string label( reinterpret_cast< const char * >( incoming.buffer() ), incoming.bufferLength() );
			result.push_back( std::move( label ) );
		}
		return std::move( result );
		BACKTRACE_END_VERBOSE( "Regex " << regex );
	}

	void rename( const std::string & from, const std::string & to )
	{
		BACKTRACE_BEGIN
		sendRenameCommand( from, to );
		Stream::AckOps( _socket ).wait( "Rename operation" );
		BACKTRACE_END_VERBOSE( "From " << from << " To " << to );
	}

	void erase( const std::string & label )
	{
		BACKTRACE_BEGIN
		sendLabelCommand( label, Tongue::Opcode::ERASE_LABEL );
		Stream::AckOps( _socket ).wait( "Erased label" );
		BACKTRACE_END_VERBOSE( "Label " << label );
	}

	void sendLabelCommand( const std::string & label, Tongue::Opcode opcode )
	{
		BACKTRACE_BEGIN
		unsigned char buffer[ 1024 ];
		struct Tongue::Header * header = reinterpret_cast< struct Tongue::Header * >( buffer );
		struct Tongue::Label * labelHeader = reinterpret_cast< struct Tongue::Label * >( header + 1 );
		unsigned char * labelText = reinterpret_cast< unsigned char * >( labelHeader + 1 );
		size_t size = reinterpret_cast< unsigned char * >( labelText + label.size() ) - buffer;
		if ( size > sizeof( buffer ) )
			THROW( Error, "Label too long" );
		header->opcode = static_cast< unsigned char >( opcode );
		ASSERT( label.size() < ( 1 << 16 ) );
		labelHeader->length = static_cast< unsigned short >( label.size() );
		memcpy( labelText, label.c_str(), label.size() );
		_socket.sendAll( buffer, size );
		BACKTRACE_END_VERBOSE( "Label " << label << " Opcode " << static_cast< unsigned >( opcode ) );
	}

private:
	TCPSocket &  _socket;

	void sendRenameCommand( const std::string & from, const std::string & to )
	{
		unsigned char buffer[ 2048 ];
		struct Tongue::Header * header = reinterpret_cast< struct Tongue::Header * >( buffer );
		struct Tongue::Label * label1Header = reinterpret_cast< struct Tongue::Label * >( header + 1 );
		unsigned char * label1Text = reinterpret_cast< unsigned char * >( label1Header + 1 );
		struct Tongue::Label * label2Header = reinterpret_cast< struct Tongue::Label * >( label1Text + from.size() );
		unsigned char * label2Text = reinterpret_cast< unsigned char * >( label2Header + 1 );
		size_t size = reinterpret_cast< unsigned char * >( label2Text + to.size() ) - buffer;
		if ( size > sizeof( buffer ) )
			THROW( Error, "Label too long" );

		header->opcode = static_cast< unsigned char >( Tongue::Opcode::RENAME_LABEL );

		ASSERT( from.size() < ( 1 << 16 ) );
		label1Header->length = static_cast< unsigned short >( from.size() );
		memcpy( label1Text, from.c_str(), from.size() );

		ASSERT( to.size() < ( 1 << 16 ) );
		label2Header->length = static_cast< unsigned short >( to.size() );
		memcpy( label2Text, to.c_str(), to.size() );

		_socket.sendAll( buffer, size );
	}

	LabelOps( const LabelOps & rhs ) = delete;
	LabelOps & operator= ( const LabelOps & rhs ) = delete;
};

} // namespace Remote
} // namespace Chain
} // namespace Osmosis

#endif // __OSMOSIS_CHAIN_REMOTE_LABEL_OPS_H__


text:
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// 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.

package com.google.devtools.build.lib.rules.objc;

import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.packages.BuiltinProvider;
import com.google.devtools.build.lib.packages.NativeInfo;
import com.google.devtools.build.lib.starlarkbuildapi.apple.AppleStaticLibraryInfoApi;
import com.google.devtools.build.lib.syntax.EvalException;

/**
 * Provider containing information regarding multi-architecture Apple static libraries, as is
 * propagated by the {@code apple_static_library} rule.
 *
 *
This provider contains:
 *
 *

 *
'archive': The multi-arch archive (.a) output by apple_static_library
 *
'objc': An {@link ObjcProvider} which contains information about the transitive
 *       dependencies linked into the library, (intended so that targets may avoid linking symbols
 *       included in this archive multiple times).
 *

 */
public final class AppleStaticLibraryInfo extends NativeInfo implements AppleStaticLibraryInfoApi {

  /** Starlark constructor and identifier for AppleStaticLibraryInfo. */
  public static final Provider STARLARK_CONSTRUCTOR = new Provider();

  private final Artifact multiArchArchive;
  private final ObjcProvider depsObjcProvider;

  /**
   * Creates a new AppleStaticLibraryInfo provider that propagates the given
   * {@code apple_static_library} information.
   */
  public AppleStaticLibraryInfo(Artifact multiArchArchive,
      ObjcProvider depsObjcProvider) {
    super(STARLARK_CONSTRUCTOR);
    this.multiArchArchive = multiArchArchive;
    this.depsObjcProvider = depsObjcProvider;
  }

  @Override
  public Artifact getMultiArchArchive() {
    return multiArchArchive;
  }

  @Override
  public ObjcProvider getDepsObjcProvider() {
    return depsObjcProvider;
  }

   /**
    * Provider class for {@link AppleStaticLibraryInfo} objects.
    */
  public static class Provider extends BuiltinProvider<AppleStaticLibraryInfo>
       implements AppleStaticLibraryInfoApi.AppleStaticLibraryInfoProvider<Artifact, ObjcProvider> {
    private Provider() {
      super(STARLARK_NAME, AppleStaticLibraryInfo.class);
    }

    @Override
    public AppleStaticLibraryInfo appleStaticLibrary(
        Artifact archive, ObjcProvider objcProvider) throws EvalException {
      return new AppleStaticLibraryInfo(archive, objcProvider);
    }
  }
}