text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
using MimeTypes;
using Noteray.Code.Commands;
using Noteray.Code.Data;
using Noteray.Code.Markdown;
using Noteray.Core;
using Noteray.Core.DataCarriers;
using Noteray.Core.Exceptions;
using Noteray.Core.Helpers;
using Noteray.ViewModels;

namespace Noteray.Windows
{
	/// <summary>
	/// Interaction logic for NoteEditor.xaml
	/// </summary>
	public partial class NoteEditor
	{
		private const string MdImageFormat = "![{1}]({0})";
		private const string ImageFormat = "<img src=\"{0}\" alt=\"{1}\" />";

		private Note _editedNote;
		private readonly List<NoteFile> _newFiles = new List<NoteFile>();
		private readonly DispatcherTimer _messageClearTimer;
		private bool _textChanged;

		public NoteFileCommand InsertAsImgCommand { get; set; }
		public NoteFileCommand InsertAsMdCommand { get; set; }
		public DocumentEntitiy CurrentEntity { get; set; }

		private readonly List<DocumentEntitiy> _documentEntitiys;

		private Note EditedNote => _editedNote ?? (_editedNote = ((NoteEditorViewModel)DataContext).Note);

		public NoteEditorViewModel Model => ((NoteEditorViewModel)DataContext);

		public NoteEditor()
		{
			InitializeComponent();

			//CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, SaveNote));
			CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, CloseEditor));

			InsertAsImgCommand = new NoteFileCommand(InsertNoteFileAsImg);
			InsertAsMdCommand = new NoteFileCommand(InsertNoteFileAsMd);

			_messageClearTimer = new DispatcherTimer();
			_messageClearTimer.Tick += ClearMessage;
			_messageClearTimer.Interval = TimeSpan.FromMilliseconds(2500);

			_documentEntitiys = new List<DocumentEntitiy>();
			var documentEntitiesTimer = new DispatcherTimer();
			documentEntitiesTimer.Tick += UpdateDocumentEntities;
			documentEntitiesTimer.Interval = TimeSpan.FromMilliseconds(1000);
			documentEntitiesTimer.Start();

			Closing += NoteEditorClosing;

			MarkdownText.Focus();
		}

		private void UpdateDocumentEntities(object sender, EventArgs e)
		{
			if (!_textChanged)
				return;

			_textChanged = false;
			_documentEntitiys.Clear();

			MatchEntities(RegularExpressions.ImageAnchorInline, EntityType.Image);
			//MatchEntities(RegularExpressions.ListTopLevel, EntityType.List);
			//MatchEntities(RegularExpressions.ListNested, EntityType.List);
			MatchEntities(RegularExpressions.SimpleAnchorInline, EntityType.SimpleAnchor);
			MatchEntities(RegularExpressions.AnchorInline, EntityType.Anchor);
			MatchEntities(RegularExpressions.Table, EntityType.Table);
			MatchEntities(RegularExpressions.TableNoDelimiter, EntityType.Table);
		}

		private void MatchEntities(Regex reg, EntityType type)
		{
			var matches = reg.Matches(MarkdownText.Text);
			foreach (Match match in matches)
			{
				if (match.Success)
				{
					//DocumentEntitiy ent = new DocumentEntitiy();
					//ent.Match = match;
					//ent.Type = type;
					//_documentEntitiys.Add(ent);
				}
			}
		}

		void NoteEditorClosing(object sender, CancelEventArgs e)
		{

		}

		void ClearMessage(object sender, EventArgs e)
		{
			Dispatcher.Invoke(() =>
			{
				_messageClearTimer.Stop();
				MessageTextBlock.Text = string.Empty;
			});
		}

		private void ShowMessage(string message)
		{
			MessageTextBlock.Text = message;
			_messageClearTimer.Start();
		}

		private void FilesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.Action == NotifyCollectionChangedAction.Add)
			{
				_newFiles.AddRange(e.NewItems.Cast<NoteFile>());
			}
			else if (e.Action == NotifyCollectionChangedAction.Remove)
			{
				foreach (NoteFile noteFile in e.NewItems.Cast<NoteFile>())
				{
					int index = _newFiles.IndexOf(noteFile);
					if (index > -1)
						_newFiles.RemoveAt(index);
				}
			}
		}

		private bool InsertNoteFileAsImg(NoteFile arg)
		{
			InsertImage(arg, ImageFormat);
			return true;
		}

		private bool InsertNoteFileAsMd(NoteFile arg)
		{
			InsertImage(arg, MdImageFormat);
			return true;
		}

		private void DragNoteFile(object sender, MouseButtonEventArgs e)
		{
			Image img = (Image)sender;
			NoteFile nf = img.Tag as NoteFile;
			if (nf == null)
				return;

			DataObject data = new DataObject(typeof(NoteFile), nf);
			DragDrop.DoDragDrop(img, data, DragDropEffects.Copy);
		}

		private void InsertImage(NoteFile nf, string format)
		{
			if (nf != null)
			{
				string content = string.Format(format, nf.FileName, nf.Name);
				MarkdownText.SelectedText = content;
			}
		}

		private void CloseEditor(object sender, ExecutedRoutedEventArgs e)
		{
			if (_newFiles.Any())
			{

			}

			Close();
		}

		private void SaveNote()
		{
			EditedNote.SecureText = MarkdownText.Text;

			//TODO: Implement http://stackoverflow.com/questions/50744/wait-until-file-is-unlocked-in-net, and show progress window explaining why, dropbox has locked the file for sync

			try
			{
				EditedNote.Save();
				Close();
			}
			catch (SaveException saveNoteException)
			{
				Note n = (Note)saveNoteException.UnsavedObject;
				MessageBox.Show("Unable to save " + n.Name + "\n\nCould not get access to file. \nDropBox has probably locked it when syncing, please try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
			}
			catch (Exception ex)
			{
				MessageBox.Show("Unable to save note.\n\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}

		private void MetroWindowLoaded(object sender, RoutedEventArgs e)
		{
			MarkdownText.Text = Model.Text;
			EditedNote.Files.CollectionChanged += FilesCollectionChanged;
		}

		private void ToolbarButtonClick(object sender, RoutedEventArgs e)
		{
			Button button = (Button)e.Source;
			string command = button.CommandParameter.ToString();

			MarkdownText.Text = ToggleFormatting(MarkdownText.Text, "**", "**", MarkdownText.SelectionStart, MarkdownText.SelectionLength);
			return;

			//string format = string.Empty, defaultText = string.Empty;
			//switch (command)
			//{
			//	case "Bold":
			//		format = "**{0}**";
			//		defaultText = string.Format(format, "Bold");

			//		return;
			//		break;
			//	case "Italic":
			//		format = "*{0}*";
			//		defaultText = string.Format(format, "Italic");
			//		break;
			//	case "Strike":
			//		format = "~~{0}~~";
			//		defaultText = string.Format(format, "Strikethrough");
			//		break;
			//	case "Code":
			//		format = "```" + Environment.NewLine + "{0}" + Environment.NewLine + "```";
			//		defaultText = string.Format(format, "function(){ alert('Bananas!'); }");
			//		break;
			//	case "Image":
			//		defaultText = string.Format(MdImageFormat, "Image url", string.Empty);
			//		break;
			//	case "H1":
			//		format = "{0}" + Environment.NewLine + "==";
			//		defaultText = string.Format(format, "Heading");
			//		break;
			//	case "H2":
			//		format = "{0}" + Environment.NewLine + "--";
			//		defaultText = string.Format(format, "Heading");
			//		break;
			//	case "H3":
			//		format = "### {0}";
			//		defaultText = string.Format(format, "Heading");
			//		break;
			//}

			//SurroundSelection(format, defaultText);
		}

		private void SurroundSelection(string format, string defaultValue)
		{
			if (MarkdownText.SelectionStart > -1 && MarkdownText.SelectionLength > 0)
			{
				MarkdownText.SelectedText = string.Format(format, MarkdownText.SelectedText);
			}
			else
			{
				MarkdownText.SelectedText = defaultValue;
				// Todo: change selection
			}
		}

		private string ToggleFormatting(string text, string startFormat, string endFormat, int selectionStart, int selectionLength)
		{
			string expression =
				$@"{startFormat}
					(?:      # Start of non-capturing group that matches...
					 (? !{startFormat}) # (if startFormat can't be matched here)
					 .       # any character
					) *?      # Repeat any number of times, as few as possible
					{endFormat}";
			Regex reg = new Regex(expression);

			MatchCollection matches = reg.Matches(text);
			if (matches.Count > 0)
			{
				foreach (Match m in matches)
				{
					if (m.Index >= selectionStart && (m.Index + m.Length) <= (selectionStart + selectionLength))
					{
						if (m.Value.StartsWith(startFormat) && m.Value.EndsWith(endFormat))
						{
							text = text.Remove(selectionStart, selectionLength);
							text = text.Insert(selectionStart, m.Value.Replace(startFormat, string.Empty).Replace(endFormat, string.Empty));
							return text;
						}
					}
				}
			}

			string selection = text.Substring(selectionStart, selectionLength);
			text = text.Remove(selectionStart, selectionLength);
			text = text.Insert(selectionStart, startFormat + selection + endFormat);
			return text;
		}

		private void StripHtmlButtonClick(object sender, RoutedEventArgs e)
		{
			if (string.IsNullOrEmpty(MarkdownText.SelectedText))
				MarkdownText.SelectAll();

			var textToStrip = MarkdownText.SelectedText;

			const string acceptable = "img|a";
			const string stringPattern = @"</?(?(?=" + acceptable + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:(["",']?).*?\1?)?)*\s*/?>";
			string result = Regex.Replace(textToStrip, stringPattern, string.Empty);

			MarkdownText.SelectedText = result;
		}

		private void ConvertToMarkdownButtonClick(object sender, RoutedEventArgs e)
		{
			MarkdownText.Text = ConvertToMd(MarkdownText.Text);
		}

		public string ConvertToMd(string source)
		{
			string processName = Hub.Instance.Settings.PandocPath;
			string args = Hub.Instance.Settings.PandocParameters;

			if (string.IsNullOrEmpty(processName) || string.IsNullOrEmpty(args))
			{
				MessageBox.Show("No settings for pandoc found.");
				return source;
			}

			ProcessStartInfo psi = new ProcessStartInfo(processName, args)
			{
				RedirectStandardOutput = true,
				RedirectStandardInput = true,
				UseShellExecute = false
			};

			Process p = new Process { StartInfo = psi };
			psi.UseShellExecute = false;
			p.Start();

			string outputString;
			byte[] inputBuffer = Encoding.UTF8.GetBytes(source);
			p.StandardInput.BaseStream.Write(inputBuffer, 0, inputBuffer.Length);
			p.StandardInput.Close();

			p.WaitForExit(2000);
			using (StreamReader sr = new StreamReader(p.StandardOutput.BaseStream))
			{
				outputString = sr.ReadToEnd();
			}

			return outputString;
		}

		private void MarkdownText_OnKeyDown(object sender, KeyEventArgs e)
		{
			if (Keyboard.Modifiers == ModifierKeys.Control)
			{
				if (e.Key == Key.B)
					ClickButton(BoldButton);
				else if (e.Key == Key.I)
					ClickButton(ItalicButton);
				else if (e.Key == Key.S)
					SaveNote();
			}

			#region -- wack --

			//switch (e.SystemKey)
			//{
			//	case (Key.Back | Key.LeftCtrl):
			//		#region -- wack --
			//		//e.SuppressKeyPress = true;
			//		//int i;
			//		//if (textbox.SelectionStart.Equals(0))
			//		//{
			//		//	return;
			//		//}
			//		//int space = textbox.Text.LastIndexOf(' ', textbox.SelectionStart - 1);
			//		//int line = textbox.Text.LastIndexOf("\r\n", textbox.SelectionStart - 1);
			//		//if (space > line)
			//		//{
			//		//	i = space;
			//		//}
			//		//else
			//		//{
			//		//	i = line;
			//		//}
			//		//if (i > -1)
			//		//{
			//		//	while (textbox.Text.Substring(i - 1, 1).Equals(' '))
			//		//	{
			//		//		if (i.Equals(0))
			//		//		{
			//		//			break;
			//		//		}
			//		//		i--;
			//		//	}
			//		//	textbox.Text = textbox.Text.Substring(0, i) + textbox.Text.Substring(textbox.SelectionStart);
			//		//	textbox.SelectionStart = i;
			//		//}
			//		//else if (i.Equals(-1))
			//		//{
			//		//	textbox.Text = textbox.Text.Substring(textbox.SelectionStart);
			//		//}
			//		#endregion
			//		SendKeys.SendWait("^+{LEFT}{BACKSPACE}");
			//		e.Handled = true;
			//		e.SuppressKeyPress = true;
			//		break;
			//	case (Keys.Control | Keys.A):
			//		textbox.SelectAll();
			//		e.Handled = true;
			//		e.SuppressKeyPress = true;
			//		break;
			//	case (Keys.Control | Keys.S):
			//		SaveButton_Click(sender, e);
			//		break;
			//	case (Keys.Escape):
			//		if (TableCreatorPanel.Visible)
			//		{
			//			TableCreatorPanel.Visible = false;
			//			e.Handled = true;
			//			e.SuppressKeyPress = true;
			//		}
			//		break;

			//	case (Keys.Control | Keys.B):
			//		Bold_Click(sender, e);
			//		e.Handled = true;
			//		e.SuppressKeyPress = true;
			//		break;
			//	case (Keys.Control | Keys.I):
			//		Italic_Click(sender, e);
			//		e.Handled = true;
			//		e.SuppressKeyPress = true;
			//		break;
			//	case (Keys.Control | Keys.H):
			//		HeadingButton_Click(sender, e);
			//		e.Handled = true;
			//		e.SuppressKeyPress = true;
			//		break;
			//	case (Keys.Control | Keys.T):
			//		ShowTableCreatorPanel(true);
			//		e.Handled = true;
			//		e.SuppressKeyPress = true;
			//		break;
			//}

			//if (PreviewInNoteEditor.Checked)
			//{
			//	if (OnTextUpdated != null)
			//		OnTextUpdated(MarkdownText.Text);
			//}

			#endregion
		}

		private void ClickButton(Button target)
		{
			ButtonAutomationPeer peer = new ButtonAutomationPeer(target);
			IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
			if (invokeProv != null)
				invokeProv.Invoke();
		}

		private void MarkdownText_OnDragOver(object sender, DragEventArgs e)
		{
			//if (!e.Data.GetDataPresent(DataFormats.FileDrop) && !e.Data.GetDataPresent(typeof(NoteFile)))
			//	return;

			//Point p = e.GetPosition(MarkdownText);
			//int charPos = MarkdownText.GetCharacterIndexFromPoint(p, true);

			//int line = MarkdownText.GetLineIndexFromCharacterIndex(charPos);

			//string lineText = MarkdownText.GetLineText(line);

			//bool emptyLine = string.IsNullOrWhiteSpace(lineText.Trim());
			//int lineMiddle = lineText.Length / 2;
			//int col = charPos - MarkdownText.GetCharacterIndexFromLineIndex(line);

			//if (!emptyLine && col > lineMiddle)
			//{
			//	Rect r = MarkdownText.GetRectFromCharacterIndex(charPos, false);
			//	Point winPoint = MarkdownText.PointToScreen(r.TopRight);
			//	if (winPoint.Y > p.Y)
			//		charPos++;
			//}

			//MarkdownText.SelectionStart = charPos;
			//MarkdownText.SelectionLength = 0;
			//MarkdownText.Focus();

			//e.Effects = DragDropEffects.Copy;
			//e.Handled = true;
		}

		private void MarkdownText_OnDragEnter(object sender, DragEventArgs e)
		{
			e.Effects = DragDropEffects.All;
		}

		private void MarkdownText_OnDragLeave(object sender, DragEventArgs e)
		{
			e.Effects = DragDropEffects.All;
		}

		private void MarkdownText_OnPreviewDrop(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
			{
				string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
				AddFiles(files);
			}
			else if (e.Data.GetDataPresent(typeof(NoteFile)))
			{
				NoteFile nf = e.Data.GetData(typeof(NoteFile)) as NoteFile;
				if (nf != null)
				{
					MarkdownText.SelectedText = string.Format(MdImageFormat, nf.FileName, nf.Name);
				}
			}
		}

		private void AddFiles(string[] files)
		{
			StringBuilder builder = new StringBuilder();
			foreach (string file in files)
			{
				FileInfo fi = new FileInfo(file);
				if (!fi.Exists)
					continue;

				byte[] bytes = File.ReadAllBytes(file);
				string mime = MimeTypeMap.GetMimeType(fi.Extension);
				NoteFile nf = NoteFile.Create(null, mime, bytes, EditedNote);
				builder.AppendFormat(MdImageFormat, nf.FileName, nf.Name);
				_newFiles.Add(nf);
			}

			MarkdownText.SelectedText = builder.ToString();
		}

		private void NoteEditor_OnClosing(object sender, CancelEventArgs e)
		{
			EditedNote.Files.CollectionChanged -= FilesCollectionChanged;
		}

		private void AddImageAsFileToNote_OnClick(object sender, RoutedEventArgs e)
		{
			string mime = null;
			byte[] bytes = null;
			if (MarkdownText.SelectedText.StartsWith("data:image"))
			{
				string[] chunks = MarkdownText.SelectedText.Split(',');
				if (chunks.Length == 2)
				{
					bytes = Convert.FromBase64String(chunks[1]);
					mime = chunks[0].Replace("data:", string.Empty).Replace(";base64", string.Empty);
				}
			}
			else
			{
				Uri uri;
				if (Uri.TryCreate(MarkdownText.SelectedText, UriKind.Absolute, out uri))
				{
					try
					{
						WebClient webClient = new WebClient();
						bytes = webClient.DownloadData(uri);
						mime = MimeType.GetMimeType(bytes);
					}
					catch (Exception)
					{
						// ignored
					}
				}
			}

			if (bytes != null && bytes.Length > 0 && mime != null)
			{
				NoteFile nf = NoteFile.Create(null, mime, bytes, EditedNote);
				MarkdownText.SelectedText = nf.Name;

				_newFiles.Add(nf);
			}
			else
			{
				ShowMessage("Unable to load image.");
			}
		}

		void MarkdownText_OnFilePasted(FileInfo fi)
		{
			byte[] bytes = File.ReadAllBytes(fi.FullName);
			string mime = MimeType.GetMimeType(bytes);
			NoteFile nf = NoteFile.Create(fi.Name, mime, bytes, EditedNote, fi.Extension);

			_newFiles.Add(nf);

			if (MimeType.IsImageExtension(fi.Extension))
			{
				InsertImage(nf, MdImageFormat);
			}
			else
			{
				MarkdownText.SelectedText = string.Format("[{0}](file:///{1})", nf.Name, nf.FullName);
			}
		}

		void MarkdownText_OnHyperLinkPasted(Uri uri)
		{
			MarkdownText.SelectedText = string.Format("<{0}>", uri.OriginalString);
		}

		void MarkdownText_OnImagePasted(System.Drawing.Image image, string fileName)
		{
			if (image == null)
				return;

			using (var ms = new MemoryStream())
			{
				image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
				byte[] bytes = ms.ToArray();
				string mime = MimeType.GetMimeType(bytes);
				if (bytes.Length > 0 && mime != null)
				{
					NoteFile nf = NoteFile.Create(fileName, mime, bytes, EditedNote);
					_newFiles.Add(nf);

					InsertImage(nf, MdImageFormat);
				}
			}
		}

		private void MarkdownText_OnTextChanged(object sender, TextChangedEventArgs e)
		{
			_textChanged = true;
		}

		private void MarkdownText_OnSelectionChanged(object sender, RoutedEventArgs e)
		{
			HideAllPopups();
			EditTableButton.IsEnabled = false;

			if (_documentEntitiys.Any())
			{
				DocumentEntitiy ent = _documentEntitiys.FirstOrDefault(en => en.InRange(MarkdownText.CaretOffset));
				if (ent != null)
				{
					CurrentEntity = ent;
					if (ent.Type == EntityType.Anchor)
					{
						if (LinkToolbarPopup != null)
						{
							PositionPopup(LinkToolbarPopup);
							LinkToolbarPopup.IsOpen = true;
						}
					}
					else if (ent.Type == EntityType.Table)
					{
						EditTableButton.IsEnabled = true;
					}
				}
			}
		}

		private void PositionPopup(Popup pop)
		{
			//Rect r = MarkdownText.GetRectFromCharacterIndex(MarkdownText.CaretIndex);
			//pop.PlacementRectangle = r;
		}

		private void HideAllPopups()
		{
			LinkToolbarPopup.IsOpen = false;
		}

		private void EditTableButton_OnClick(object sender, RoutedEventArgs e)
		{
			if (CurrentEntity != null && CurrentEntity.Type == EntityType.Table)
			{
				//string headString = CurrentEntity.Match.Groups[1].Value;
				//string textAlign = CurrentEntity.Match.Groups[2].Value;
				//string rowsString = CurrentEntity.Match.Groups[3].Value;
			}
		}
	}
}


text:
#include "talk/app/webrtc/mediastreamtrackproxy.h"

#include "talk/media/base/videocapturer.h"

namespace {

enum {
  MSG_REGISTER_OBSERVER = 1,
  MSG_UNREGISTER_OBSERVER,
  MSG_LABEL,
  MSG_ENABLED,
  MSG_SET_ENABLED,
  MSG_STATE,
  MSG_GET_AUDIOSOURCE,
  MSG_GET_VIDEOSOURCE,
  MSG_ADD_VIDEORENDERER,
  MSG_REMOVE_VIDEORENDERER,
  MSG_GET_VIDEOFRAMEINPUT,
};

typedef talk_base::TypedMessageData<std::string*> LabelMessageData;
typedef talk_base::TypedMessageData<webrtc::ObserverInterface*>
    ObserverMessageData;
typedef talk_base::TypedMessageData
    <webrtc::MediaStreamTrackInterface::TrackState> TrackStateMessageData;
typedef talk_base::TypedMessageData<bool> EnableMessageData;
typedef talk_base::TypedMessageData<webrtc::VideoRendererInterface*>
    VideoRendererInterfaceMessageData;
typedef talk_base::TypedMessageData<cricket::VideoRenderer*>
    VideoFrameInputMessageData;

class AudioSourceMessageData : public talk_base::MessageData {
 public:
  talk_base::scoped_refptr<webrtc::AudioSourceInterface> audio_source_;
};

class VideoSourceMessageData : public talk_base::MessageData {
 public:
  talk_base::scoped_refptr<webrtc::VideoSourceInterface> video_source_;
};

}  // namespace anonymous

namespace webrtc {

template <class T>
MediaStreamTrackProxy<T>::MediaStreamTrackProxy(
    T* track, talk_base::Thread* signaling_thread)
    : signaling_thread_(signaling_thread),
      track_(track) {
}

template <class T>
std::string MediaStreamTrackProxy<T>::kind() const {
  return track_->kind();
}

template <class T>
std::string MediaStreamTrackProxy<T>::label() const {
  if (!signaling_thread_->IsCurrent()) {
    std::string label;
    LabelMessageData msg(&label);
    Send(MSG_LABEL, &msg);
    return label;
  }
  return track_->label();
}

template <class T>
MediaStreamTrackInterface::TrackState MediaStreamTrackProxy<T>::state() const {
  if (!signaling_thread_->IsCurrent()) {
    TrackStateMessageData msg(MediaStreamTrackInterface::kInitializing);
    Send(MSG_STATE, &msg);
    return msg.data();
  }
  return track_->state();
}

template <class T>
bool MediaStreamTrackProxy<T>::enabled() const {
  if (!signaling_thread_->IsCurrent()) {
    EnableMessageData msg(false);
    Send(MSG_ENABLED, &msg);
    return msg.data();
  }
  return track_->enabled();
}

template <class T>
bool MediaStreamTrackProxy<T>::set_enabled(bool enable) {
  if (!signaling_thread_->IsCurrent()) {
    EnableMessageData msg(enable);
    Send(MSG_SET_ENABLED, &msg);
    return msg.data();
  }
  return track_->set_enabled(enable);
}

template <class T>
bool MediaStreamTrackProxy<T>::set_state(
    MediaStreamTrackInterface::TrackState new_state) {
  if (!signaling_thread_->IsCurrent()) {
    // State should only be allowed to be changed from the signaling thread.
    ASSERT(!"Not Allowed!");
    return false;
  }
  return track_->set_state(new_state);
}

template <class T>
void MediaStreamTrackProxy<T>::RegisterObserver(ObserverInterface* observer) {
  if (!signaling_thread_->IsCurrent()) {
    ObserverMessageData msg(observer);
    Send(MSG_REGISTER_OBSERVER, &msg);
    return;
  }
  track_->RegisterObserver(observer);
}

template <class T>
void MediaStreamTrackProxy<T>::UnregisterObserver(ObserverInterface* observer) {
  if (!signaling_thread_->IsCurrent()) {
    ObserverMessageData msg(observer);
    Send(MSG_UNREGISTER_OBSERVER, &msg);
    return;
  }
  track_->UnregisterObserver(observer);
}

template <class T>
void MediaStreamTrackProxy<T>::Send(uint32 id,
                                    talk_base::MessageData* data) const {
  signaling_thread_->Send(const_cast<MediaStreamTrackProxy<T>*>(this), id,
                          data);
}

template <class T>
bool MediaStreamTrackProxy<T>::HandleMessage(talk_base::Message* msg) {
  talk_base::MessageData* data = msg->pdata;
  switch (msg->message_id) {
    case MSG_REGISTER_OBSERVER: {
      ObserverMessageData* observer = static_cast<ObserverMessageData*>(data);
      track_->RegisterObserver(observer->data());
      return true;
      break;
    }
    case MSG_UNREGISTER_OBSERVER: {
      ObserverMessageData* observer = static_cast<ObserverMessageData*>(data);
      track_->UnregisterObserver(observer->data());
      return true;
      break;
    }
    case MSG_LABEL: {
      LabelMessageData* label = static_cast<LabelMessageData*>(data);
      *(label->data()) = track_->label();
      return true;
    }
    case MSG_SET_ENABLED: {
      EnableMessageData* enabled = static_cast<EnableMessageData*>(data);
      enabled->data() = track_->set_enabled(enabled->data());
      return true;
      break;
    }
    case MSG_ENABLED: {
      EnableMessageData* enabled = static_cast<EnableMessageData*>(data);
      enabled->data() = track_->enabled();
      return true;
      break;
    }
    case MSG_STATE: {
      TrackStateMessageData* state = static_cast<TrackStateMessageData*>(data);
      state->data() = track_->state();
      return true;
      break;
    }
    default:
      return false;
  }
}

AudioTrackProxy::AudioTrackProxy(AudioTrackInterface* track,
                                 talk_base::Thread* signaling_thread)
    : MediaStreamTrackProxy<AudioTrackInterface>(track,
                                                 signaling_thread) {
}

AudioSourceInterface* AudioTrackProxy::GetSource() const {
  if (!signaling_thread_->IsCurrent()) {
    AudioSourceMessageData msg;
    Send(MSG_GET_AUDIOSOURCE, &msg);
    return msg.audio_source_;
  }
  return track_->GetSource();
}

void AudioTrackProxy::OnMessage(talk_base::Message* msg) {
  if (!HandleMessage(msg)) {
    if (msg->message_id == MSG_GET_AUDIOSOURCE) {
      AudioSourceMessageData* audio_source =
          static_cast<AudioSourceMessageData*>(msg->pdata);
      audio_source->audio_source_ = track_->GetSource();
      return;
    }
    ASSERT(!"Not Implemented!");
  }
}

talk_base::scoped_refptr<AudioTrackProxy> AudioTrackProxy::Create(
    AudioTrackInterface* track,
    talk_base::Thread* signaling_thread) {
  talk_base::RefCountedObject<AudioTrackProxy>* proxy =
      new talk_base::RefCountedObject<AudioTrackProxy>(track,
                                                       signaling_thread);
  return proxy;
}

VideoTrackProxy::VideoTrackProxy(VideoTrackInterface* video_track,
                                 talk_base::Thread* signaling_thread)
    : MediaStreamTrackProxy<VideoTrackInterface>(video_track,
                                                 signaling_thread) {
}

void VideoTrackProxy::AddRenderer(VideoRendererInterface* renderer) {
  if (!signaling_thread_->IsCurrent()) {
    VideoRendererInterfaceMessageData msg(renderer);
    Send(MSG_ADD_VIDEORENDERER, &msg);
    return;
  }
  track_->AddRenderer(renderer);
}

void VideoTrackProxy::RemoveRenderer(VideoRendererInterface* renderer) {
  if (!signaling_thread_->IsCurrent()) {
    VideoRendererInterfaceMessageData msg(renderer);
    Send(MSG_REMOVE_VIDEORENDERER, &msg);
    return;
  }
  track_->RemoveRenderer(renderer);
}

cricket::VideoRenderer* VideoTrackProxy::FrameInput() {
  if (!signaling_thread_->IsCurrent()) {
    VideoFrameInputMessageData msg(NULL);
    Send(MSG_GET_VIDEOFRAMEINPUT, &msg);
    return msg.data();
  }
  return track_->FrameInput();
}

VideoSourceInterface* VideoTrackProxy::GetSource() const {
  if (!signaling_thread_->IsCurrent()) {
    VideoSourceMessageData msg;
    Send(MSG_GET_VIDEOSOURCE, &msg);
    return msg.video_source_;
  }
  return track_->GetSource();
}

void VideoTrackProxy::OnMessage(talk_base::Message* msg) {
  if (!MediaStreamTrackProxy<VideoTrackInterface>::HandleMessage(msg)) {
    switch (msg->message_id) {
       case  MSG_GET_VIDEOSOURCE: {
        VideoSourceMessageData* video_source =
            static_cast<VideoSourceMessageData*>(msg->pdata);
        video_source->video_source_ = track_->GetSource();
        break;
      }
      case MSG_ADD_VIDEORENDERER: {
        VideoRendererInterfaceMessageData* renderer =
            static_cast<VideoRendererInterfaceMessageData*>(msg->pdata);
        track_->AddRenderer(renderer->data());
        break;
      }
      case MSG_REMOVE_VIDEORENDERER: {
        VideoRendererInterfaceMessageData* message =
            static_cast<VideoRendererInterfaceMessageData*>(msg->pdata);
        track_->RemoveRenderer(message->data());
        break;
      }
      case MSG_GET_VIDEOFRAMEINPUT: {
        VideoFrameInputMessageData* message =
            static_cast<VideoFrameInputMessageData*>(msg->pdata);
        message->data() = track_->FrameInput();
        break;
      }
    default:
      ASSERT(!"Not Implemented!");
      break;
    }
  }
}

talk_base::scoped_refptr<VideoTrackProxy> VideoTrackProxy::Create(
    VideoTrackInterface* track,
    talk_base::Thread* signaling_thread) {
  talk_base::RefCountedObject<VideoTrackProxy>* proxy =
      new talk_base::RefCountedObject<VideoTrackProxy>(track,
                                                       signaling_thread);
  return proxy;
}

}  // namespace webrtc

redpajama_set_name: RedPajamaGithub


text:
class Spree::ContactUsConfiguration < Spree::Preferences::Configuration
  preference :contact_tracking_message, :string, :default => nil
end


text:
package org.jetbrains.idea.maven.execution;

import com.intellij.ide.util.treeView.NodeRenderer;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.Ref;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.Consumer;
import com.intellij.util.containers.Convertor;
import icons.MavenIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import org.jetbrains.idea.maven.utils.MavenProjectNamer;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Sergey Evdokimov
 */
public class MavenSelectProjectPopup {

  public static void attachToWorkingDirectoryField(@NotNull final MavenProjectsManager projectsManager,
                                                   final JTextField workingDirectoryField,
                                                   final JButton showModulesButton,
                                                   @Nullable final JComponent focusAfterSelection) {
    attachToButton(projectsManager, showModulesButton, new Consumer<MavenProject>() {
      @Override
      public void consume(MavenProject project) {
        workingDirectoryField.setText(project.getDirectory());

        if (focusAfterSelection != null) {
          ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
              if (workingDirectoryField.hasFocus()) {
                focusAfterSelection.requestFocus();
              }
            }
          });
        }
      }
    });

    workingDirectoryField.addKeyListener(new KeyAdapter() {
      @Override
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_DOWN) {
          if (!e.isConsumed()) { // May be consumed by path completion.
            e.consume();
            showModulesButton.doClick();
          }
        }
      }
    });
  }

  public static void attachToButton(@NotNull final MavenProjectsManager projectsManager,
                                    @NotNull final JButton button,
                                    @NotNull final Consumer<MavenProject> callback) {
    button.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        List<MavenProject> projectList = projectsManager.getProjects();
        if (projectList.isEmpty()) {
          JBPopupFactory.getInstance().createMessage("Maven projects not found").showUnderneathOf(button);
          return;
        }

        DefaultMutableTreeNode root = buildTree(projectList);

        final Map<MavenProject, String> projectsNameMap = MavenProjectNamer.generateNameMap(projectList);

        final Tree projectTree = new Tree(root);
        projectTree.setRootVisible(false);
        projectTree.setCellRenderer(new NodeRenderer() {
          @Override
          public void customizeCellRenderer(JTree tree,
                                            Object value,
                                            boolean selected,
                                            boolean expanded,
                                            boolean leaf,
                                            int row,
                                            boolean hasFocus) {
            if (value instanceof DefaultMutableTreeNode) {
              MavenProject mavenProject = (MavenProject)((DefaultMutableTreeNode)value).getUserObject();
              value = projectsNameMap.get(mavenProject);
              setIcon(MavenIcons.MavenProject);
            }

            super.customizeCellRenderer(tree, value, selected, expanded, leaf, row, hasFocus);
          }
        });

        new TreeSpeedSearch(projectTree, new Convertor<TreePath, String>() {
          @Override
          public String convert(TreePath o) {
            Object lastPathComponent = o.getLastPathComponent();
            if (!(lastPathComponent instanceof DefaultMutableTreeNode)) return null;

            Object userObject = ((DefaultMutableTreeNode)lastPathComponent).getUserObject();

            //noinspection SuspiciousMethodCalls
            return projectsNameMap.get(userObject);
          }
        });

        final Ref<JBPopup> popupRef = new Ref<JBPopup>();

        final Runnable clickCallBack = new Runnable() {
          @Override
          public void run() {
            TreePath path = projectTree.getSelectionPath();
            if (path == null) return;

            Object lastPathComponent = path.getLastPathComponent();
            if (!(lastPathComponent instanceof DefaultMutableTreeNode)) return;

            Object object = ((DefaultMutableTreeNode)lastPathComponent).getUserObject();
            if (object == null) return; // may be it's the root

            callback.consume((MavenProject)object);

            popupRef.get().closeOk(null);
          }
        };

        projectTree.addKeyListener(new KeyAdapter() {
          @Override
          public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
              clickCallBack.run();
              e.consume();
            }
          }
        });

        JBPopup popup = new PopupChooserBuilder(projectTree)
          .setTitle("Select maven project")
          .setResizable(true)
          .setItemChoosenCallback(clickCallBack).setAutoselectOnMouseMove(true)
          .setCloseOnEnter(false)
          .createPopup();

        popupRef.set(popup);

        popup.showUnderneathOf(button);
      }

      private DefaultMutableTreeNode buildTree(List<MavenProject> projectList) {
        MavenProject[] projects = projectList.toArray(new MavenProject[projectList.size()]);
        Arrays.sort(projects, new MavenProjectNamer.MavenProjectComparator());

        Map<MavenProject, DefaultMutableTreeNode> projectsToNode = new HashMap<MavenProject, DefaultMutableTreeNode>();
        for (MavenProject mavenProject : projects) {
          projectsToNode.put(mavenProject, new DefaultMutableTreeNode(mavenProject));
        }

        DefaultMutableTreeNode root = new DefaultMutableTreeNode();

        for (MavenProject mavenProject : projects) {
          DefaultMutableTreeNode parent;

          MavenProject aggregator = projectsManager.findAggregator(mavenProject);
          if (aggregator != null) {
            parent = projectsToNode.get(aggregator);
          }
          else {
            parent = root;
          }

          parent.add(projectsToNode.get(mavenProject));
        }

        return root;
      }
    });
  }
}


text:
import React from "react";
import TestUtils from "react-addons-test-utils";
import chai from "chai";

import Media from "../src/Media";

let expect = chai.expect;

describe("Media", function () {
  beforeEach(function () {
    this.data = {
      url: "https://twitter.com/RedeGlobo/status/840532910696361984"
    };

    this.media = TestUtils.renderIntoDocument(
      <Media url={this.data.url} />
    );

    this.iframe = TestUtils.findRenderedDOMComponentWithClass(this.media, "media");
  });

  it("should render nothing", function () {
    const media = TestUtils.renderIntoDocument(
      <Media />
    );
    expect(media.textContent).to.be.empty;
    expect(media.children).to.be.empty;
  });

  it("should have a URL src from props", function () {
    expect(this.iframe.src).to.equal(this.data.url);
  });
});


text:
// Generated Source
import CfaAttachments from "./CfaAttachments";
import CfaRecurrence from "./CfaRecurrence";

interface CfaSchedule {

    /**
     *
     */
    scheduleId?: string;

    /**
     *
     */
    recurrence?: CfaRecurrence;

    /**
     *
     */
    viewType?: "Detailed" | "Simple";

    /**
     *
     */
    attachments?: CfaAttachments;

    /**
     *
     */
    recipients?: string[];

    /**
     *
     */
    pages?: string[];
}

export default CfaSchedule;


text:
using System;
using System.Linq;

namespace SME.AST
{
    /// <summary>
    /// A statement in the method body.
    /// </summary>
    public abstract class Statement : ASTItem
    {

    }

    /// <summary>
    /// An expression statement.
    /// </summary>
    public class ExpressionStatement : Statement
    {
        /// <summary>
        /// The expression inside the statement.
        /// </summary>
        public Expression Expression;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public ExpressionStatement()
        {
        }

        /// <summary>
        /// Creates a new statement for the expression.
        /// </summary>
        /// <param name="expression">The expression to use.</param>
        public ExpressionStatement(Expression expression)
        {
            this.Expression = expression;
            this.Expression.Parent = this;
        }
    }

    /// <summary>
    /// A simple empty statement.
    /// </summary>
    public class EmptyStatement : Statement
    {
    }

    /// <summary>
    /// An If/Else statement.
    /// </summary>
    public class IfElseStatement : Statement
    {
        /// <summary>
        /// The expression to evaluate.
        /// </summary>
        public Expression Condition;
        /// <summary>
        /// The statements to execute if the condition is true.
        /// </summary>
        public Statement TrueStatement;
        /// <summary>
        /// The statements to execute if the condition is false.
        /// </summary>
        public Statement FalseStatement;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public IfElseStatement()
        {
        }

        /// <summary>
        /// Constructs a new <see cref="IfElseStatement"/>.
        /// </summary>
        /// <param name="condition">The condition expression.</param>
        /// <param name="trueStatement">The true statement.</param>
        /// <param name="falseStatement">The false statement.</param>
        public IfElseStatement(Expression condition, Statement trueStatement, Statement falseStatement)
        {
            this.Condition = condition;
            this.TrueStatement = trueStatement;
            this.FalseStatement = falseStatement;
            this.Condition.Parent = this;
            this.TrueStatement.Parent = this;
            this.FalseStatement.Parent = this;
        }
    }

    /// <summary>
    /// A block statement.
    /// </summary>
    public class BlockStatement : Statement
    {
        /// <summary>
        /// The statements in the block.
        /// </summary>
        public Statement[] Statements;

        /// <summary>
        /// The variables defined in the block scope.
        /// </summary>
        public Variable[] Variables;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public BlockStatement()
        {
        }

        /// <summary>
        /// Constructs a new block statement.
        /// </summary>
        /// <param name="statements">The statements in the block.</param>
        /// <param name="variables">The variables used in the block.</param>
        public BlockStatement(Statement[] statements, Variable[] variables)
        {
            this.Statements = statements;
            this.Variables = variables;
            foreach (var s in this.Statements ?? new Statement[0])
                s.Parent = this;
        }
    }

    /// <summary>
    /// A switch statement.
    /// </summary>
    public class SwitchStatement : Statement
    {
        /// <summary>
        /// The expression the switch is performed on.
        /// </summary>
        public Expression SwitchExpression;

        /// <summary>
        /// The cases and labels for the statement.
        /// </summary>
        public Tuple<Expression[], Statement[]>[] Cases;

        /// <summary>
        /// States whether or not the SwitchStatement contains a default: case.
        /// </summary>
        public bool HasDefault;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public SwitchStatement()
        {
        }

        /// <summary>
        /// Constructs a new switch statement.
        /// </summary>
        /// <param name="switchExpression">The expression to switch on.</param>
        /// <param name="cases">The cases in the statement.</param>
        public SwitchStatement(Expression switchExpression, Tuple<Expression[], Statement[]>[] cases)
        {
            this.SwitchExpression = switchExpression;
            this.Cases = cases;
            this.SwitchExpression.Parent = this;
            foreach (var c in cases ?? new Tuple<Expression[], Statement[]>[0])
            {
                foreach (var e in c.Item1 ?? new Expression[0])
                    e.Parent = this;
                foreach (var s in c.Item2 ?? new Statement[0])
                    s.Parent = this;
            }
        }
    }

    /// <summary>
    /// A return statement.
    /// </summary>
    public class ReturnStatement : Statement
    {
        /// <summary>
        /// The expression that should be evaluated to return this.
        /// </summary>
        public Expression ReturnExpression;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public ReturnStatement()
        {
        }

        /// <summary>
        /// Creates a new return statement.
        /// </summary>
        /// <param name="expression">The expression to return.</param>
        public ReturnStatement(Expression expression)
        {
            this.ReturnExpression = expression;
            this.ReturnExpression.Parent = this;
        }
    }

    /// <summary>
    /// A for statement.
    /// </summary>
    public class ForStatement : Statement
    {
        /// <summary>
        /// The initialization expression for the loop index.
        /// </summary>
        public Expression Initializer;
        /// <summary>
        /// The final value for the loop index.
        /// </summary>
        public Expression Condition;
        /// <summary>
        /// The increment for each loop iteration.
        /// </summary>
        public Expression Increment;
        /// <summary>
        /// The variable used to hold the loop value.
        /// </summary>
        public Variable LoopIndex;

        /// <summary>
        /// The loop body content.
        /// </summary>
        public Statement LoopBody;

        /// <summary>
        /// A variable indicating if the for loop has a statically known size.
        /// </summary>
        public bool HasStaticSize;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public ForStatement()
        {
        }

        /// <summary>
        /// Creates a new loop statement.
        /// </summary>
        /// <param name="initializer">The initial expression.</param>
        /// <param name="condition">The condition expression value.</param>
        /// <param name="increment">The loop increment expression.</param>
        /// <param name="loopIndex">The loop index.</param>
        /// <param name="body">The loop body.</param>
        public ForStatement(Expression initializer, Expression condition, Expression increment, Variable loopIndex, Statement body)
        {
            this.Initializer = initializer;
            this.Condition = condition;
            this.Increment = increment;
            this.LoopIndex = loopIndex;
            this.LoopBody = body;
            this.LoopBody.Parent = this;
            this.HasStaticSize =
                new[] { initializer, condition, increment }
                .Count(x => (x as PrimitiveExpression)?.GetTarget() is Constant) == 3;
        }
    }

    /// <summary>
    /// A break statement.
    /// </summary>
    public class BreakStatement : Statement
    {
    }

    /// <summary>
    /// A goto statement.
    /// </summary>
    public class GotoStatement : Statement
    {
        /// <summary>
        /// The target label.
        /// </summary>
        public string Label;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public GotoStatement()
        {
        }

        /// <summary>
        /// Creates a new goto statement.
        /// </summary>
        /// <param name="label">The label target.</param>
        public GotoStatement(string label)
        {
        }
    }

    /// <summary>
    /// A label statement.
    /// </summary>
    public class LabelStatement : Statement
    {
        /// <summary>
        /// The label.
        /// </summary>
        public string Label;
    }

    /// <summary>
    /// A statement used to output a comment.
    /// </summary>
    public class CommentStatement : Statement
    {
        /// <summary>
        /// The comment message.
        /// </summary>
        public string Message;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:SME.AST.CommentStatement"/> class.
        /// </summary>
        public CommentStatement() { }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:SME.AST.CommentStatement"/> class.
        /// </summary>
        /// <param name="message">The message to set.</param>
        public CommentStatement(string message)
        {
            Message = message;
        }
    }

    /// <summary>
    /// A while statement.
    /// </summary>
    public class WhileStatement : Statement
    {
        /// <summary>
        /// The while condition expression.
        /// </summary>
        public Expression Condition;

        /// <summary>
        /// The while loop body statement.
        /// </summary>
        public Statement Body;

        /// <summary>
        /// Initializes a new instance of the <see cref="T:SME.AST.WhileStatement"/> class.
        /// </summary>
        public WhileStatement() { }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:SME.AST.WhileStatement"/> class.
        /// </summary>
        /// <param name="condition">The while condition.</param>
        /// <param name="body">The while loop body.</param>
        public WhileStatement(Expression condition, Statement body)
        {
            Condition = condition;
            Body = body;
            if (Condition != null)
                Condition.Parent = this;
            if (Body != null)
                Body.Parent = this;
        }
    }
}


text:
package com.enonic.harvest.harvestclient.models;

import com.enonic.harvest.harvestclient.exceptions.HarvestClientException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;
import java.util.Date;

@XmlAccessorType(XmlAccessType.NONE)
public class InvoiceMessage
{
    @XmlElement(name = "id")
    private Integer id;

    @XmlElement(name = "body")
    private String body;

    @XmlElement(name = "invoice-id")
    private Integer invoiceId;

    @XmlElement(name = "send-me-a-copy")
    private boolean sendMeACopy;

    @XmlElement(name = "sent-by")
    private String sentBy;

    @XmlElement(name = "sent-by-email")
    private String sentByEmail;

    @XmlElement(name = "full-recipient-list")
    private String fullRecipientList;

    @XmlElement(name = "updated-at")
    private Date updatedAt;

    @XmlElement(name = "created-at")
    private Date createdAt;

    public static InvoiceMessage fromInputStream(final InputStream xml)
            throws HarvestClientException
    {
        try
        {
            JAXBContext context = JAXBContext.newInstance(InvoiceMessage.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            Source source = new StreamSource(xml);
            // We have to explicitly tell it what class we want, since we can't have two
            // classes annotated with @XmlRootElement(name = "invoice-message")
            // This is due to a bug in the Harvest API for InvoiceMessages using same element
            // name for both the list and the items in it.
            return unmarshaller.unmarshal(source, InvoiceMessage.class).getValue();
        }
        catch (Exception e)
        {
            throw new HarvestClientException("Unable to parse XML into Invoice.", e);
        }

    }

    public Integer getId()
    {
        return id;
    }

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

    public String getBody()
    {
        return body;
    }

    public void setBody(String body)
    {
        this.body = body;
    }

    public Integer getInvoiceId()
    {
        return invoiceId;
    }

    public void setInvoiceId(Integer invoiceId)
    {
        this.invoiceId = invoiceId;
    }

    public boolean isSendMeACopy()
    {
        return sendMeACopy;
    }

    public void setSendMeACopy(boolean sendMeACopy)
    {
        this.sendMeACopy = sendMeACopy;
    }

    public String getSentBy()
    {
        return sentBy;
    }

    public void setSentBy(String sentBy)
    {
        this.sentBy = sentBy;
    }

    public String getSentByEmail()
    {
        return sentByEmail;
    }

    public void setSentByEmail(String sentByEmail)
    {
        this.sentByEmail = sentByEmail;
    }

    public String getFullRecipientList()
    {
        return fullRecipientList;
    }

    public void setFullRecipientList(String fullRecipientList)
    {
        this.fullRecipientList = fullRecipientList;
    }

    public Date getUpdatedAt()
    {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt)
    {
        this.updatedAt = updatedAt;
    }

    public Date getCreatedAt()
    {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt)
    {
        this.createdAt = createdAt;
    }
}


text:
@interface BRDummyBeaconMessagePersistorLogIterator : NSObject<BRLogIterator> {
    NSMutableArray* _messages;
    int _cursor;
}

- (id) initWithMessages: (NSMutableArray*) messages;
- (BOOL) hasNext;
- (BRBeaconMessage*) next;

@end


text:
#include <vector>
#include "util/name_map.h"
#include "kernel/free_vars.h"
#include "kernel/for_each_fn.h"
#include "library/trace.h"
#include "library/compiler/rec_fn_macro.h"
#include "library/compiler/procedure.h"
#include "library/compiler/compiler_step_visitor.h"

namespace lean {
static expr reduce_arity_of(expr const & e, unsigned i, std::vector<bool> const & keep_bv) {
    if (i == keep_bv.size())
        return e;
    lean_assert(is_lambda(e));
    expr new_body = reduce_arity_of(binding_body(e), i+1, keep_bv);
    if (keep_bv[i])
        return copy_tag(e, mk_lambda(binding_name(e), binding_domain(e), new_body));
    else
        return lower_free_vars(new_body, 1);
}

/* Auxiliary functor for removing arguments that are not needed in auxiliary function calls */
class remove_args_fn : public compiler_step_visitor {
    /* Mapping from auxiliary function name to bitvector of used arguments */
    name_map<std::vector<bool>> const & m_to_reduce;

    virtual expr visit_macro(expr const & e) override {
        /* This module assumes rec_fn_macros have already been eliminated.
           Remark: the step erase_irrelevant eliminates all occurences. */
        lean_assert(!is_rec_fn_macro(e));
        return compiler_step_visitor::visit_macro(e);
    }

    virtual expr visit_app(expr const & e) override {
        expr const & fn = get_app_fn(e);
        if (is_constant(fn)) {
            if (std::vector<bool> const * bv = m_to_reduce.find(const_name(fn))) {
                buffer<expr> args;
                get_app_args(e, args);
                buffer<expr> new_args;
                for (unsigned i = 0; i < args.size(); i++) {
                    /* The case i >= bv->size() can happen when the function is returning a closure.
                       We eta-expand terms, but we may miss cases where the type is opaque (e.g., IO a),
                       or the type is dependent (e.g., T b) where (T is defined as T b := bool.cases_on b nat (nat -> nat)).
                    */
                    if (i >= bv->size() || (*bv)[i])
                        new_args.push_back(visit(args[i]));
                }
                return mk_app(fn, new_args);
            }
        }
        return compiler_step_visitor::visit_app(e);
    }

public:
    remove_args_fn(environment const & env, abstract_context_cache & cache, name_map<std::vector<bool>> const & to_reduce):
        compiler_step_visitor(env, cache), m_to_reduce(to_reduce) {}
};

void reduce_arity(environment const & env, abstract_context_cache & cache, buffer<procedure> & procs) {
    lean_assert(!procs.empty());
    /* Store in to_reduce a bit-vector indicating which arguments are used by each (auxiliary) function. */
    name_map<std::vector<bool>> to_reduce;
    for (unsigned i = 0; i < procs.size() - 1; i++) {
        expr fn = procs[i].m_code;
        std::vector<bool> keep_bv;
        bool reduced = false;
        while (is_lambda(fn)) {
            expr const & body = binding_body(fn);
            if (has_free_var(body,  0)) {
                keep_bv.push_back(true);
            } else {
                keep_bv.push_back(false);
                reduced = true;
            }
            fn = body;
        }
        if (reduced) {
            to_reduce.insert(procs[i].m_name, keep_bv);
        }
    }
    if (to_reduce.empty())
        return;
    /* reduce arity of functions at to_reduce */
    for (unsigned i = 0; i < procs.size() - 1; i++) {
        procedure & d = procs[i];
        if (std::vector<bool> const * bv = to_reduce.find(d.m_name)) {
            d.m_code = reduce_arity_of(d.m_code, 0, *bv);
        }
    }
    /* reduce irrelevant application arguments */
    remove_args_fn remove_args(env, cache, to_reduce);
    for (unsigned i = 0; i < procs.size(); i++) {
        procedure & d = procs[i];
        d.m_code = remove_args(d.m_code);
    }
}
}


text:
package rubyobj

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/aybabtme/fatherhood"
	"io"
	// "log"
	"sync"
)

// Trivial codec

// Decoder decodes RubyObjects from an io.Reader.  It wraps a json.Decoder and is
// pretty slow, but simple to use for those acustomed to the json.Decoder from
// the stdlib.
type Decoder struct {
	dec *json.Decoder
}

// NewDecoder returns a trivial decoder wrapping a json.Decoder of the stdlib.
// It is pretty slow but simple to use.
//
// For performance, prefer ParallelDecode.
func NewDecoder(r io.Reader) *Decoder {
	return &Decoder{json.NewDecoder(r)}
}

var schema objectSchema

// Decode decodes a ruby object from the underlying io.Reader.
func (d *Decoder) Decode(rObj *RubyObject) (err error) {
	schema.clear()
	err = d.dec.Decode(&schema)
	if err != nil {
		return err
	}
	return rObj.loadSchema(&schema)
}

// Encoder encodes RubyObjects to an io.Writer.  It wraps a json.Encoder and is
// pretty slow, but simple to use for those acustomed to the json.Encoder from
// the stdlib.
type Encoder struct {
	enc *json.Encoder
}

// NewEncoder returns a trivial encoder wrapping a json.Encoder of the stdlib.
// It is pretty slow but simple to use.
func NewEncoder(w io.Writer) *Encoder {
	return &Encoder{json.NewEncoder(w)}
}

// Encode encodes the object onto the underlying io.Writer.
func (e *Encoder) Encode(rObj *RubyObject) (err error) {
	return e.enc.Encode(rObj.saveSchema())
}

// Parallel

// ParallelDecode will use many goroutines to decode io.Reader.  io.Reader MUST
// present JSON objects seperated by \n characters.
//
// Decoding will use para + 1 goroutines:
//      1 x goroutines to read all the lines in the io.Reader
//   para x goroutines to decode the lines
//
// The decoding will continue until it reaches EOF in the io.Reader, and return
// all the errors it encountered on the error channel, including Read errors,
// unmarshalling errors and loading errors.
func ParallelDecode(r io.Reader, para uint) (<-chan RubyObject, <-chan error) {

	bufLen := para << 2
	decodedC := make(chan RubyObject, bufLen)
	errc := make(chan error, bufLen)

	go func() {
		defer close(decodedC)
		defer close(errc)

		lineC := scanLines(r, errc, bufLen)

		wg := sync.WaitGroup{}
		// log.Printf("[para] starting workers")
		for i := uint(0); i < para; i++ {
			// log.Printf("[para] -> worker %d", i)
			wg.Add(1)
			go decodeLines(&wg, lineC, decodedC, errc)
		}
		// log.Printf("[para] waiting for workers")
		wg.Wait()
	}()

	return decodedC, errc

}

func scanLines(r io.Reader, errc chan<- error, para uint) <-chan []byte {
	linesC := make(chan []byte, para)

	go func() {
		defer close(linesC)

		br := bufio.NewReader(r)

		var line []byte
		var err error

		// log.Printf("[scan] scanning...")
		// defer log.Printf("[scan] done")
		for {
			line, err = br.ReadBytes('\n')
			if err == io.EOF {
				break
			}
			if err != nil {
				// log.Printf("[scan] -> error")
				errc <- err
			}
			linesC <- line
			// log.Printf("[scan] -> scanned")

		}

	}()

	return linesC
}

func decodeLines(wg *sync.WaitGroup, lineC <-chan []byte, decoded chan<- RubyObject, errc chan<- error) {
	defer wg.Done()

	rObj := RubyObject{}
	schema := objectSchema{}
	var err error

	r := bytes.NewBuffer(nil)
	dec := fatherhood.NewDecoder(r)

	for line := range lineC {

		_, _ = r.Write(line)
		err = dec.EachMember(&schema, decodeObjSchema)
		if err != nil {
			errc <- err
			continue
		}

		err = rObj.loadSchema(&schema)
		if err != nil {
			errc <- err
			continue
		}
		decoded <- rObj

	}

}

func decodeObjSchema(dec *fatherhood.Decoder, s interface{}, member string) error {
	schema := s.(*objectSchema)
	switch member {
	case "address":
		return dec.ReadString(&schema.Address)
	case "class":
		return dec.ReadString(&schema.Class)
	case "node_type":
		return dec.ReadString(&schema.NodeType)
	case "references":
		schema.References = make([]string, 0)
		return dec.EachValue(&schema.References, decodeReference)
	case "type":
		return dec.ReadString(&schema.Type)
	case "value":
		return dec.ReadString(&schema.Value)
	case "line":
		return dec.ReadUint64(&schema.Line)
	case "method":
		return dec.ReadString(&schema.Method)
	case "file":
		return dec.ReadString(&schema.File)
	case "fd":
		return dec.ReadInt(&schema.Fd)
	case "bytesize":
		return dec.ReadUint64(&schema.Bytesize)
	case "capacity":
		return dec.ReadUint64(&schema.Capacity)
	case "length":
		return dec.ReadUint64(&schema.Length)
	case "size":
		return dec.ReadUint64(&schema.Size)
	case "encoding":
		return dec.ReadString(&schema.Encoding)
	case "default":
		return dec.ReadString(&schema.Default)
	case "name":
		return dec.ReadString(&schema.Name)
	case "struct":
		return dec.ReadString(&schema.Struct)
	case "ivars":
		return dec.ReadUint64(&schema.Ivars)
	case "generation":
		return dec.ReadUint64(&schema.Generation)
	case "memsize":
		return dec.ReadUint64(&schema.Memsize)
	case "frozen":
		return dec.ReadBool(&schema.Frozen)
	case "embedded":
		return dec.ReadBool(&schema.Embedded)
	case "broken":
		return dec.ReadBool(&schema.Broken)
	case "fstring":
		return dec.ReadBool(&schema.Fstring)
	case "shared":
		return dec.ReadBool(&schema.Shared)
	case "flags":
		schema.Flags = flagSchema{}
		return dec.EachMember(&schema.Flags, decodeFlagSchema)
	}
	// unsupported member
	return dec.Discard()
}

func decodeFlagSchema(dec *fatherhood.Decoder, f interface{}, member string) error {
	flag := f.(*flagSchema)
	switch member {
	case "wb_protected":
		return dec.ReadBool(&flag.WbProtected)
	case "old":
		return dec.ReadBool(&flag.Old)
	case "marked":
		return dec.ReadBool(&flag.Marked)
	}
	// unsupported member
	return dec.Discard()
}

func decodeReference(dec *fatherhood.Decoder, a interface{}, t fatherhood.JSONType) error {
	arr := a.(*[]string)
	switch t {
	case fatherhood.String:
		var v struct {
			val string
		}
		err := dec.ReadString(&v.val)
		if err != nil {
			return err
		}
		*arr = append(*arr, v.val)
		return nil
	}
	return fmt.Errorf("unexpected type in 'reference' array, %#v", t)
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Yarrow & Meyer, Int. J. Syst. Bacteriol. 28(4): 612 (1978)

#### Original name
Torulopsis domercqiae Van der Walt & Kerken, 1960

### Remarks
null


text:
'use strict';

var gulp = require('gulp');

module.exports = function(opts) {
    return function() {
        return gulp.src(opts.src)
            .pipe(gulp.dest(opts.dest));
    };
};


text:
<md-content style="background-color: rgba(255, 255, 255, .70);" layout-fill >

shirts

<md-divider></md-divider>

Proceeds from the sales of CyclePhilly T-Shirts help us offset the costs of managing the project.

Buy on Square Market

</md-content>


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.insightsuen.stayfoolish">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:name=".SFApplication"
        android:theme="@style/AppTheme">

        <activity android:name=".ui.main.MainActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity android:name=".ui.drag.DragActivity"/>
        <activity android:name=".ui.image.GalleryActivity"/>
        <activity android:name=".ui.toast.ToastActivity"/>
        <activity android:name=".ui.blur.BlurActivity"/>
        <activity android:name=".ui.style.UnifyStyleActivity"/>
        <activity android:name=".ui.widget.WidgetActivity"/>
        <activity android:name=".ui.thread.ThreadActivity"/>
        <activity android:name=".ui.aidl.AidlActivity"/>
        <activity android:name=".ui.handler.HandlerActivity"/>
        <activity android:name=".ui.orm.OrmActivity"/>
        <activity android:name=".ui.rx.RxActivity"/>
        <activity android:name=".ui.appbar.AppbarActivity"
            android:theme="@style/AppTheme.CustomerActionBar"
            android:parentActivityName=".ui.main.MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".ui.main.MainActivity" />
        </activity>

    </application>

</manifest>


text:
using System.IO;

using JetBrains.Annotations;

using ManagedIrbis;
using ManagedIrbis.Client;
using ManagedIrbis.Pft;
using ManagedIrbis.Pft.Infrastructure;
using ManagedIrbis.Pft.Infrastructure.Ast;
using ManagedIrbis.Pft.Infrastructure.Compiler;
using ManagedIrbis.Pft.Infrastructure.Diagnostics;
using ManagedIrbis.Pft.Infrastructure.Serialization;
using ManagedIrbis.Pft.Infrastructure.Text;

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTests.ManagedIrbis.Pft.Infrastructure.Ast
{
    [TestClass]
    public class PftAnyTest
    {
        private void _Execute
            (
                [NotNull] MarcRecord record,
                [NotNull] PftAny node,
                bool expected
            )
        {
            PftContext context = new PftContext(null)
            {
                Record = record
            };
            node.Execute(context);
            bool actual = node.Value;
            Assert.AreEqual(expected, actual);
        }

        [NotNull]
        private MarcRecord _GetRecord()
        {
            MarcRecord result = new MarcRecord();

            RecordField field = new RecordField(700);
            field.AddSubField('a', "Иванов");
            field.AddSubField('b', "И. И.");
            result.Fields.Add(field);

            field = new RecordField(701);
            field.AddSubField('a', "Петров");
            field.AddSubField('b', "П. П.");
            result.Fields.Add(field);

            field = new RecordField(200);
            field.AddSubField('a', "Заглавие");
            field.AddSubField('e', "подзаголовочное");
            field.AddSubField('f', "И. И. Иванов, П. П. Петров");
            result.Fields.Add(field);

            field = new RecordField(300, "Первое примечание");
            result.Fields.Add(field);
            field = new RecordField(300, "Второе примечание");
            result.Fields.Add(field);
            field = new RecordField(300, "Третье примечание");
            result.Fields.Add(field);

            return result;
        }

        [NotNull]
        private PftAny _GetNode()
        {
            return new PftAny
            {
                InnerCondition = new PftComparison
                {
                    LeftOperand = new PftV("v300"),
                    Operation = ":",
                    RightOperand = new PftUnconditionalLiteral("примечание")
                }
            };
        }

        [TestMethod]
        public void PftAny_Construction_1()
        {
            PftAny node = new PftAny();
            Assert.IsFalse(node.ConstantExpression);
            Assert.IsTrue(node.RequiresConnection);
            Assert.IsTrue(node.ExtendedSyntax);
            Assert.IsNull(node.InnerCondition);
        }

        [TestMethod]
        public void PftAny_Construction_2()
        {
            PftToken token = new PftToken(PftTokenKind.Any, 1, 1, "any");
            PftAny node = new PftAny(token);
            Assert.IsFalse(node.ConstantExpression);
            Assert.IsTrue(node.RequiresConnection);
            Assert.IsTrue(node.ExtendedSyntax);
            Assert.IsNull(node.InnerCondition);
            Assert.AreEqual(token.Column, node.Column);
            Assert.AreEqual(token.Line, node.LineNumber);
            Assert.AreEqual(token.Text, node.Text);
        }

        [TestMethod]
        public void PftAny_Clone_1()
        {
            PftAny first = new PftAny();
            PftAny second = (PftAny) first.Clone();
            PftSerializationUtility.CompareNodes(first, second);
        }

        [TestMethod]
        public void PftAny_Clone_2()
        {
            PftAny first = _GetNode();
            PftAny second = (PftAny)first.Clone();
            PftSerializationUtility.CompareNodes(first, second);
        }

        [TestMethod]
        public void PftAny_Execute_1()
        {
            MarcRecord record = _GetRecord();
            PftAny node = _GetNode();
            _Execute(record, node, true);
        }

        [TestMethod]
        public void PftAny_Execute_2()
        {
            MarcRecord record = _GetRecord();
            PftAny node = _GetNode();
            PftComparison comparison = (PftComparison) node.InnerCondition;
            Assert.IsNotNull(comparison);
            comparison.RightOperand = new PftUnconditionalLiteral("noSuchWord");
            _Execute(record, node, false);
        }

        [TestMethod]
        public void PftAny_Execute_2a()
        {
            MarcRecord record = _GetRecord();
            PftAny node = _GetNode();
            PftComparison comparison = (PftComparison) node.InnerCondition;
            Assert.IsNotNull(comparison);
            comparison.LeftOperand = new PftV("v444");
            _Execute(record, node, false);
        }

        [TestMethod]
        [ExpectedException(typeof(PftSemanticException))]
        public void PftAny_Execute_3()
        {
            PftAny node = _GetNode();
            PftContext context = new PftContext(null)
            {
                CurrentGroup = new PftGroup()
            };
            node.Execute(context);
        }

        [TestMethod]
        public void PftAny_Execute_4()
        {
            MarcRecord record = _GetRecord();
            PftAny node = new PftAny
            {
                InnerCondition = new PftComparison
                {
                    LeftOperand = new PftUnconditionalLiteral("1"),
                    Operation = "=",
                    RightOperand = new PftUnconditionalLiteral("1")
                }
            };
            _Execute(record, node, false);
        }

        [TestMethod]
        public void PftAny_GetNodeInfo_1()
        {
            PftAny node = _GetNode();
            PftNodeInfo info = node.GetNodeInfo();
            Assert.AreSame(node, info.Node);
            Assert.AreEqual("Any", info.Name);
        }

        [TestMethod]
        public void PftAny_PrettyPrint_1()
        {
            PftAny node = _GetNode();
            PftPrettyPrinter printer = new PftPrettyPrinter();
            node.PrettyPrint(printer);
            Assert.AreEqual("any(v300:'примечание')", printer.ToString());
        }

        private void _TestSerialization
            (
                [NotNull] PftAny first
            )
        {
            MemoryStream stream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(stream);
            PftSerializer.Serialize(writer, first);

            byte[] bytes = stream.ToArray();
            stream = new MemoryStream(bytes);
            BinaryReader reader = new BinaryReader(stream);
            PftAny second = (PftAny) PftSerializer.Deserialize(reader);
            PftSerializationUtility.CompareNodes(first, second);
        }

        [TestMethod]
        public void PftAny_Serialization_1()
        {
            PftAny node = new PftAny();
            _TestSerialization(node);

            node = _GetNode();
            _TestSerialization(node);
        }

        [TestMethod]
        public void PftAny_ToString_1()
        {
            PftAny node = new PftAny();
            Assert.AreEqual("any()", node.ToString());
        }

        [TestMethod]
        public void PftAny_ToString_2()
        {
            PftAny node = _GetNode();
            Assert.AreEqual("any(v300:'примечание')", node.ToString());
        }
    }
}


text:
<?php
namespace Codeception\Command;

use Codeception\Lib\Generator\Feature;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Generates Feature file (in Gherkin):
 *
 * * `codecept generate:feature suite Login`
 * * `codecept g:feature suite subdir/subdir/login.feature`
 * * `codecept g:feature suite login.feature -c path/to/project`
 *
 */
class GenerateFeature extends Command
{
    use Shared\FileSystem;
    use Shared\Config;

    protected function configure()
    {
        $this->setDefinition([
            new InputArgument('suite', InputArgument::REQUIRED, 'suite to be tested'),
            new InputArgument('feature', InputArgument::REQUIRED, 'feature to be generated'),
            new InputOption('config', 'c', InputOption::VALUE_OPTIONAL, 'Use custom path for config'),
        ]);
    }

    public function getDescription()
    {
        return 'Generates empty feature file in suite';
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $suite = $input->getArgument('suite');
        $filename = $input->getArgument('feature');

        $config = $this->getSuiteConfig($suite);
        $this->createDirectoryFor($config['path'], $filename);

        $gen = new Feature(basename($filename));
        if (!preg_match('~\.feature$~', $filename)) {
            $filename .= '.feature';
        }
        $full_path = rtrim($config['path'], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename;
        $res = $this->createFile($full_path, $gen->produce());
        if (!$res) {
            $output->writeln("<error>Feature $filename already exists</error>");
            return;
        }
        $output->writeln("<info>Feature was created in $full_path</info>");
    }
}


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.test.internal.engine.valueextraction.model;

/**
 * @author Marko Bekhta
 */
public interface ImprovedCustomContainer<T,E> extends CustomContainer<T> {
	int size();

	E getE();
}


text:
package com.betfair.cougar.core.api;

import com.betfair.cougar.api.export.Protocol;

/**
 * Base level interface for a transport specific binding descriptor
 * Indicates which transport the binding descriptor is applicable too
 */
public interface BindingDescriptor {
    Protocol getServiceProtocol();
}


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.Generic;
using TransactionFramework = TransactionalNodeService.Soap.TransactionFramework;

namespace TransactionalNodeService.Proxy
{
    public class MetadataCollection : IEnumerable<IMetadataSet>
    {
        private List<IMetadataSet> _metadata = null;
        private Proxy.MetadataType _stringType = null;

        #region Common Super Graph Types
        protected Proxy.MetadataType StringMetadataType
        {
            get
            {
                if (_stringType == null)
                {
                    _stringType = MapManager.MetadataTypes["string"];
                }

                return _stringType;
            }
        }
        #endregion

        protected List<IMetadataSet> Metadata
        {
            get
            {
                if (_metadata == null)
                {
                    _metadata = new List<IMetadataSet>();
                }

                return _metadata;
            }
            set
            {
                _metadata = value;
            }
        }

        protected Proxy.IMapManager MapManager
        {
            get;
            set;
        }

        public void Clear()
        {
            /// Shouldn't clear all the metadata as some of it may have only just been added.
            /// Only remove the SoapMetadata objects. The InPocessMetadata needs to remain.
            //Metadata.Clear();

            Metadata.RemoveAll(RemoveMetadataSetPredicate);
        }

        private bool RemoveMetadataSetPredicate(IMetadataSet metadataSet)
        {
            FacadeMetadataSet facadeMetadataSet = metadataSet as FacadeMetadataSet;

            if (facadeMetadataSet != null)
            {
                if (facadeMetadataSet.BaseMetadata is Soap.SoapMetadataSet)
                {
                    return true;
                }
            }

            return false;
        }

        public void Remove(IMetadataSet metadataSet)
        {
            Metadata.Remove(metadataSet);
        }

        protected TransactionFramework.AddMetadataTransactionLink AddMetadataTransaction(IMetadataSet metadataSet, Proxy.INode node, Proxy.IRelationship relationship, Proxy.ConnectionType connectionType, string name, string value)
        {
            TransactionFramework.AddMetadataTransactionLink addMetadataTransaction = new TransactionFramework.AddMetadataTransactionLink();
            addMetadataTransaction.DomainId = node.DomainId;
            addMetadataTransaction.RootMapId = node.RootMapId;
            addMetadataTransaction.MapManager = MapManager;
            addMetadataTransaction.MetadataSet = metadataSet;
            addMetadataTransaction.Node = node;
            addMetadataTransaction.Relationship = relationship;
            addMetadataTransaction.ConnectionType = connectionType;
            addMetadataTransaction.MetadataType = StringMetadataType;
            addMetadataTransaction.Name = name;
            addMetadataTransaction.Value = value;

            return addMetadataTransaction;
        }

        IEnumerator<IMetadataSet> IEnumerable<IMetadataSet>.GetEnumerator()
        {
            return Metadata.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return Metadata.GetEnumerator();
        }
    }
}


text:
package org.spongepowered.common.data.value.immutable;

import static com.google.common.base.Preconditions.checkNotNull;

import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.DataManipulator;
import org.spongepowered.api.data.manipulator.immutable.ImmutableMobSpawnerData;
import org.spongepowered.api.data.manipulator.mutable.MobSpawnerData;
import org.spongepowered.api.entity.EntityType;
import org.spongepowered.api.entity.EntityTypes;
import org.spongepowered.api.util.weighted.WeightedEntity;
import org.spongepowered.common.data.value.mutable.SpongeNextEntityToSpawnValue;

import java.util.Collection;
import java.util.function.Function;

import javax.annotation.Nullable;

public class ImmutableSpongeEntityToSpawnValue extends ImmutableSpongeValue<WeightedEntity> implements
                                                                                ImmutableMobSpawnerData.ImmutableNextEntityToSpawnValue {

    public ImmutableSpongeEntityToSpawnValue(WeightedEntity actualValue) {
        super(Keys.SPAWNER_NEXT_ENTITY_TO_SPAWN, new WeightedEntity(EntityTypes.CREEPER, 1), actualValue);
    }

    @Override
    public ImmutableSpongeEntityToSpawnValue with(WeightedEntity value) {
        return new ImmutableSpongeEntityToSpawnValue(checkNotNull(value));
    }

    @Override
    public ImmutableSpongeEntityToSpawnValue transform(Function<WeightedEntity, WeightedEntity> function) {
        final WeightedEntity value = checkNotNull(function).apply(get());
        return new ImmutableSpongeEntityToSpawnValue(checkNotNull(value));
    }

    @Override
    public MobSpawnerData.NextEntityToSpawnValue asMutable() {
        return new SpongeNextEntityToSpawnValue(this.actualValue);
    }

    @Override
    public ImmutableMobSpawnerData.ImmutableNextEntityToSpawnValue with(EntityType type,
                                                                        @Nullable Collection<DataManipulator<?, ?>> additionalProperties) {
        if (additionalProperties == null) {
            return new ImmutableSpongeEntityToSpawnValue(new WeightedEntity(checkNotNull(type), 1));
        } else {
            return new ImmutableSpongeEntityToSpawnValue(new WeightedEntity(checkNotNull(type), 1, additionalProperties));
        }
    }
}


text:
package hu.akarnokd.rxjava2;

import org.junit.Test;

import io.reactivex.Single;
import io.reactivex.schedulers.Schedulers;

public class OnErrorCrash {

    @Test
    public void test() throws Exception {
        Single.fromCallable(() -> { throw new RuntimeException(); })
        .subscribeOn(Schedulers.io())
        .observeOn(Schedulers.computation())
        .subscribe(v -> { }, e -> { throw new RuntimeException(e); });

        Thread.sleep(50000);
    }
}


text:
package co.bugfreak;

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

import co.bugfreak.components.ErrorReportDataProvider;
import co.bugfreak.components.ErrorReportSerializer;
import co.bugfreak.framework.ServiceLocator;

public class GlobalConfig {

  private static String serviceEndPoint;
  private static String apiKey;
  private static String token;
  private static List<ErrorReportDataProvider> providers = new ArrayList<ErrorReportDataProvider>();
  private static ServiceLocator serviceLocator;
  private static ErrorReportSerializer errorReportSerializer;

  public static ServiceLocator getServiceLocator() {
    return serviceLocator;
  }

  public static void setServiceLocator(ServiceLocator serviceLocator) {
    GlobalConfig.serviceLocator = serviceLocator;
  }

  public static ErrorReportSerializer getErrorReportSerializer() {
    return errorReportSerializer;
  }

  public static void setErrorReportSerializer(ErrorReportSerializer errorReportSerializer) {
    GlobalConfig.errorReportSerializer = errorReportSerializer;
  }

  public static void addDataProvider(ErrorReportDataProvider provider) {
    providers.add(provider);
  }

  public static List<ErrorReportDataProvider> getDataProviders() {
    return providers;
  }

  public static String getServiceEndPoint() {
    return GlobalConfig.serviceEndPoint;
  }

  public static void setServiceEndPoint(String serviceEndPoint) {
    GlobalConfig.serviceEndPoint = serviceEndPoint;
  }

  public static String getApiKey() {
    return GlobalConfig.apiKey;
  }

  public static void setApiKey(String apiKey) {
    GlobalConfig.apiKey = apiKey;
  }

  public static String getToken() {
    return GlobalConfig.token;
  }

  public static void setToken(String token) {
    GlobalConfig.token = token;
  }
}


text:
from __future__ import unicode_literals

import mock
import os
import unittest

from mkdocs import nav, utils, exceptions
from mkdocs.tests.base import dedent

class UtilsTests(unittest.TestCase):
    def test_html_path(self):
        expected_results = {
            'index.md': 'index.html',
            'api-guide.md': 'api-guide/index.html',
            'api-guide/index.md': 'api-guide/index.html',
            'api-guide/testing.md': 'api-guide/testing/index.html',
        }
        for file_path, expected_html_path in expected_results.items():
            html_path = utils.get_html_path(file_path)
            self.assertEqual(html_path, expected_html_path)

    def test_url_path(self):
        expected_results = {
            'index.md': '/',
            'api-guide.md': '/api-guide/',
            'api-guide/index.md': '/api-guide/',
            'api-guide/testing.md': '/api-guide/testing/',
        }
        for file_path, expected_html_path in expected_results.items():
            html_path = utils.get_url_path(file_path)
            self.assertEqual(html_path, expected_html_path)

    def test_is_markdown_file(self):
        expected_results = {
            'index.md': True,
            'index.MARKDOWN': True,
            'index.txt': False,
            'indexmd': False
        }
        for path, expected_result in expected_results.items():
            is_markdown = utils.is_markdown_file(path)
            self.assertEqual(is_markdown, expected_result)

    def test_is_html_file(self):
        expected_results = {
            'index.htm': True,
            'index.HTML': True,
            'index.txt': False,
            'indexhtml': False
        }
        for path, expected_result in expected_results.items():
            is_html = utils.is_html_file(path)
            self.assertEqual(is_html, expected_result)

    def test_create_media_urls(self):
        pages = [
            {'Home': 'index.md'},
            {'About': 'about.md'},
            {'Sub': [
                {'Sub Home': 'index.md'},
                {'Sub About': 'about.md'},

            ]}
        ]
        expected_results = {
            'https://media.cdn.org/jq.js': 'https://media.cdn.org/jq.js',
            'http://media.cdn.org/jquery.js': 'http://media.cdn.org/jquery.js',
            '//media.cdn.org/jquery.js': '//media.cdn.org/jquery.js',
            'media.cdn.org/jquery.js': './media.cdn.org/jquery.js',
            'local/file/jquery.js': './local/file/jquery.js',
            'image.png': './image.png',
        }
        site_navigation = nav.SiteNavigation(pages)
        for path, expected_result in expected_results.items():
            urls = utils.create_media_urls(site_navigation, [path])
            self.assertEqual(urls[0], expected_result)

    def test_create_relative_media_url_sub_index(self):
        '''
        test special case where there's a sub/index.md page
        '''

        site_navigation = nav.SiteNavigation([
            {'Home': 'index.md'},
            {'Sub': [
                {'Sub Home': '/subpage/index.md'},

            ]}
        ])
        site_navigation.url_context.set_current_url('/subpage/')
        site_navigation.file_context.current_file = "subpage/index.md"

        def assertPathGenerated(declared, expected):
            url = utils.create_relative_media_url(site_navigation, declared)
            self.assertEqual(url, expected)

        assertPathGenerated("img.png", "./img.png")
        assertPathGenerated("./img.png", "./img.png")
        assertPathGenerated("/img.png", "../img.png")

    def test_reduce_list(self):
        self.assertEqual(
            utils.reduce_list([1, 2, 3, 4, 5, 5, 2, 4, 6, 7, 8]),
            [1, 2, 3, 4, 5, 6, 7, 8]
        )

    def test_get_themes(self):

        self.assertEqual(
            sorted(utils.get_theme_names()),
            sorted(['flatly', 'cerulean', 'slate', 'bootstrap', 'yeti',
                    'spacelab', 'united', 'readable', 'simplex', 'mkdocs',
                    'cosmo', 'journal', 'cyborg', 'readthedocs', 'amelia']))

    @mock.patch('pkg_resources.iter_entry_points', autospec=True)
    def test_get_themes_warning(self, mock_iter):

        theme1 = mock.Mock()
        theme1.name = 'mkdocs2'
        theme1.dist.key = 'mkdocs2'
        theme1.load().__file__ = "some/path1"

        theme2 = mock.Mock()
        theme2.name = 'mkdocs2'
        theme2.dist.key = 'mkdocs3'
        theme2.load().__file__ = "some/path2"

        mock_iter.return_value = iter([theme1, theme2])

        self.assertEqual(
            sorted(utils.get_theme_names()),
            sorted(['mkdocs2', ]))

    @mock.patch('pkg_resources.iter_entry_points', autospec=True)
    @mock.patch('pkg_resources.get_entry_map', autospec=True)
    def test_get_themes_error(self, mock_get, mock_iter):

        theme1 = mock.Mock()
        theme1.name = 'mkdocs'
        theme1.dist.key = 'mkdocs'
        theme1.load().__file__ = "some/path1"

        theme2 = mock.Mock()
        theme2.name = 'mkdocs'
        theme2.dist.key = 'mkdocs2'
        theme2.load().__file__ = "some/path2"

        mock_iter.return_value = iter([theme1, theme2])
        mock_get.return_value = {'mkdocs': theme1, }

        self.assertRaises(exceptions.ConfigurationError, utils.get_theme_names)

    def test_nest_paths(self):

        j = os.path.join

        result = utils.nest_paths([
            'index.md',
            j('user-guide', 'configuration.md'),
            j('user-guide', 'styling-your-docs.md'),
            j('user-guide', 'writing-your-docs.md'),
            j('about', 'contributing.md'),
            j('about', 'license.md'),
            j('about', 'release-notes.md'),
        ])

        self.assertEqual(
            result,
            [
                'index.md',
                {'User guide': [
                    j('user-guide', 'configuration.md'),
                    j('user-guide', 'styling-your-docs.md'),
                    j('user-guide', 'writing-your-docs.md')]},
                {'About': [
                    j('about', 'contributing.md'),
                    j('about', 'license.md'),
                    j('about', 'release-notes.md')]}
            ]
        )

    def test_unicode_yaml(self):

        yaml_src = dedent(
            '''
            key: value
            key2:
              - value
            '''
        )

        config = utils.yaml_load(yaml_src)
        self.assertTrue(isinstance(config['key'], utils.text_type))
        self.assertTrue(isinstance(config['key2'][0], utils.text_type))


text:
module Fixnames
  module Helpers
    def safeloop(condition, max_tries = option.max_filter_loops, &block)
      max_tries.times do
        return fixed unless fixed =~ Regexp.new(condition)
        block.call
      end
    end

    def replace(re, replacement)
      re_str = bold "/#{re}/"
      replacement_str = bold "\"#{replacement}\""
      debug "\t<replace>  #{re_str}  ->  #{replacement_str}"
      fixed.gsub! Regexp.new(re), replacement
    end

    def remove(re)
      re_str = bold "/#{re}/"
      debug "\t<expunge>  #{re_str}"
      fixed.gsub! Regexp.new(re), ''
    end

    def replace_all(condition, replacement)
      safeloop(condition) { replace(condition, replacement) }
    end

    def remove_all(condition)
      safeloop(condition) { remove(condition) }
    end

    def translate(src, dst)
      debug "\t<translate>  #{bold src.inspect}  ->  #{bold dst.inspect}"
      fixed.tr! src, dst
    end

    def match_bracket_open
      "[#{Regexp.escape(option.bracket_characters_open)}]"
    end

    def match_bracket_close
      "[#{Regexp.escape(option.bracket_characters_close)}]"
    end

    def wrap_brackets(re)
      "#{match_bracket_open}#{re}#{match_bracket_close}"
    end

    def remove_bracket_ranges(re)
      remove wrap_brackets(".*?#{re}.*?")
    end

    def remove_bracket_characters_from(str)
      str.gsub /(#{match_bracket_open}|#{match_bracket_close})/, ''
    end
  end
end


text:
module ActsAsConfigurable
end
current_dir = File.dirname(__FILE__)
%w( acts_methods configuration_store ).each do |to_load|
  require "#{current_dir}/acts_as_configurable/#{to_load}"
end


text:
package org.drools.guvnor.client.widgets.drools.wizards.assets.decisiontable;

import java.util.List;

import org.drools.ide.common.client.modeldriven.dt52.ConditionCol52;

import com.google.gwt.user.client.ui.IsWidget;

/**
 * View and Presenter definitions for the Column Expansion page
 */
public interface ColumnExpansionPageView
        extends
        IsWidget {

    interface Presenter {

        void setColumnsToExpand(List<ConditionCol52> columns);

    }

    /**
     * Set the Presenter for the View to callback to
     *
     * @param presenter
     */
    void setPresenter(Presenter presenter);

    void setAvailableColumns(List<ConditionCol52> columns);

    void setAreConditionsDefined(boolean areConditionsDefined);

}


text:
import os
import sys
from goanna.client import GoannaClient
from goanna.exceptions import UsageError, ConnectionError
from goanna.client.utils.svn import GitRefListParser

# To make requests via a web proxies, set the http_proxy environment var.
# Alternatively, set it from within the script, e.g.
#    os.environ["http_proxy"] = "http://proxy_url:8080"

def main():
    usage = """usage: %prog [options] PROJECT_NAME

Submit change information to Goanna server. This is meant to be run from
a Git post-receive hook script."""

    from optparse import OptionParser
    fallback_config = os.path.join(os.getcwd(), "goanna_client_config.py")
    parser = OptionParser(usage=usage)
    parser.add_option("-c", "--config-file",
                      help="Configuration file to use",
                      dest="cfg_file",
                      metavar="FILE")

    try:
        (opts, (project)) = parser.parse_args()
    except:
        return parser.print_help()

    try:
        if not opts.cfg_file:
            raise UsageError("Config file not specified")
        client = GoannaClient.load_using_config(opts.cfg_file)
        parser = GitRefListParser(sys.stdin)
        client.add_changes(parser.get_changes(project))
        client.submit()
    except (UsageError, ConnectionError) as E:
        sys.stderr.write("ERROR: %s\n" % E)
        return 1

if __name__ == "__main__":
    import sys
    sys.exit(main())


text:
package archivos;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

public class ArchivosMain {

	public static void init(){

		BasicasArchivo ba = new BasicasArchivo();
//		ArchivosMain.imprimeRutaEjecucion();
//		ArchivosMain.printVmProperties();

//		ba.lanzarSelector();
		ba.escribirArchivo();

	}

	/**
	 * Imprime la ruta donde se buscan los archivos para leer
	 *
	 */
	public static void imprimeRutaEjecucion(){

		File dir = new File("");

		System.out.println("Ruta \n" + dir.getAbsolutePath());

		try {
			System.out.println("dir.getCanonicalPath() : " + dir.getCanonicalPath());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	 public static void printVmProperties(){
		 Properties props = System.getProperties();
		 Enumeration<?> keys = props.keys();

		 while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			String valor = (String) props.get(key);
			System.out.println(key +" : "+ valor);

		}

	 }

}