text:
/*
 * Created on Mar 11, 2004
 *
 */
package net.sf.appia.xml.templates;

import java.util.Hashtable;
import java.util.LinkedList;

import net.sf.appia.core.AppiaCursorException;
import net.sf.appia.core.AppiaInvalidQoSException;
import net.sf.appia.core.Channel;
import net.sf.appia.core.ChannelCursor;
import net.sf.appia.core.EventScheduler;
import net.sf.appia.core.Layer;
import net.sf.appia.core.QoS;
import net.sf.appia.core.Session;
import net.sf.appia.core.memoryManager.MemoryManager;
import net.sf.appia.management.jmx.JMXConfiguration;
import net.sf.appia.xml.AppiaXMLException;
import net.sf.appia.xml.interfaces.InitializableSession;
import net.sf.appia.xml.utils.ChannelProperties;
import net.sf.appia.xml.utils.SessionProperties;
import net.sf.appia.xml.utils.SharingState;

/**
 * This class implements a channel template. It is used to generate one or more
 * channels that have identical QoS.
 *
 * @author Jose Mocito
 *
 */
public class ChannelTemplate {

		// Template name
		private String name;
		// Session templates
		private LinkedList sessionTemplates;

		/**
		 * Builds a channel template.
		 *
		 * @param name the template's name.
		 */
		public ChannelTemplate(String name) {
			this.name = name;
			sessionTemplates = new LinkedList();
		}

		/**
		 * @return Returns the name.
		 */
		public String getName() {
			return name;
		}

		/**
		 * @return Returns the sessionTemplates.
		 */
		public LinkedList getSessionTemplates() {
			return sessionTemplates;
		}

		/**
		 * Adds a session to the channel template.
		 *

		 * First session added corresponds to the bottom most layer.
		 *
		 * @param name the name of the session.
		 * @param sharing the sharing property of the session.
		 * @param layer the layer associated with the session.
		 * @see SharingState
		 */
		public void addSession(String name, int sharing, Layer layer) {
			sessionTemplates.add(new SessionTemplate(name,sharing,layer));
		}

		/**
		 *
Returns the number of layers defined in this template.

		 *
		 * @return the number of layers defined in this template.
		 */
		public int numberOfLayers() {
			return sessionTemplates.size();
		}

		/**
		 * Creates a channel.
		 *

		 * Channel returned is not initialized!
		 *
		 * @param name the name of the channel.
		 * @param label the label of the channel or null if none is defined.
		 * @param params the parameters passed to the channel.
		 * @param globalSessions Hashtable containing the
		 * 	shared "global sessions".
		 * @param labelSessions Hashtable containing the
		 * 	shared "label sessions".
		 * @return the channel created.
		 * @throws AppiaException
		 */
		/*public Channel createChannel(
				String name,
				String label,
				ChannelProperties params,
				Hashtable globalSessions,
				Hashtable labelSessions)
		throws AppiaException {
			return createChannel(name,label,params,globalSessions,labelSessions,null);
		}*/

		/**
		 * Creates a channel.
		 *

		 * Channel returned is not initialized!
		 *
		 * @param name the name of the channel.
		 * @param label the label of the channel or null if none is defined.
		 * @param params the parameters passed to the channel.
		 * @param globalSessions Hashtable containing the
		 * 	shared "global sessions".
		 * @param labelSessions Hashtable containing the
		 * 	shared "label sessions".
		 * @param eventScheduler the EventScheduler associated with the channel.
		 * @return the channel created.
		 * @throws AppiaXMLException
		 */
		public Channel createChannel(
				String name,
				String label,
				ChannelProperties params,
				Hashtable globalSessions,
				Hashtable labelSessions,
				EventScheduler eventScheduler,
                MemoryManager memoryManager,
                JMXConfiguration jmxConfig)
		throws AppiaXMLException {
			// Complete name is equal to the given name plus the template name
			//String completeName = name + " " + this.name;
			final int numberOfSessions = sessionTemplates.size();
			final Layer[] qosList = new Layer[numberOfSessions];
			SessionTemplate currSession = null;
			// Generates the QoS
			for (int i = 0; i < numberOfSessions; i++) {
				currSession = (SessionTemplate) sessionTemplates.get(i);
				qosList[i] = currSession.layerInstance();
			}
			QoS qos = null;
			try {
                qos = new QoS(name+" QoS",qosList);
            } catch (AppiaInvalidQoSException e) {
                throw new AppiaXMLException("Unable to create QoS: "+name+" QoS",e);
            }
			// Creates the channel based on the QoS
			Channel channel;
			if (eventScheduler == null && memoryManager == null)
				channel = qos.createUnboundChannel(name,jmxConfig);
			else if (eventScheduler == null && memoryManager != null)
				channel = qos.createUnboundChannel(name,memoryManager,jmxConfig);
			else if (eventScheduler != null && memoryManager == null)
				channel = qos.createUnboundChannel(name,eventScheduler,jmxConfig);
			else
				channel = qos.createUnboundChannel(name,eventScheduler,memoryManager,jmxConfig);
			final ChannelCursor cc = channel.getCursor();
			cc.bottom();
			// Associates the sessions to their corresponding layers
			for (int i = 0; i < numberOfSessions; i++) {
				currSession = (SessionTemplate) sessionTemplates.get(i);
				Session sessionInstance = null;
				// if "global session" then use only global sessions table.
				if (currSession.getSharingState() == SharingState.GLOBAL)
					sessionInstance = currSession.sessionInstance(label,globalSessions);
				// else (is label or private) use only label sessions table.
				else
					sessionInstance = currSession.sessionInstance(label,labelSessions);
				// Verifies if the session accepts parameters and if
				// they are present in the configuration passes them to
				// the session.
				if (sessionInstance instanceof InitializableSession &&
						params != null &&
						params.containsKey(currSession.getName())) {
					final SessionProperties parameters =
						params.getParams(currSession.getName());
					((InitializableSession)sessionInstance).init(parameters);
				}
				try {
                    cc.setSession(sessionInstance);
                } catch (AppiaCursorException e) {
                    throw new AppiaXMLException("Unable to set the session "+sessionInstance+
                            " on channel " + channel.getChannelID()+": "+e.getMessage(),e);
                }
                try {
                    cc.up();
                } catch (AppiaCursorException e) {
                    throw new AppiaXMLException("Unable to move the cursor up, on channel " + channel.getChannelID()+".",e);
                }
			}
			return channel;
		}

		/**
		 * FOR TESTING PURPOSES ONLY!
		 */
		public void printChannelTemplate() {
			final Object [] staux = sessionTemplates.toArray();
			final SessionTemplate[] st = new SessionTemplate[staux.length];
			for (int i = 0; i < staux.length; i++)
				st[i] = (SessionTemplate) staux[i];

			System.out.println("Template Name: "+name);
			for (int i = 0; i < sessionTemplates.size(); i++)
				st[i].printSessionTemplate();
		}
}


text:
export const appendCSRFtoken = (formData) => {
  const CSRFparam = document.querySelector('meta[name="csrf-param"]').content;
  const CSRFtoken = document.querySelector('meta[name="csrf-token"]').content;

  formData.append(CSRFparam, CSRFtoken);

  return formData;
};

export const checkStatus = (response) => {
  if (response.ok) {
    return response;
  } else {
    const error = new Error(response.statusText);

    error.response = response;
    throw error;
  }
};

export const checkFlashMessages = (response) => {
  const flashMessages = JSON.parse(response.headers.get('X-Flash-Messages'));

  if (flashMessages) {
    const error = new Error('X-Flash-Messages');

    error.response = response;
    error.flashMessages = flashMessages;
    throw error;
  } else {
    return response;
  }
};

export const getJSON = (response) => {
  const contentType = response.headers.get('Content-Type');

  if (/application\/json/.test(contentType)) {
    return response.json();
  } else {
    const error = new Error('Response is not a valid JSON');

    error.response = response;
    throw error;
  }
};

export const checkFormErrors = (json) => {
  const formErrors = json.form_errors;

  if (formErrors) {
    const error = new Error('Form errors');

    error.formErrors = formErrors;
    throw error;
  } else {
    return json;
  }
};

export const createFetchHandler = ({ method, endpoint, onRequest, onSuccess, onFailure }) => (
  (formData = new FormData()) => (
    (dispatch, getState) => {
      onRequest && onRequest(dispatch, getState);

      const fetchParams = {
        body: appendCSRFtoken(formData),
        credentials: 'same-origin',
        method
      };

      const handleData = (data) => onSuccess && onSuccess(data, dispatch, getState);
      const handleError = (error) => onFailure && onFailure(error, dispatch, getState);

      return fetch(endpoint, fetchParams)
        .then(checkStatus)
        .then(checkFlashMessages)
        .then(getJSON)
        .then(checkFormErrors)
        .then(handleData)
        .catch(handleError);
    }
  )
);

redpajama_set_name: RedPajamaGithub


text: TODO: write about page here... **OR** delete this file if not required.


text:
/* General styles */
.table-of-contents {
	font-size: .8em;
	display: inline-block;
}
.table-of-contents.toc,
.table-of-contents.minitoc {
	background-color: #F8F8F8;
	box-shadow: 0 0 5px 0 rgba(50, 50, 50, 0.4);
	padding: 1em 2em;
	min-width: 33.3%;
	max-width: 25%;
}
.table-of-contents.toc {
	float: right;
	margin: 0 0 2em 2em;
}

/* TOC elements */
.table-of-contents .toctitle {
	display: block;
	font-size: larger;
	font-weight: bold;
	margin-bottom: .5em;
}
.table-of-contents ul {
	list-style: none;
	padding: 0;
	margin: 0;
}
.table-of-contents > ul {
	margin-left: 1.5em;
}
.table-of-contents ul ul {
	padding: 0 1em;
}
.table-of-contents li {
	margin: 0 0 .25em;
	display: block;
	color: #808080;
}
.table-of-contents .toclink:before {
	content: "\00BB"; 									/* » */
	display: inline;
	margin-right: 0.5ex;
}
.toclink {
	margin-left: -1em;
}

/* Mini TOC */
.table-of-contents.minitoc {
	margin: -1em 0;
}

/* Blog adjustments */
.list-item {
	clear: right;
	display: inline-block;
	width: 100%;
}

/* Anchorlinks */
.headeranchor-link {
	color: inherit;
	display: inline-block;
	outline: none;
	position: relative;
}
.headeranchor-link:before,
.headeranchor-link-left:before {
	content: attr(data-icon);   	 					/* "\2693" Dingsbat anchor */
	display: inline-block;
	margin-left: -1em;
	padding-right: .3em;
	text-align: right;
	text-decoration: none;
	width: 1em;

	position: relative;
	left: -9999px;
	height: 0;
	opacity: 0;
	visibility: hidden;

	transition: opacity .4s ease-in-out 0s
}
.headeranchor-link:hover:before,
.headeranchor-link.headeranchor-visible-always:before {
	left: 0;
	height: auto;
	opacity: 1;
	visibility: visible;
}
.headeranchor-link-right:hover:before,
.headeranchor-link-right.headeranchor-visible-always:before {
	left: calc(100% + 1.1em);
}
.headeranchor-link.no-anchor:hover:before {
	left: -9999px;
	height: 0;
	opacity: 0;
	visibility: hidden;
}

/* Toc links */
.toclink code,
.headeranchor-link code {
	font-size: inherit;
	vertical-align: inherit;
}
.toclink:hover code,
.headeranchor-link:hover code {
	color: inherit;
}


text:
package questions.chapter3;

import java.util.Arrays;
import java.util.List;

public class ForEach04 {

    public ForEach04() {
        List<String> texts = Arrays.asList("Java", "JavaScript", "Ruby", "Pearl", "PHP", "Scala", "Groovy");

        printList(texts);
    }

    private void printList(List<String> texts) {
        for (String text: texts) {
            String lowerText = text.toLowerCase();

            if (lowerText.startsWith("j")) {
                System.out.println(lowerText);
            }
        }
    }

    public static void main(String... args) {
        new ForEach04();
    }
}


text:
import { Component, Input } from '@angular/core';

import { UserService } from './../../services/user-service';
import { PostService } from './../post.service';
import { PostUploadComponent } from './../shared/post-upload.component';
import { IPost } from './../post';

const DEFAULT_CATEGORY: String = 'other';

class Post implements IPost {
    constructor(public _id: String,
        public title: String,
        public category: String,
        public author: String,
        public createdOn: Date,
        public imageName: String,
        public imagePath: String,
        public likes: Number,
        public comments: String[] = null,
        public usersLiked: String[] = null
    ) { }
}

@Component({
    moduleId: module.id,
    templateUrl: './post.component.html'
})
export class PostCreateComponent {
    private author: String;
    private imageName: String;
    private imagePath: String;
    private post: Post;

    public title: String;
    public selectedCategory: String = DEFAULT_CATEGORY;
    public categories: String[];
    public error: Boolean;
    public errorMessage: String;

    constructor(private userService: UserService, private postService: PostService) {
        this.categories = ['fun', 'chilling', 'crazy', 'extreme', 'party',
            'celebration', 'kifla', 'other'];
    }

    public createPost(): void {
        if (this.imageName == '' || this.imagePath == '') {
            this.handleError('No image uploaded. Please upload image before posting!');
            return;
        }

        if (!this.title || this.title === '') {
            this.handleError('Title is missing!');
            return;
        }

        this.userService.getLoggedUser()
            .subscribe((res) => {
                if (!res.user) {
                    this.handleError('No user is logged in!');
                    return;
                }

                let author = res.user.username;
                let post = new Post(null, this.title, this.selectedCategory, author, new Date(), this.imageName, this.imagePath, 0);
                this.postService.createPost(post)
                    .subscribe((dbPost) => { this.userService.addPost(author, dbPost).subscribe((resp) => console.log(resp), (err) => console.log(err)) });
            });
    }

    public onUploaded(file: any): void {
        if (file !== undefined) {
            this.imageName = file.filename;
            this.imagePath = file.path;
        }
    }

    private handleError(msg: String) {
        this.error = true;
        this.errorMessage = msg;
        return setTimeout(() => {
            this.error = false;
        }, 2500);
    }
}


text:
var gulp = require('gulp'),
	paths = require('./config/paths'),
	plumber = require('gulp-plumber'),
	rigger = require('gulp-rigger'),
	rename = require('gulp-rename');

// Concatenate & Minify JS
gulp.task('rigger:main', function() {
	return gulp.src([
		paths.dev.js + '/*.js',
		'!' + paths.dev.js + '/*.min.js'
	])
		.pipe(plumber())
		.pipe(rigger())
		.pipe(rename({suffix: '.min'}))
		.pipe(gulp.dest(paths.build.js));
});


text:
import { WidgetHeader } from "../widget_header";
import { mount } from "enzyme";
import { docLink } from "../doc_link";

describe("<WidgetHeader />", () => {
  it("renders title", () => {
    const wrapper = mount(WidgetHeader({
      title: "fakeWidget"
    }));
    expect(wrapper.html()).toContain("fakeWidget");
  });

  it("renders children", () => {
    const wrapper = mount(WidgetHeader({
      title: "fakeWidget",
      children: "children"
    }));
    expect(wrapper.html()).toContain("children");
  });

  it("renders helpText", () => {
    const wrapper = mount(WidgetHeader({
      title: "fakeWidget",
      helpText: "fakeHelp"
    }));
    expect(wrapper.html()).toContain("fakeHelp");
    expect(wrapper.html()).not.toContain("a href");
  });

  it("renders docs link", () => {
    const wrapper = mount(WidgetHeader({
      title: "fakeWidget",
      helpText: "fakeHelp",
      docPage: "farmware"
    }));
    expect(wrapper.html())
      .toContain(docLink("farmware"));
    expect(wrapper.text()).toContain("Documentation");
    expect(wrapper.html()).toContain("fa-external-link");
  });
});


text:
package org.apache.ignite.internal.processors.igfs;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.igfs.IgfsMode;
import org.apache.ignite.igfs.IgfsPath;
import org.apache.ignite.internal.util.GridBoundedConcurrentLinkedHashMap;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.jetbrains.annotations.Nullable;

/**
 *
 */
public class IgfsModeResolver implements Externalizable {
    /** */
    private static final long serialVersionUID = 0L;

    /** Maximum size of map with cached path modes. */
    private static final int MAX_PATH_CACHE = 1000;

    /** Default mode. */
    private IgfsMode dfltMode;

    /** Modes for particular paths. Ordered from longest to shortest. */
    private List<T2<IgfsPath, IgfsMode>> modes;

    /** Cached modes per path. */
    private Map<IgfsPath, IgfsMode> modesCache;

    /** Set to store parent dual paths that have primary children. */
    private Set<IgfsPath> dualParentsWithPrimaryChildren;

    /**
     * Empty constructor required by {@link Externalizable}.
     */
    public IgfsModeResolver() {
        // No-op.
    }

    /**
     * Constructor
     *
     * @param dfltMode Default IGFS mode.
     * @param modes List of configured modes. The order is significant as modes are added in order of occurrence.
     * @throws IgniteCheckedException On error.
     */
    public IgfsModeResolver(IgfsMode dfltMode, @Nullable ArrayList<T2<IgfsPath, IgfsMode>> modes)
            throws IgniteCheckedException {
        assert dfltMode != null;

        this.dfltMode = dfltMode;

        dualParentsWithPrimaryChildren = new HashSet<>();

        this.modes = IgfsUtils.preparePathModes(dfltMode, modes, dualParentsWithPrimaryChildren);

        if (modes != null)
            modesCache = new GridBoundedConcurrentLinkedHashMap<>(MAX_PATH_CACHE);
    }

    /**
     * Resolves IGFS mode for the given path.
     *
     * @param path IGFS path.
     * @return IGFS mode.
     */
    public IgfsMode resolveMode(IgfsPath path) {
        assert path != null;

        if (modes == null)
            return dfltMode;
        else {
            IgfsMode mode = modesCache.get(path);

            if (mode == null) {
                for (T2<IgfsPath, IgfsMode> entry : modes) {
                    if (F.eq(path, entry.getKey()) || path.isSubDirectoryOf(entry.getKey())) {
                        // As modes ordered from most specific to least specific first mode found is ours.
                        mode = entry.getValue();

                        break;
                    }
                }

                if (mode == null)
                    mode = dfltMode;

                modesCache.put(path, mode);
            }

            return mode;
        }
    }

    /**
     * Answers if the given path has an immediate child of PRIMARY mode.
     *
     * @param path The path to query.
     * @return If the given path has an immediate child of PRIMARY mode.
     */
    public boolean hasPrimaryChild(IgfsPath path) {
        return dualParentsWithPrimaryChildren.contains(path);
    }

    /** {@inheritDoc} */
    @Override public void writeExternal(ObjectOutput out) throws IOException {
        U.writeEnum(out, dfltMode);

        if (modes != null) {
            out.writeBoolean(true);
            out.writeInt(modes.size());

            for (T2<IgfsPath, IgfsMode> pathMode : modes) {
                assert pathMode.getKey() != null;

                pathMode.getKey().writeExternal(out);

                U.writeEnum(out, pathMode.getValue());
            }
        }
        else
            out.writeBoolean(false);

        if (!F.isEmpty(dualParentsWithPrimaryChildren)) {
            out.writeBoolean(true);
            out.writeInt(dualParentsWithPrimaryChildren.size());

            for (IgfsPath p : dualParentsWithPrimaryChildren)
                p.writeExternal(out);
        }
        else
            out.writeBoolean(false);

    }

    /** {@inheritDoc} */
    @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        dfltMode = IgfsMode.fromOrdinal(in.readByte());

        if (in.readBoolean()) {
            int size = in.readInt();

            modes = new ArrayList<>(size);

            for (int i = 0; i < size; i++) {
                IgfsPath path = IgfsUtils.readPath(in);

                modes.add(new T2<>(path, IgfsMode.fromOrdinal(in.readByte())));
            }

            modesCache = new GridBoundedConcurrentLinkedHashMap<>(MAX_PATH_CACHE);
        }

        dualParentsWithPrimaryChildren = new HashSet<>();

        if (in.readBoolean()) {
            int size = in.readInt();

            for (int i = 0; i < size; i++)
                dualParentsWithPrimaryChildren.add(IgfsUtils.readPath(in));
        }
    }
}


text:
package com.fujitsu.fac.activities.surveys;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.fujitsu.fac.R;
import com.fujitsu.fac.domain.Survey;
import com.fujitsu.fac.services.EventService;

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

import roboguice.activity.RoboListActivity;
import roboguice.inject.InjectView;

public class SurveyActivity extends RoboListActivity {

    @InjectView(R.id.back_button)
    private View backBtn;

    @InjectView(R.id.submit_button)
    private View submitBtn;

    private Dialog surveyQuestionsDialog = null;

    private List<Survey> surveyList = null;
    private List<String> surveyAnswerList = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_survey);

        surveyList = EventService.getInstance().getCurrentEvent().getSurveyList();

        surveyAnswerList = new ArrayList<String>();
        for(int i=0; i<surveyList.size(); i++) {
            surveyAnswerList.add("");
        }

        System.out.println("+++ "+surveyList.size());
        System.out.println("+++ "+surveyAnswerList);

        SurveyListAdapter surveyListAdapter = new SurveyListAdapter(R.layout.list_row_surveys, surveyList);
        this.setListAdapter(surveyListAdapter);

        this.backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        this.submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("+++ SUBMIT CLICKED");

                System.out.println("+++ "+surveyAnswerList);
            }
        });
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(
                SurveyActivity.this);
        dialogBuilder.setView(prepareDialogCustomView(position));
        this.surveyQuestionsDialog = dialogBuilder.create();
        this.surveyQuestionsDialog.show();
    }

    private View prepareDialogCustomView(int position) {

        View v = (View) getLayoutInflater().inflate(
                R.layout.dialog_survey_questions, null);

        final SurveyAnswersListAdapter surveyAnswersListAdapter
                = new SurveyAnswersListAdapter(R.layout.list_row_survey_choices, this.surveyList.get(position).getChoices());

        ListView lv = (ListView) v.findViewById(R.id.item_type_list_view);
        lv.setAdapter(surveyAnswersListAdapter);

        View dialogBottomBar = (View) v.findViewById(R.id.dialog_bottom_bar);
        dialogBottomBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SurveyActivity.this.surveyQuestionsDialog.dismiss();
            }
        });

        return v;
    }

    private class SurveyAnswersListAdapter extends BaseAdapter {

        private int viewResourceId;
        private List<String> surveyChoicesList;
        private RadioButton selectedRadioButton = null;

        public SurveyAnswersListAdapter(int viewResourceId, List<String> surveyAnswersList) {
            this.viewResourceId = viewResourceId;
            this.surveyChoicesList = surveyAnswersList;
        }

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

        @Override
        public Object getItem(int position) {
            return surveyChoicesList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            View row = convertView;
            final MyPlaceHolder holder;

            if (row == null) {

                LayoutInflater inflater = (LayoutInflater) SurveyActivity.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(this.viewResourceId, parent, false);
                holder = new MyPlaceHolder();

                holder.radioSurveyAnswer = (RadioButton) row.findViewById(R.id.radio_survey);

                row.setTag(holder);
            } else {
                holder = (MyPlaceHolder) row.getTag();
            }

            final String s = surveyChoicesList.get(position);

            if (position == getCount() - 1) {
                if (selectedRadioButton == null) {
                    holder.radioSurveyAnswer.setChecked(false);
                    //selectedRadioButton = holder.radioSurveyAnswer;
                }
            }

            holder.radioSurveyAnswer.setText(s);
            holder.radioSurveyAnswer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (selectedRadioButton != null) {
                        selectedRadioButton.setChecked(false);
                    }
                    holder.radioSurveyAnswer.setChecked(true);
                    selectedRadioButton = holder.radioSurveyAnswer;
                    surveyAnswerList.set(position, holder.radioSurveyAnswer.getText().toString());
                }
            });

            return row;
        }

        class MyPlaceHolder {
            RadioButton radioSurveyAnswer;
        }
    }

    private class SurveyListAdapter extends BaseAdapter {

        private int viewResourceId;
        private List<Survey> surveyList;

        public SurveyListAdapter(int viewResourceId, List<Survey> surveyList) {
            this.viewResourceId = viewResourceId;
            this.surveyList = surveyList;
        }

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

        @Override
        public Object getItem(int position) {
            return surveyList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            View row = convertView;
            MyPlaceHolder holder = null;

            if (row == null) {

                LayoutInflater inflater = (LayoutInflater) SurveyActivity.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(this.viewResourceId, parent, false);
                holder = new MyPlaceHolder();

                holder.textQuestion = (TextView) row.findViewById(R.id.text_question);

                row.setTag(holder);
            } else {
                holder = (MyPlaceHolder) row.getTag();
            }

            final Survey s = surveyList.get(position);

            holder.textQuestion.setText(s.getQuestion());

            return row;
        }

        class MyPlaceHolder {
            TextView textQuestion;
        }
    }
}


text:
package org.intellij.images.editor.actionSystem;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.Presentation;
import org.intellij.images.editor.ImageEditor;
import org.intellij.images.ui.ImageComponentDecorator;

/**
 * Editor actions utility.
 *
 * @author Alexey Efimov
 */
public final class ImageEditorActionUtil {
    private ImageEditorActionUtil() {
    }

    /**
     * Extract current editor from event context.
     *
     * @param e Action event
     * @return Current {@link ImageEditor} or {@code null}
     */
    //public static ImageEditor getValidEditor(AnActionEvent e) {
    //    ImageEditor editor = getEditor(e);
    //    if (editor != null && editor.isValid()) {
    //        return editor;
    //    }
    //    return null;
    //}

    public static ImageComponentDecorator getImageComponentDecorator(AnActionEvent e) {
        DataContext dataContext = e.getDataContext();
        return ImageComponentDecorator.DATA_KEY.getData(dataContext);
    }

    /**
     * Enable or disable current action from event.
     *
     * @param e Action event
     * @return Enabled value
     */
    public static boolean setEnabled(AnActionEvent e) {
        ImageComponentDecorator decorator = getImageComponentDecorator(e);
        Presentation presentation = e.getPresentation();
        presentation.setEnabled(decorator != null);
        return presentation.isEnabled();
    }
}


text:
<?php

namespace Org_Heigl\DateFormatter\Service;

use Org_Heigl\DateFormatter\UnknownFormatException;
use Org_Heigl\FileFinder\ClassMapList;
use Org_Heigl\FileFinder\FileFinder;
use Org_Heigl\FileFinder\Filter\ClassIsInstanceof;

class FormatterService
{
    protected static $list;

    protected static $formatterDirectories = [
        __DIR__ . '/../Formatter/',
    ];

    /**
     * @return \Org_Heigl\FileFinder\FileListInterface
     */
    protected static function getList()
    {
        if (! self::$list) {
            $finder = new FileFinder();
            $finder->addFilter(new ClassIsInstanceof(['Org_Heigl\DateFormatter\Formatter\FormatterInterface']));
            $finder->setFileList(new ClassMapList());
            foreach (self::$formatterDirectories as $directory) {
                $finder->addDirectory($directory);
            }
            self::$list = $finder->find();
        }

        return self::$list;
    }

    /**
     * @param string $format
     *
     * @return Org_Heigl\DateFormatter\Formatter\FormatterInterface
     */
    public static function getFormatter($format)
    {
        foreach (self::getList() as $class => $path) {
            if (! in_array(strtolower($format), array_map('strtolower', $class::getFormatString()))) {
                continue;
            }

            return new $class();
        }

        throw new UnknownFormatException('There is no formater for this format');
    }

    /**
     * @param string $folder
     *
     * @return void
     */
    public static function addFormatterFolder($folder)
    {
        if (! is_dir($folder)) {
            return;
        }

        array_unshift(self::$formatterDirectories, $folder);
        self::$list = null;
    }

}


text:
package org.thymeleaf.examples.spring6.sayhello.dialect;

import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;
import org.unbescape.html.HtmlEscape;

public class SayToAttributeTagProcessor extends AbstractAttributeTagProcessor {

    private static final String ATTR_NAME = "sayto";
    private static final int PRECEDENCE = 10000;

    public SayToAttributeTagProcessor(final String dialectPrefix) {
        super(
            TemplateMode.HTML, // This processor will apply only to HTML mode
            dialectPrefix,     // Prefix to be applied to name for matching
            null,              // No tag name: match any tag name
            false,             // No prefix to be applied to tag name
            ATTR_NAME,         // Name of the attribute that will be matched
            true,              // Apply dialect prefix to attribute name
            PRECEDENCE,        // Precedence (inside dialect's precedence)
            true);             // Remove the matched attribute afterwards
    }

    protected void doProcess(
            final ITemplateContext context, final IProcessableElementTag tag,
            final AttributeName attributeName, final String attributeValue,
            final IElementTagStructureHandler structureHandler) {

        structureHandler.setBody(
                "Hello, " + HtmlEscape.escapeHtml5(attributeValue) + "!", false);

    }

}


text:
package com.intellij.codeInsight.dataflow.map;

import com.intellij.codeInsight.dataflow.SetUtil;
import org.jetbrains.annotations.Nullable;

import java.util.*;

/**
 * @author yole
 */
public class DFAMap<V> {

  // invariant:
  // if myAll != null, the map contains more than one value, and all of them are in myAll
  // if myAll == null && myK != null, the map contains only one value (myK, myV)
  // if myAll == null && myK == null, the map is empty
  private String myK;
  private V myV;
  private HashMap<String, V> myAll;

  private static final DFAMap ourEmptyMap = new DFAMap() {
    @Override
    public void put(String key, Object value) {
      throw new UnsupportedOperationException();
    }

    @Override
    public void remove(String name) {
      throw new UnsupportedOperationException();
    }

    @Override
    public DFAMap asWritable() {
      return new DFAMap();
    }
  };

  public DFAMap() {
  }

  private DFAMap(DFAMap<V> initialMap) {
    myK = initialMap.myK;
    myV = initialMap.myV;
    myAll = initialMap.myAll == null ? null : new HashMap<String,V>(initialMap.myAll);
  }

  public static <V> DFAMap<V> empty() {
    //noinspection unchecked
    return (DFAMap<V>) ourEmptyMap;
  }

  public void addKeys(HashSet<String> allNames) {
    if (myAll != null) {
      allNames.addAll(myAll.keySet());
    }
    else if (myK != null) {
      allNames.add(myK);
    }
  }

  public void put(String key, V value) {
    if ((myK == null || myK.equals(key)) && myAll == null) {
      myK = key;
      myV = value;
    }
    else {
      if (myAll == null) {
        myAll = new HashMap<String,V>();
        myAll.put(myK, myV);
      }
      myAll.put(key, value);
    }
  }

  @Nullable
  public V get(String key) {
    if (myAll != null) {
      return myAll.get(key);
    }
    if (key.equals(myK)) {
      return myV;
    }
    return null;
  }

  public void remove(String name) {
    if (myAll != null) {
      myAll.remove(name);
      if (myAll.size() == 1) {
        final Map.Entry<String, V> e = myAll.entrySet().iterator().next();
        myK = e.getKey();
        myV = e.getValue();
        myAll = null;
      }
    }
    else if (name.equals(myK)) {
      myK = null;
      myV = null;
    }
  }

  public boolean containsKey(String name) {
    if (myAll != null) {
      return myAll.containsKey(name);
    }
    return name.equals(myK);
  }

  public Set<String> intersectKeys(@Nullable Set<String> names2Include) {
    if (myAll != null) {
      if (names2Include == null) return myAll.keySet();
      return SetUtil.intersect(names2Include, myAll.keySet());
    }
    if (myK != null && (names2Include == null || names2Include.contains(myK))) {
      if (names2Include != null && names2Include.size() == 1) return names2Include;
      final HashSet<String> result = new HashSet<String>();
      result.add(myK);
      return result;
    }
    return Collections.emptySet();
  }

  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof DFAMap)) return false;
    @SuppressWarnings({"unchecked"}) DFAMap<V> rhs = (DFAMap<V>) obj;
    if (myAll == null) {
      if (rhs.myAll != null) return false;
      if (myK == null) return rhs.myK == null;
      return myK.equals(rhs.myK) && myV.equals(rhs.myV);
    }
    else {
      if (rhs.myAll == null) return false;
      return myAll.equals(rhs.myAll);
    }
  }

  public Collection<V> values() {
    if (myAll != null) {
      return myAll.values();
    }
    if (myV != null) {
      return Collections.singletonList(myV);
    }
    return Collections.emptyList();
  }

  public Collection<? extends Map.Entry<String, V>> entrySet() {
    if (myAll != null) {
      return myAll.entrySet();
    }
    if (myK != null) {
      return Collections.singleton(new Map.Entry<String, V>() {
        @Override
        public String getKey() {
          return myK;
        }

        @Override
        public V getValue() {
          return myV;
        }

        @Override
        public V setValue(V value) {
          throw new UnsupportedOperationException();
        }
      });
    }
    return Collections.emptyList();
  }

  public DFAMap<V> asWritable() {
    return new DFAMap<V>(this);
  }

  @Override
  public String toString() {
    if (this == ourEmptyMap){
      return "Empty Map";
    }
    if (myAll != null){
      return myAll.toString();
    }
    if (myK != null){
      return "{" + myK + "=" + myV + "}";
    }
    return "Empty";
  }

  public Set<String> keySet() {
    if (myAll != null){
      return myAll.keySet();
    }
    return myK != null ? Collections.singleton(myK) : Collections.<String>emptySet();
  }
}


text:
import Logger from '/imports/server/lib/logger';
import { updateInvoiceTicket } from '/imports/server/invoice-ticket-state-machine';
import { setInvoiceTicketFields } from '/imports/server/invoice-ticket-update-manager';
import { secureInvoicesOptionsByRole } from '/server/lib/invoice-tickets-publish-fields';
import { preCancellableStates } from '/imports/server/invoice-ticket-state-machine';

// {key -> stateTransition : value -> [Role]}
const managerStateTransitions = {
  'receiveFunds': ['admin', 'headInvoiceManager', 'bankManager'],
  'cancelFundsReceived': ['admin', 'headInvoiceManager', 'bankChecker'],
  'confirmFundsReceived': ['admin', 'headInvoiceManager', 'bankChecker'],
  'prepareTicket': ['admin', 'headInvoiceManager', 'exporter'],
  'cancelPreparedTicket': ['admin', 'headInvoiceManager', 'exporter'],
  'bundleTicket': ['admin', 'headInvoiceManager', 'exporter'],
  'finalizeBundledTicket': ['admin', 'headInvoiceManager', 'exporter'],
  'exportPayments': ['admin', 'headInvoiceManager', 'exporter'],
  'reviveInvoiceBank': ['admin'],
  'reviveInvoiceBtc': ['admin'],
  'preCancelInvoiceOnReject': ['compliance', 'chiefcompliance', 'headCompliance'],
  'preCancelInvoice': ['headCompliance'],
  'startSaleBank': ['headInvoiceManager'],
  'startSaleBtc': ['headInvoiceManager'],
  'approveInvalidTicket': ['headInvoiceManager'],
  'refundInvalidTicket': ['headInvoiceManager']
};

// security implemented as whitelist
const userHasPermission = function(userId, stateTransition) {
  let hasPermission = false;
  const validRoles = managerStateTransitions[stateTransition];
  if (validRoles !== undefined) {
    hasPermission = Roles.userIsInRole(userId, validRoles);
  }
  return hasPermission;
};

const throwUserUnauthorizedException = function(userId, event) {
  Logger.error(`User[${userId}] has no permission to ${event}`);
  throw new Meteor.Error('unauthorized');
};

// args: fieldName1, field1, fieldName2, field2...
const throwMeteorMethodException = function(methodName, errorName, errorMessage, ...args) {
  Logger.error(methodName + ": " + errorName + " : " + errorMessage + " -", ...args);
  throw new Meteor.Error(errorName, errorMessage);
};

const createManagerRecord = function(userId, stateTransition, ticket) {
  if (_.contains(Object.keys(managerStateTransitions), stateTransition)) {
    StateTransitionRecords.insert({
      invoiceTicketId: ticket._id,
      event: stateTransition,
      managerId: userId,
    });
  }
};

const changeState = function changeState(event, ticket, modifier) {
  const userId = Meteor.user()._id;
  if (!userHasPermission(userId, event)) {
    throwUserUnauthorizedException(userId, event);
  }
  createManagerRecord(userId, event, ticket);
  updateInvoiceTicket(event, ticket, modifier);
};

export const preCancelInvoicesOnReject = function(buyerId) {
  Logger.info('[preCancelInvoicesOnReject - Starting]', `for Buyer[${buyerId}]`);
  check(buyerId, String);
  const tickets = InvoiceTickets.find({
    buyerId: buyerId,
    state: {
      $in: preCancellableStates
    }
  }).fetch();
  Logger.info('[preCancelInvoicesOnReject - Info]', `for Buyer[${buyerId}]`, `${tickets.length} tickets to cancel`);
  tickets.forEach(function(ticket) {
    changeState('preCancelInvoiceOnReject', ticket, undefined);
  });
  Logger.info('[preCancelInvoicesOnReject - Finshied]', `for Buyer[${buyerId}]`);
};

Meteor.methods({
  // options: { buyerId, [usdRequested or centsRequested] }
  // can include any other ticket fields, i.e. options: { paymentOption }
  confirmPurchase: function(options) {
    if (this.userId !== options.buyerId) {
      throw new Meteor.Error(403, '[Error] confirmPurchase: Unauthorized',
        'Only the buyer may confirm a purchase.');
    }

    Logger.info('purchase confirmed for buyerId: ', options.buyerId);
    const role = Meteor.users.getFirstRole(this.userId);
    let ticket = InvoiceTickets.findOne({ buyerId: options.buyerId, state: 'inviteSent' }, secureInvoicesOptionsByRole({}, role));
    Logger.info('ticket: ', ticket);
    return { ticketId: ticket._id };
  },
  updateComment: function(ticketId, newComment) {
    check(ticketId, String);
    check(newComment, String);
    if (!Roles.userIsInRole(this.userId, ['headInvoiceManager', 'admin'])) {
      throwUserUnauthorizedException(this.userId, "updateComment");
    }
    setInvoiceTicketFields(ticketId, {comment: newComment});
  },
  changeState: function(event, ticket, modifier) {
    changeState(event, ticket, modifier);
  },
  getBundleInvoiceTickets: function(bundle) {
    if (!userHasPermission(this.userId, "bundleTicket")) {
      throwUserUnauthorizedException(this.userId, "bundleTicket");
    }
    const role = Meteor.users.getFirstRole(this.userId);
    return InvoiceTickets.find({_id: {$in: bundle.invoiceTicketIds}}, secureInvoicesOptionsByRole({}, role)).fetch();
  },
  createPaymentsBundle: function() {
    Logger.info("createPaymentsBundle: starting");
    if (!userHasPermission(this.userId, "bundleTicket")) {
      throwUserUnauthorizedException(this.userId, "bundleTicket");
    }
    /* mark tickets: change state to 'bundleTicket',
       and return tickets Id's and total yen amount for the Bundle */
    const role = Meteor.users.getFirstRole(this.userId);
    const tickets = InvoiceTickets.find({ state: 'ticketPrepared' }, secureInvoicesOptionsByRole({}, role));
    const bundleTicketIds = [];
    let totalYenAmount = 0;
    tickets.forEach(function(ticket) {
      bundleTicketIds.push(ticket._id);
      totalYenAmount += ticket.yenReceived;
      ticket.changeState('bundleTicket');
    });
    if (bundleTicketIds.length === 0) {
      throwMeteorMethodException("createPaymentsBundle",
        'bundleIsEmpty',
        "Payment Bundle must have at least one invoice ticket",
        "bundleTicketIds", bundleTicketIds);
    }
    Logger.info("createPaymentsBundle: ticket for Bundle change to state: 'bundleTicket' successfully");
    PaymentExports.insert({
      invoiceTicketIds: bundleTicketIds,
      yenAmount: totalYenAmount
    });
    Logger.info("createPaymentsBundle: new Bundle created successfully");
  },
  finalizePaymentsBundle: function(params) {
    // Basic props that are always required
    check(params, Match.ObjectIncluding({
      paymentStrategy: Match.OneOf('YEN', 'USD'),
      _id: String
    }));

    // Check provided exchange rates based on strategy
    if (params.paymentStrategy === 'YEN') {
      check(params, Match.ObjectIncluding({ btcUsd: Number, btcJpy: Number }));
    }
    if (params.paymentStrategy === 'USD') {
      check(params, Match.ObjectIncluding({ btcUsd: Number, jpyUsd: Number }));
    }

    if (!userHasPermission(this.userId, "finalizeBundledTicket")) {
      throwUserUnauthorizedException(this.userId, "finalizeBundledTicket");
    }

    // prepare new export fields
    const exportFields = lodash.pick(params, ['_id', 'jpyUsd', 'btcJpy', 'btcUsd']);
    exportFields.finalized = true;
    exportFields.finalizedAt = new Date();
    const exchangeRates = lodash.pick(params, ['jpyUsd', 'btcJpy', 'btcUsd']);

    // get current export
    const paymentExport = PaymentExports.findOne(exportFields._id);

    // prevent exporting if no holding wallet
    if (paymentExport.holdingWalletAddress === 'false') {
      throw new Meteor.Error('missingHoldingWallet');
    }

    // mark tickets for export and update payment export
    const role = Meteor.users.getFirstRole(this.userId);
    const tickets = InvoiceTickets.find({ _id: { $in: paymentExport.invoiceTicketIds } }, secureInvoicesOptionsByRole({}, role)).fetch();
    exportFields.batchFulfillmentAmount = 0;

    tickets.forEach(function(ticket) {
      const satoshisExpected = InvoiceManager.calculateOrderFulfillmentAmount(
        params.paymentStrategy, ticket.yenReceived, exchangeRates
      );
      const ticketProps = lodash.extend({ satoshisExpected: satoshisExpected }, exchangeRates);
      ticket.changeState('finalizeBundledTicket', ticketProps);
      // Sum up the total satoshis amount of the export
      exportFields.batchFulfillmentAmount += satoshisExpected;
    });

    PaymentExports.update(exportFields._id, { $set: exportFields });
    return PaymentExports.findOne(exportFields._id);

  },
  refundInvalidFunds: function(ticketId, refundTransactionId, refundReason) {
    const userId = Meteor.userId();
    Logger.info('[refundInvalidFunds] - Starting',
                'userId:', userId,
                'ticketId', ticketId,
                'refundTransactionId', refundTransactionId,
                'refundReason', refundReason);
    if (!userHasPermission(userId, "refundInvalidTicket")) {
      throwUserUnauthorizedException(userId, "refundInvalidTicket");
    }
    check(ticketId, String);
    check(refundTransactionId, String);
    check(refundReason, String);
    if (refundTransactionId === '') {
      Logger.error('[refundInvalidFunds] - Error: Transaction Id is empty');
      throw new Meteor.Error('invalidTransactionId');
    }
    if (refundReason === '') {
      Logger.error('[refundInvalidFunds] - Error: Refund Reason is empty');
      throw new Meteor.Error('invalidRefundReason');
    }
    const ticket = InvoiceTickets.findOne({_id: ticketId});
    if (!ticket) {
      Logger.error('[refundInvalidFunds] - Error: Ticket not found', 'ticket:', ticketId);
      throw new Meteor.Error('invoiceNotFound');
    }
    const modifier = {
      refundTransactionId: refundTransactionId,
      refundReason: refundReason,
    };
    createManagerRecord(userId, 'refundInvalidTicket', ticket);
    updateInvoiceTicket('refundInvalidTicket', ticket, modifier);
    Logger.info('[refundInvalidFunds] - Finished succesfully!');
  }

});


text:
#if !defined(SPIRIT_PASS_CONTAINER_MAR_15_2009_0114PM)
#define SPIRIT_PASS_CONTAINER_MAR_15_2009_0114PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/karma/detail/attributes.hpp>
#include <boost/spirit/home/support/container.hpp>
#include <boost/spirit/home/support/handles_container.hpp>
#include <boost/spirit/home/support/detail/hold_any.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/or.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/fusion/include/deduce_sequence.hpp>

#include <boost/mpl/print.hpp>

namespace boost { namespace spirit { namespace karma { namespace detail
{
    // Helper meta-function allowing to evaluate weak substitutability and
    // negate the result if the predicate (Sequence) is not true
    template <typename Sequence, typename Attribute, typename ValueType>
    struct negate_weak_substitute_if_not
      : mpl::if_<
            Sequence
          , typename traits::is_weak_substitute<Attribute, ValueType>::type
          , typename mpl::not_<
                traits::is_weak_substitute<Attribute, ValueType>
            >::type>
    {};

    // pass_through_container: utility to check decide whether a provided
    // container attribute needs to be passed through to the current component
    // or of we need to split the container by passing along instances of its
    // value type

    // if the expected attribute of the current component is neither a Fusion
    // sequence nor a container, we will pass through the provided container
    // only if its value type is not compatible with the component
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence, typename Enable = void>
    struct pass_through_container_base
      : negate_weak_substitute_if_not<Sequence, ValueType, Attribute>
    {};

    // Specialization for fusion sequences, in this case we check whether all
    // the types in the sequence are convertible to the lhs attribute.
    //
    // We return false if the rhs attribute itself is a fusion sequence, which
    // is compatible with the LHS sequence (we want to pass through this
    // attribute without it being split apart).
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence = mpl::true_>
    struct not_compatible_element
      : mpl::and_<
            negate_weak_substitute_if_not<Sequence, Container, Attribute>
          , negate_weak_substitute_if_not<Sequence, ValueType, Attribute> >
    {};

    // If the value type of the container is not a Fusion sequence, we pass
    // through the container if each of the elements of the Attribute
    // sequence is compatible with either the container or its value type.
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence
      , bool IsSequence = fusion::traits::is_sequence<ValueType>::value>
    struct pass_through_container_fusion_sequence
    {
        typedef typename mpl::find_if<
            Attribute, not_compatible_element<Container, ValueType, mpl::_1>
        >::type iter;
        typedef typename mpl::end<Attribute>::type end;

        typedef typename is_same<iter, end>::type type;
    };

    // If both, the Attribute and the value type of the provided container
    // are Fusion sequences, we pass the container only if the two
    // sequences are not compatible.
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence>
    struct pass_through_container_fusion_sequence<
            Container, ValueType, Attribute, Sequence, true>
    {
        typedef typename mpl::find_if<
            Attribute
          , not_compatible_element<Container, ValueType, mpl::_1, Sequence>
        >::type iter;
        typedef typename mpl::end<Attribute>::type end;

        typedef typename is_same<iter, end>::type type;
    };

    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence>
    struct pass_through_container_base<Container, ValueType, Attribute
          , Sequence
          , typename enable_if<fusion::traits::is_sequence<Attribute> >::type>
      : pass_through_container_fusion_sequence<
            Container, ValueType, Attribute, Sequence>
    {};

    // Specialization for containers
    //
    // If the value type of the attribute of the current component is not
    // a Fusion sequence, we have to pass through the provided container if
    // both are compatible.
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence, typename AttributeValueType
      , bool IsSequence = fusion::traits::is_sequence<AttributeValueType>::value>
    struct pass_through_container_container
      : mpl::or_<
            traits::is_weak_substitute<Container, Attribute>
          , traits::is_weak_substitute<Container, AttributeValueType> >
    {};

    // If the value type of the exposed container attribute is a Fusion
    // sequence, we use the already existing logic for those.
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence, typename AttributeValueType>
    struct pass_through_container_container<
            Container, ValueType, Attribute, Sequence, AttributeValueType, true>
      : pass_through_container_fusion_sequence<
            Container, ValueType, AttributeValueType, Sequence>
    {};

    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence>
    struct pass_through_container_base<Container, ValueType, Attribute
          , Sequence
          , typename enable_if<traits::is_container<Attribute> >::type>
      : detail::pass_through_container_container<
          Container, ValueType, Attribute, Sequence
        , typename traits::container_value<Attribute>::type>
    {};

    // Specialization for exposed optional attributes
    //
    // If the type embedded in the exposed optional is not a Fusion
    // sequence we pass through the container attribute if it is compatible
    // either to the optionals embedded type or to the containers value
    // type.
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence
      , bool IsSequence = fusion::traits::is_sequence<Attribute>::value>
    struct pass_through_container_optional
      : mpl::or_<
            traits::is_weak_substitute<Container, Attribute>
          , traits::is_weak_substitute<ValueType, Attribute> >
    {};

    // If the embedded type of the exposed optional attribute is a Fusion
    // sequence, we use the already existing logic for those.
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence>
    struct pass_through_container_optional<
            Container, ValueType, Attribute, Sequence, true>
      : pass_through_container_fusion_sequence<
            Container, ValueType, Attribute, Sequence>
    {};

    ///////////////////////////////////////////////////////////////////////////
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence>
    struct pass_through_container
      : pass_through_container_base<Container, ValueType, Attribute, Sequence>
    {};

    // Handle optional attributes
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence>
    struct pass_through_container<
            Container, ValueType, boost::optional<Attribute>, Sequence>
      : pass_through_container_optional<
            Container, ValueType, Attribute, Sequence>
    {};

    // If both, the containers value type and the exposed attribute type are
    // optionals we are allowed to pass through the the container only if the
    // embedded types of those optionals are not compatible.
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence>
    struct pass_through_container<
            Container, boost::optional<ValueType>, boost::optional<Attribute>
          , Sequence>
      : mpl::not_<traits::is_weak_substitute<ValueType, Attribute> >
    {};

    // Specialization for exposed variant attributes
    //
    // We pass through the container attribute if at least one of the embedded
    // types in the variant requires to pass through the attribute

#define BOOST_SPIRIT_PASS_THROUGH_CONTAINER(z, N, _)                          \
    pass_through_container<Container, ValueType,                              \
        BOOST_PP_CAT(T, N), Sequence>::type::value ||                         \
    /***/

    // make sure unused variant parameters do not affect the outcome
    template <typename Container, typename ValueType, typename Sequence>
    struct pass_through_container<Container, ValueType
          , boost::detail::variant::void_, Sequence>
      : mpl::false_
    {};

    template <typename Container, typename ValueType, typename Sequence
      , BOOST_VARIANT_ENUM_PARAMS(typename T)>
    struct pass_through_container<Container, ValueType
          , boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>, Sequence>
      : mpl::bool_<BOOST_PP_REPEAT(BOOST_VARIANT_LIMIT_TYPES
          , BOOST_SPIRIT_PASS_THROUGH_CONTAINER, _) false>
    {};

#undef BOOST_SPIRIT_PASS_THROUGH_CONTAINER
}}}}

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit { namespace traits
{
    ///////////////////////////////////////////////////////////////////////////
    // forwarding customization point for domain karma::domain
    template <typename Container, typename ValueType, typename Attribute
      , typename Sequence>
    struct pass_through_container<
            Container, ValueType, Attribute, Sequence, karma::domain>
      : karma::detail::pass_through_container<
            Container, ValueType, Attribute, Sequence>
    {};
}}}

namespace boost { namespace spirit { namespace karma { namespace detail
{
    ///////////////////////////////////////////////////////////////////////////
    // This function handles the case where the attribute (Attr) given
    // to the sequence is an STL container. This is a wrapper around F.
    // The function F does the actual generating.
    template <typename F, typename Attr, typename Iterator, typename Sequence>
    struct pass_container
    {
        typedef typename F::context_type context_type;

        pass_container(F const& f, Iterator begin, Iterator end)
          : f(f), iter(begin), end(end)
        {}

        bool is_at_end() const
        {
            return traits::compare(iter, end);
        }

        void next()
        {
            traits::next(iter);
        }

        // this is for the case when the current element expects an attribute
        // which is taken from the next entry in the container
        template <typename Component>
        bool dispatch_container(Component const& component, mpl::false_) const
        {
            // get the next value to generate from container
            if (!is_at_end() && !f(component, traits::deref(iter)))
            {
                // needs to return false as long as everything is ok
                traits::next(iter);
                return false;
            }

            // either no elements available any more or generation failed
            return true;
        }

        // this is for the case when the current element is able to handle an
        // attribute which is a container itself, this element will push its
        // data directly into the attribute container
        template <typename Component>
        bool dispatch_container(Component const& component, mpl::true_) const
        {
            return f(component, make_iterator_range(iter, end));
        }

        ///////////////////////////////////////////////////////////////////////
        // this is for the case when the current element doesn't expect an
        // attribute
        template <typename Component>
        bool dispatch_attribute(Component const& component, mpl::false_) const
        {
            return f(component, unused);
        }

        // the current element expects an attribute
        template <typename Component>
        bool dispatch_attribute(Component const& component, mpl::true_) const
        {
            typedef typename traits::container_value<Attr>::type value_type;
            typedef typename
                traits::attribute_of<Component, context_type>::type
            lhs_attribute;

            // this predicate detects, whether the value type of the container
            // attribute is a substitute for the attribute of the current
            // element
            typedef mpl::and_<
                traits::handles_container<Component, Attr, context_type>
              , traits::pass_through_container<
                    Attr, value_type, lhs_attribute, Sequence, karma::domain>
            > predicate;

            return dispatch_container(component, predicate());
        }

        // Dispatches to dispatch_main depending on the attribute type
        // of the Component
        template <typename Component>
        bool operator()(Component const& component) const
        {
            // we need to dispatch depending on the type of the attribute
            // of the current element (component). If this is has no attribute
            // we shouldn't use an element of the container but unused_type
            // instead
            typedef traits::not_is_unused<
                typename traits::attribute_of<Component, context_type>::type
            > predicate;

            return dispatch_attribute(component, predicate());
        }

        F f;
        mutable Iterator iter;
        mutable Iterator end;

    private:
        // silence MSVC warning C4512: assignment operator could not be generated
        pass_container& operator= (pass_container const&);
    };
}}}}

#endif


text:
/**
 * Created by YuebinYang on 9/18/17.
 */
import java.util.*;
public class _131PalindromePartitioning {

    public List<List<String>> partition(String s) {
        List<List<String>> result = new ArrayList<>();
        if (s == null || s.length() == 0) return result;
        List<String> path = new LinkedList<>();

        DFS(s, result, path, 0);
        return result;
    }

    public void DFS(String s, List<List<String>> result, List<String> path, int startIdx) {
        if (startIdx == s.length()) {
            result.add(new LinkedList<>(path));
            return;
        }

        for (int i = startIdx + 1; i <= s.length(); i++) {
            String temp = s.substring(startIdx, i);
            if (validPartition(temp)) {
                path.add(temp);
                DFS(s, result, path, i);
                path.remove(path.size() - 1);
            }
        }
    }

    public boolean validPartition(String str) {
        int start = 0;
        int end = str.length() - 1;
        while (start < end) {
            if (str.charAt(start) != str.charAt(end)) return false;
            start++;
            end--;
        }
        return true;
    }
}


text:
import icons from './icons'

const mimeTypes = {
    'image/gif': icons.image,
    'image/jpeg': icons.image,
    'image/png': icons.image,

    'application/pdf': icons.pdf,

    'application/msword': icons.word,
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': icons.word,

    'application/mspowerpoint': icons.powerpoint,
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': icons.powerpoint,

    'application/msexcel': icons.excel,
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': icons.excel,

    'text/csv': icons.csv,

    'audio/aac': icons.audio,
    'audio/wav': icons.audio,
    'audio/mpeg': icons.audio,
    'audio/mp4': icons.audio,
    'audio/ogg': icons.audio,

    'video/x-msvideo': icons.video,
    'video/mpeg': icons.video,
    'video/mp4': icons.video,
    'video/ogg': icons.video,
    'video/quicktime': icons.video,
    'video/webm': icons.video,

    'application/gzip': icons.archive,
    'application/zip': icons.archive,

    'text/css': icons.code,
    'text/html': icons.code,
    'text/javascript': icons.code,
    'application/javascript': icons.code,

    'text/plain': icons.text,
    'text/richtext': icons.text,
    'text/rtf': icons.text
}

export default mimeTypes


text:
START_ATF_NAMESPACE
    typedef HACCEL__ *HACCEL;
END_ATF_NAMESPACE


text:
import os
from nose.tools import (assert_equal, assert_is, assert_is_not_none)
from ... import ROOT
from qipipe.staging.image_collection import Collection
from qipipe.staging import image_collection
from ...helpers.logging import logger

class TestCollection(object):
    """Image collection unit tests."""

    def test_name(self):
        a = Collection('test', subject=None, session=None,
                       scan=None, volume=None)
        assert_equal(a.name, 'Test', "Collection name is not capitalized: %s" %
                                     a.name)

    def test_with_name(self):
        collections = {name: Collection(name, subject=None, session=None,
                                        scan=None, volume=None)
                       for name in ['Aa', 'bB']}
        for name, expected in collections.iteritems():
            actual = image_collection.with_name(name)
            assert_is_not_none(actual, "Collection search on exact name %s"
                                       " unsuccessful" % name)
            assert_is(actual, expected, "Collection search on exact name"
                                        " %s incorrect" % name)
            lc_name = name.lower()
            actual = image_collection.with_name(lc_name)
            assert_is_not_none(actual, "Collection search on lower-case name %s"
                                       " unsuccessful" % lc_name)
            assert_is(actual, expected, "Collection search on lower-case name"
                                        " %s incorrect" % lc_name)

if __name__ == "__main__":
    import nose
    nose.main(defaultTest=__name__)


text:
<?php

declare(strict_types=1);

namespace ArrayType;

use InvalidArgumentException;
use WsdlToPhp\PackageBase\AbstractStructArrayBase;

/**
 * This class stands for NonEmptyArrayOfReminderItemActionType ArrayType
 * @package Ews
 * @subpackage Arrays
 * @author WsdlToPhp <contact@wsdltophp.com>
 */
class EwsNonEmptyArrayOfReminderItemActionType extends AbstractStructArrayBase
{
    /**
     * The ReminderItemAction
     * Meta information extracted from the WSDL
     * - maxOccurs: unbounded
     * - minOccurs: 1
     * @var \StructType\EwsReminderItemActionType[]
     */
    protected array $ReminderItemAction = [];
    /**
     * Constructor method for NonEmptyArrayOfReminderItemActionType
     * @uses EwsNonEmptyArrayOfReminderItemActionType::setReminderItemAction()
     * @param \StructType\EwsReminderItemActionType[] $reminderItemAction
     */
    public function __construct(array $reminderItemAction)
    {
        $this
            ->setReminderItemAction($reminderItemAction);
    }
    /**
     * Get ReminderItemAction value
     * @return \StructType\EwsReminderItemActionType[]
     */
    public function getReminderItemAction(): array
    {
        return $this->ReminderItemAction;
    }
    /**
     * This method is responsible for validating the values passed to the setReminderItemAction method
     * This method is willingly generated in order to preserve the one-line inline validation within the setReminderItemAction method
     * @param array $values
     * @return string A non-empty message if the values does not match the validation rules
     */
    public static function validateReminderItemActionForArrayConstraintsFromSetReminderItemAction(array $values = []): string
    {
        $message = '';
        $invalidValues = [];
        foreach ($values as $nonEmptyArrayOfReminderItemActionTypeReminderItemActionItem) {
            // validation for constraint: itemType
            if (!$nonEmptyArrayOfReminderItemActionTypeReminderItemActionItem instanceof \StructType\EwsReminderItemActionType) {
                $invalidValues[] = is_object($nonEmptyArrayOfReminderItemActionTypeReminderItemActionItem) ? get_class($nonEmptyArrayOfReminderItemActionTypeReminderItemActionItem) : sprintf('%s(%s)', gettype($nonEmptyArrayOfReminderItemActionTypeReminderItemActionItem), var_export($nonEmptyArrayOfReminderItemActionTypeReminderItemActionItem, true));
            }
        }
        if (!empty($invalidValues)) {
            $message = sprintf('The ReminderItemAction property can only contain items of type \StructType\EwsReminderItemActionType, %s given', is_object($invalidValues) ? get_class($invalidValues) : (is_array($invalidValues) ? implode(', ', $invalidValues) : gettype($invalidValues)));
        }
        unset($invalidValues);

        return $message;
    }
    /**
     * Set ReminderItemAction value
     * @throws InvalidArgumentException
     * @param \StructType\EwsReminderItemActionType[] $reminderItemAction
     * @return \ArrayType\EwsNonEmptyArrayOfReminderItemActionType
     */
    public function setReminderItemAction(array $reminderItemAction): self
    {
        // validation for constraint: array
        if ('' !== ($reminderItemActionArrayErrorMessage = self::validateReminderItemActionForArrayConstraintsFromSetReminderItemAction($reminderItemAction))) {
            throw new InvalidArgumentException($reminderItemActionArrayErrorMessage, __LINE__);
        }
        $this->ReminderItemAction = $reminderItemAction;

        return $this;
    }
    /**
     * Returns the current element
     * @see AbstractStructArrayBase::current()
     * @return \StructType\EwsReminderItemActionType|null
     */
    public function current(): ?\StructType\EwsReminderItemActionType
    {
        return parent::current();
    }
    /**
     * Returns the indexed element
     * @see AbstractStructArrayBase::item()
     * @param int $index
     * @return \StructType\EwsReminderItemActionType|null
     */
    public function item($index): ?\StructType\EwsReminderItemActionType
    {
        return parent::item($index);
    }
    /**
     * Returns the first element
     * @see AbstractStructArrayBase::first()
     * @return \StructType\EwsReminderItemActionType|null
     */
    public function first(): ?\StructType\EwsReminderItemActionType
    {
        return parent::first();
    }
    /**
     * Returns the last element
     * @see AbstractStructArrayBase::last()
     * @return \StructType\EwsReminderItemActionType|null
     */
    public function last(): ?\StructType\EwsReminderItemActionType
    {
        return parent::last();
    }
    /**
     * Returns the element at the offset
     * @see AbstractStructArrayBase::offsetGet()
     * @param int $offset
     * @return \StructType\EwsReminderItemActionType|null
     */
    public function offsetGet($offset): ?\StructType\EwsReminderItemActionType
    {
        return parent::offsetGet($offset);
    }
    /**
     * Add element to array
     * @see AbstractStructArrayBase::add()
     * @throws InvalidArgumentException
     * @param \StructType\EwsReminderItemActionType $item
     * @return \ArrayType\EwsNonEmptyArrayOfReminderItemActionType
     */
    public function add($item): self
    {
        // validation for constraint: itemType
        if (!$item instanceof \StructType\EwsReminderItemActionType) {
            throw new InvalidArgumentException(sprintf('The ReminderItemAction property can only contain items of type \StructType\EwsReminderItemActionType, %s given', is_object($item) ? get_class($item) : (is_array($item) ? implode(', ', $item) : gettype($item))), __LINE__);
        }
        return parent::add($item);
    }
    /**
     * Returns the attribute name
     * @see AbstractStructArrayBase::getAttributeName()
     * @return string ReminderItemAction
     */
    public function getAttributeName(): string
    {
        return 'ReminderItemAction';
    }
}


text:
ifneq ($(SWIG),YES)

SHELL = /bin/sh

#### Start of system configuration section. ####

srcdir = .
topdir = $(shell echo /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/universal-darwin*)
hdrdir = $(topdir)
VPATH = $(srcdir):$(topdir):$(hdrdir)
exec_prefix = $(prefix)
prefix = $(DESTDIR)/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr
sharedstatedir = $(prefix)/com
mandir = $(DESTDIR)/usr/share/man
psdir = $(docdir)
oldincludedir = $(DESTDIR)/usr/include
localedir = $(datarootdir)/locale
bindir = $(exec_prefix)/bin
libexecdir = $(exec_prefix)/libexec
sitedir = $(DESTDIR)/Library/Ruby/Site
htmldir = $(docdir)
vendorarchdir = $(vendorlibdir)/$(sitearch)
includedir = $(prefix)/include
infodir = $(DESTDIR)/usr/share/info
vendorlibdir = $(vendordir)/$(ruby_version)
sysconfdir = $(prefix)/etc
libdir = $(exec_prefix)/lib
sbindir = $(exec_prefix)/sbin
rubylibdir = $(libdir)/ruby/$(ruby_version)
docdir = $(datarootdir)/doc/$(PACKAGE)
dvidir = $(docdir)
vendordir = $(libdir)/ruby/vendor_ruby
datarootdir = $(prefix)/share
pdfdir = $(docdir)
archdir = $(rubylibdir)/$(arch)
sitearchdir = $(sitelibdir)/$(sitearch)
datadir = $(datarootdir)
localstatedir = $(prefix)/var
sitelibdir = $(sitedir)/$(ruby_version)

CC = c++
CXX = $(CC)
LIBRUBY = $(LIBRUBY_SO)
LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a
LIBRUBYARG_SHARED = -l$(RUBY_SO_NAME)
LIBRUBYARG_STATIC = -l$(RUBY_SO_NAME)

RUBY_EXTCONF_H =
LLVM-CONFIG = llvm-config
CFLAGS   =  $(RC_CFLAGS) $(shell $(LLVM-CONFIG) --cxxflags | sed -e 's/ *-arch [^ ]*//g' -e 's/ *-D[^ ]*//g')

INCFLAGS = -I. -I$(topdir) -I$(hdrdir) -I$(srcdir)
DEFS     =
CPPFLAGS =  $(shell $(LLVM-CONFIG) --cppflags | sed 's/ *-arch [^ ]*//g')

CXXFLAGS = $(CFLAGS)
ldflags  = $(RC_CFLAGS) $(shell $(LLVM-CONFIG) --ldflags | sed 's/ *-arch [^ ]*//g')

dldflags =
archflag =
DLDFLAGS = $(ldflags) $(dldflags) $(archflag)
LDSHARED = $(CC) $(RC_CFLAGS) -pipe -bundle -undefined dynamic_lookup
AR = ar
EXEEXT =

RUBY_INSTALL_NAME = ruby
RUBY_SO_NAME = ruby
arch = $(shell $(RUBY) -e 'puts RUBY_PLATFORM')
sitearch = $(arch)
ruby_version = 1.8
ruby = /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
RUBY = $(ruby)
RM = rm -f
MAKEDIRS = mkdir -p
INSTALL = /usr/bin/install -c
INSTALL_PROG = $(INSTALL) -m 0755
INSTALL_DATA = $(INSTALL) -m 644
COPY = cp

#### End of system configuration section. ####

preload =

libpath = . $(libdir)
LIBPATH =  -L. -L$(libdir)
DEFFILE =

CLEANFILES = mkmf.log bridgesupportparser_wrap.cpp
DISTCLEANFILES =

extout =
extout_prefix =
target_prefix =
LOCAL_LIBS =
LIBS = $(LIBRUBYARG_SHARED) -lclangCodeGen -lclangAnalysis -lclangRewrite -lclangSema -lclangFrontend -lclangDriver -lclangAST -lclangParse -lclangLex -lclangBasic -lLLVMCore -lLLVMSupport -lLLVMSystem -lLLVMBitWriter -lLLVMBitReader -lLLVMCodeGen -lLLVMAnalysis -lLLVMTarget -lLLVMMC
SRCS = bridgesupportparser.cpp bridgesupportparser_wrap.cpp
OBJS = bridgesupportparser.o bridgesupportparser_wrap.o
TARGET = bridgesupportparser
DLLIB = $(TARGET).bundle
EXTSTATIC =
STATIC_LIB =

BINDIR        = $(bindir)
RUBYCOMMONDIR = $(sitedir)$(target_prefix)
RUBYLIBDIR    = $(sitelibdir)$(target_prefix)
RUBYARCHDIR   = $(sitearchdir)$(target_prefix)

TARGET_SO     = $(DLLIB)
CLEANLIBS     = $(TARGET).bundle $(TARGET).il? $(TARGET).tds $(TARGET).map
CLEANOBJS     = *.o *.a *.s[ol] *.pdb *.exp *.bak

all:		$(DLLIB)
static:		$(STATIC_LIB)

clean:
		@-$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES)

distclean:	clean
		@-$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log
		@-$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES)

realclean:	distclean
install: install-so install-rb

install-so: $(RUBYARCHDIR)
install-so: $(RUBYARCHDIR)/$(DLLIB)
$(RUBYARCHDIR)/$(DLLIB): $(DLLIB)
	$(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR)
install-rb: pre-install-rb install-rb-default
install-rb-default: pre-install-rb-default
pre-install-rb: Makefile
pre-install-rb-default: Makefile
$(RUBYARCHDIR):
	$(MAKEDIRS) $@

site-install: site-install-so site-install-rb
site-install-so: install-so
site-install-rb: install-rb

.SUFFIXES: .c .m .cc .cxx .cpp .C .o

.cc.o:
	$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) -c $<

.cxx.o:
	$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) -c $<

.cpp.o:
	$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) -c $<

.C.o:
	$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) -c $<

.c.o:
	$(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) -c $<

$(DLLIB): $(OBJS) Makefile
	@-$(RM) $@
	$(LDSHARED) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS)
ifneq ($(findstring -g,$(CXXFLAGS)),)
	dsymutil $@
endif

$(OBJS): ruby.h defines.h

BSP_HEADERS = classes.h bridgesupportparser.h __xattr__.h
$(OBJS): $(BSP_HEADERS)

bridgesupportparser_wrap.o: bridgesupportparser_wrap.cpp
	$(CXX) $(INCFLAGS) -DSWIG $(CPPFLAGS) $(CXXFLAGS) -c $<

else # SWIG = YES

# Because of different versions of swig on different OS releases, it isn't
# safe to create bridgesupportparser_wrap.cpp by running swig at build time
# (bridgesupportparser.i is dependent on certain swig internals that
# may change with different versions of swig).  So we use a frozen version
# of bridgesupportparser_wrap.cpp, which can be regenerated by running
# "make SWIG=YES".  Anytime classes.h, bridgesupportparser.h, __xattr__.h
# or bridgesupportparser.i change, bridgesupportparser_wrap.cpp will need
# to be regenerated manually.

bridgesupportparser_wrap.cpp: $(BSP_HEADERS)
bridgesupportparser_wrap.cpp: bridgesupportparser.i
	swig -c++ -ruby -o $@ $<

endif # SWIG = YES


text:
package irc_test

import (
	"testing"

	. "macleod.io/bounce/irc"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Parses messages", func() {
	Specify("Command", func() {
		msg := ParseMessage("PRIVMSG")
		Expect(msg.Command).To(Equal("PRIVMSG"))
	})
	Specify("Tag", func() {
		msg := ParseMessage("@key=value PING")
		Expect(msg.Command).To(Equal("PING"))
		Expect(msg.Tags).To(HaveKeyWithValue("key", "value"))
		Expect(msg.Tags).To(HaveLen(1))
	})
	Specify("Multiple tags", func() {
		msg := ParseMessage("@first;second=2;third PING")
		Expect(msg.Command).To(Equal("PING"))
		Expect(msg.Tags).To(HaveLen(3))
	})
	Specify("Prefix", func() {
		msg := ParseMessage(":irc.example.org PING")
		Expect(msg.Command).To(Equal("PING"))
		Expect(msg.Prefix).To(Equal("irc.example.org"))
	})
	Specify("Param", func() {
		msg := ParseMessage("PING one")
		Expect(msg.Command).To(Equal("PING"))
		Expect(msg.Params).To(ConsistOf("one"))
	})
	Specify("Param with trailing whitespace", func() {
		msg := ParseMessage("PING one ")
		Expect(msg.Command).To(Equal("PING"))
		Expect(msg.Params).To(ConsistOf("one"))
	})
	Specify("Multiple params", func() {
		msg := ParseMessage("PRIVMSG #channel :a b c ")
		Expect(msg.Command).To(Equal("PRIVMSG"))
		Expect(msg.Params).To(BeEquivalentTo([]string{
			"#channel", "a b c ",
		}))
	})
	Specify("All of the above", func() {
		raw := `@time=half\sfive;foo :example.org CAP * LS :server-time sasl`
		msg := ParseMessage(raw)
		Expect(msg.Raw).To(Equal(raw))
		Expect(msg.Tags).To(BeEquivalentTo(map[string]string{
			"time": "half five",
			"foo":  "",
		}))
		Expect(msg.Prefix).To(Equal("example.org"))
		Expect(msg.Command).To(Equal("CAP"))
		Expect(msg.Params).To(BeEquivalentTo([]string{
			"*", "LS", "server-time sasl",
		}))
	})
})

var _ = Describe("Composes messages", func() {
	Specify("Complex message", func() {
		msg := ParseMessage("@key=value :example.org PRIVMSG #channel :hello world ")
		Expect(msg.Buffer().String()).To(Equal("@key=value :example.org PRIVMSG #channel :hello world \r\n"))
	})
	Specify("Multiple tags", func() {
		msg := ParseMessage("@one=1;two PING")
		Expect(msg.Buffer().String()).To(SatisfyAny(
			Equal("@one=1;two PING\r\n"),
			Equal("@two;one=1 PING\r\n"),
		))
	})
})

func BenchmarkParsing(b *testing.B) {
	for i := 0; i < b.N; i++ {
		ParseMessage("@time=now :example.org PRIVMSG #channel :message message message")
	}
	b.StopTimer()
}

func BenchmarkBufferComposition(b *testing.B) {
	msg := &Message{
		Tags: map[string]string{
			"key": "value",
		},
		Prefix:  "example.org",
		Command: "PRIVMSG",
		Params: []string{
			"#channel",
			"hello world",
		},
	}
	for i := 0; i < b.N; i++ {
		msg.Buffer()
	}
	b.StopTimer()
}


text:
import {reducer} from './tellers.reducer';
import {ResourceState} from '../../../common/store/resource.reducer';
import {ExecuteCommandPayload, ExecuteCommandSuccessAction} from './teller.actions';
import {Status} from '../../../services/teller/domain/teller.model';

describe('Tellers Reducer', () => {

  describe('EXECUTE_COMMAND_SUCCESS', () => {

    function createState(state?: Status, assignedEmployee?: string): ResourceState {
      return {
        ids: ['testTeller'],
        entities: {
          'testTeller': {
            code: 'testTeller',
            state,
            assignedEmployee
          }
        },
        selectedId: null,
        loadedAt: {}
      };
    }

    it('should add assigned employee on open', () => {
      const payload: ExecuteCommandPayload = {
        officeId: 'officeId',
        tellerCode: 'testTeller',
        command: {
          action: 'OPEN',
          assignedEmployeeIdentifier: 'test'
        },
        activatedRoute: null
      };

      const initialState: ResourceState = createState();

      const expectedResult: ResourceState = createState('OPEN', payload.command.assignedEmployeeIdentifier);

      const result = reducer(initialState, new ExecuteCommandSuccessAction(payload));

      expect(result).toEqual(expectedResult);
    });

    it('should remove assigned employee on close', () => {
      const payload: ExecuteCommandPayload = {
        officeId: 'officeId',
        tellerCode: 'testTeller',
        command: {
          action: 'CLOSE'
        },
        activatedRoute: null
      };

      const initialState: ResourceState = createState();

      const expectedResult: ResourceState = createState('CLOSED', null);

      const result = reducer(initialState, new ExecuteCommandSuccessAction(payload));

      expect(result).toEqual(expectedResult);
    });
  });

});


text:
{
  "title": "Code Combat (Woodland Cleaver)",
  "duration": "3:10"
}
---

Use a new attack move whenever it's ready.  You use conditionals to check for it.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
    internal static class NavigateToSymbolFinder
    {
        private static readonly char[] s_dotArray = new char[] { '.' };

        internal static async Task<IEnumerable<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>> FindNavigableDeclaredSymbolInfos(Project project, string pattern, CancellationToken cancellationToken)
        {
            var patternMatcher = new PatternMatcher(pattern);

            var result = new List<ValueTuple<DeclaredSymbolInfo, Document, IEnumerable<PatternMatch>>>();
            foreach (var document in project.Documents)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var declaredSymbolInfos = await document.GetDeclaredSymbolInfosAsync(cancellationToken).ConfigureAwait(false);
                foreach (var declaredSymbolInfo in declaredSymbolInfos)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var patternMatches = patternMatcher.GetMatches(
                        GetSearchName(declaredSymbolInfo),
                        declaredSymbolInfo.FullyQualifiedContainerName);

                    if (patternMatches != null)
                    {
                        result.Add(ValueTuple.Create(declaredSymbolInfo, document, patternMatches));
                    }
                }
            }

            return result;
        }

        private static string GetSearchName(DeclaredSymbolInfo declaredSymbolInfo)
        {
            if (declaredSymbolInfo.Kind == DeclaredSymbolInfoKind.Indexer && declaredSymbolInfo.Name == WellKnownMemberNames.Indexer)
            {
                return "this";
            }
            else
            {
                return declaredSymbolInfo.Name;
            }
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.orion_platform</groupId>
        <artifactId>orion_platform</artifactId>
        <version>1.0.0</version>
    </parent>

    <groupId>com.orion_platform</groupId>
    <artifactId>orion_notifications</artifactId>
    <version>1.0.0</version>
    <name>Orion Notifications</name>

    <dependencies>
        <dependency>
            <groupId>com.orion_platform</groupId>
            <artifactId>orion_data_source</artifactId>
            <version>1.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.orion_platform</groupId>
            <artifactId>orion_data_model</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
</project>


text:
<?php

 /**
  *
  */

 	require_once(__CA_MODELS_DIR__."/ca_editor_uis.php");
 	require_once(__CA_MODELS_DIR__."/ca_attribute_values.php");
 	require_once(__CA_MODELS_DIR__."/ca_metadata_elements.php");
 	require_once(__CA_MODELS_DIR__."/ca_bundle_mappings.php");
 	require_once(__CA_MODELS_DIR__."/ca_bundle_displays.php");
 	require_once(__CA_LIB_DIR__."/core/Datamodel.php");
 	require_once(__CA_LIB_DIR__."/ca/ApplicationPluginManager.php");
 	require_once(__CA_LIB_DIR__."/ca/ResultContext.php");
	require_once(__CA_LIB_DIR__."/core/Logging/Eventlog.php");

 	class BaseEditorController extends ActionController {
 		# -------------------------------------------------------
 		protected $opo_datamodel;
 		protected $opo_app_plugin_manager;
 		protected $opo_result_context;

 		protected $opo_plugin_config;
 		protected $ops_theme;
 		protected $ops_table_name = null;		// name of "subject" table (what we're editing)
 		protected $opo_instance = null;

 		protected $ops_ui_code = null;
 		protected $opa_ui_info = null;
 		# -------------------------------------------------------
 		#
 		# -------------------------------------------------------
 		public function __construct(&$po_request, &$po_response, $pa_view_paths=null) {
 			parent::__construct($po_request, $po_response, $pa_view_paths);

 			$this->opo_datamodel = Datamodel::load();
 			$this->opo_app_plugin_manager = new ApplicationPluginManager();
 			$this->opo_result_context = new ResultContext($po_request, $this->ops_table_name, ResultContext::getLastFind($po_request, $this->ops_table_name));
 		}
 		# -------------------------------------------------------
 		/**
 		 * Generates a form for editing new or existing records. The form is rendered into the current view, inherited from ActionController
 		 *
 		 * @param array $pa_values An optional array of values to preset in the format, overriding any existing values in the model of the record being editing.
 		 * @param array $pa_options Array of options passed through to _initView
 		 *
 		 */
 		public function Edit($pa_values=null, $pa_options=null) {
 			list($vn_subject_id, $t_subject, $t_ui) = $this->_initView($pa_options);
 			$vs_mode = $this->request->getParameter('mode', pString);

 			//
 			// Don't open existing records
 			//
 			if ($t_subject->hasField('deleted') && $t_subject->get('deleted')) {
 				$this->response->setRedirect($this->request->config->get('error_display_url').'/n/2550?r='.urlencode($this->request->getFullUrlPath()));
 				return;
 			}

 			if ((!$t_subject->getPrimaryKey()) && ($vn_subject_id)) {
 				$this->response->setRedirect($this->request->config->get('error_display_url').'/n/2500?r='.urlencode($this->request->getFullUrlPath()));
 				return;
 			}

 			if(is_array($pa_values)) {
 				foreach($pa_values as $vs_key => $vs_val) {
 					$t_subject->set($vs_key, $vs_val);
 				}
 			}

 			// set "context" id from those editors that need to restrict idno lookups to within the context of another field value (eg. idno's for ca_list_items are only unique within a given list_id)
 			if ($vs_idno_context_field = $t_subject->getProperty('ID_NUMBERING_CONTEXT_FIELD')) {
 				if ($vn_subject_id > 0) {
 					$this->view->setVar('_context_id', $t_subject->get($vs_idno_context_field));
 				}
 			}

 			// get default screen

 			if (!($vn_type_id = $t_subject->getTypeID())) {
 				$vn_type_id = $this->request->getParameter($t_subject->getTypeFieldName(), pInteger);
 			}

 			if (!$this->request->getActionExtra()) {
 				$va_nav = $t_ui->getScreensAsNavConfigFragment($this->request, $vn_type_id, $this->request->getModulePath(), $this->request->getController(), $this->request->getAction(),
					array(),
					array()
				);
 				$this->request->setActionExtra($va_nav['defaultScreen']);
 			}
			$this->view->setVar('t_ui', $t_ui);
			if (!$t_ui->getPrimaryKey()) {
				$vs_notification_message = _t('There is no configuration available for this editor. Check your system configuration and ensure there is at least one valid configuration for this type of editor.');
			}
			if ($vn_subject_id) { $this->request->session->setVar($this->ops_table_name.'_browse_last_id', $vn_subject_id); } 	// set last edited

			# trigger "EditItem" hook
			$this->opo_app_plugin_manager->hookEditItem(array('id' => $vn_subject_id, 'table_num' => $t_subject->tableNum(), 'table_name' => $t_subject->tableName(), 'instance' => $t_subject));
			$this->view->setVar("notification_message", $vs_notification_message);
			$this->render('screen_html.php');
 		}
 		# -------------------------------------------------------
 		/**
 		 * Saves the content of a form editing new or existing records. It returns the same form + status messages rendered into the current view, inherited from ActionController
 		 *
 		 * @param array $pa_options Array of options passed through to _initView and saveBundlesForScreen()
 		 */
 		public function Save($pa_options=null) {
 			list($vn_subject_id, $t_subject, $t_ui) = $this->_initView($pa_options);
 			if (!is_array($pa_options)) { $pa_options = array(); }
 			$vs_message = '';

 			$vs_auth_table_name = $this->ops_table_name;
 			if (in_array($this->ops_table_name, array('ca_object_representations', 'ca_representation_annotations'))) { $vs_auth_table_name = 'ca_objects'; }

 			if(!sizeof($_REQUEST)) {
 				$vs_message = _t("Cannot save using empty request. Are you using a bookmark?");
 				$this->view->setVar("message", $vs_message);
 				$this->render('screen_html.php');
 				return;
 			}

 			// set "context" id from those editors that need to restrict idno lookups to within the context of another field value (eg. idno's for ca_list_items are only unique within a given list_id)
 			$vn_context_id = null;
 			if ($vs_idno_context_field = $t_subject->getProperty('ID_NUMBERING_CONTEXT_FIELD')) {
 				if ($vn_subject_id > 0) {
 					$this->view->setVar('_context_id', $vn_context_id = $t_subject->get($vs_idno_context_field));
 				}

 				if ($vn_context_id) { $t_subject->set($vs_idno_context_field, $vn_context_id); }
 			}

 			if (!($vs_type_name = $t_subject->getTypeName())) {
 				$vs_type_name = $t_subject->getProperty('NAME_SINGULAR');
 			}

 			if ($vn_subject_id && !$t_subject->getPrimaryKey()) {
 				$vs_notification_message = _t("%1 does not exist", $vs_type_name);
 				$this->view->setVar("notification_message", $vs_notification_message);
 				return;
 			}

 			# trigger "BeforeSaveItem" hook
			$this->opo_app_plugin_manager->hookBeforeSaveItem(array('id' => $vn_subject_id, 'table_num' => $t_subject->tableNum(), 'table_name' => $t_subject->tableName(), 'instance' => $t_subject, 'is_insert' => $vb_is_insert));

 			$vb_is_insert = !$t_subject->getPrimaryKey();

 			// Set access and status
 			if(strlen($vn_access = CatalogingPlugin::getFormSetting('access'))) {
 				$t_subject->set("access", $this->request->getParameter("access", pInteger));
 			}
 			if(strlen($vn_status = CatalogingPlugin::getFormSetting('status'))) {
 				$t_subject->set("status", $this->request->getParameter("status", pInteger));
 			}
 			$vb_save_rc = $t_subject->saveBundlesForScreen($this->request->getActionExtra(), $this->request, array_merge($pa_options, array('ui_instance' => $t_ui)));
			$this->view->setVar('t_ui', $t_ui);

			if(!$vn_subject_id) {
				$vn_subject_id = $t_subject->getPrimaryKey();
				if (!$vb_save_rc) {
					$vs_message = "";
				} else {
					if (isset($pa_options['setNotifictionOnSuccess']) && $pa_options['setNotifictionOnSuccess']) {
						$vs_message = _t("Added %1", $vs_type_name);
					}
					$this->request->setParameter($t_subject->primaryKey(), $vn_subject_id, 'GET');
					$this->view->setVar($t_subject->primaryKey(), $vn_subject_id);
					$this->view->setVar('subject_id', $vn_subject_id);
					$this->request->session->setVar($this->ops_table_name.'_browse_last_id', $vn_subject_id);	// set last edited
				}

			} else {
 				$vs_message = _t("Saved changes to %1", $vs_type_name);
 			}

 			$va_errors = $this->request->getActionErrors();							// all errors from all sources
 			$va_general_errors = $this->request->getActionErrors('general');		// just "general" errors - ones that are not attached to a specific part of the form
 			if (is_array($va_general_errors) && sizeof($va_general_errors) > 0) {
 				foreach($va_general_errors as $o_e) {
 					$vs_notification_message = $o_e->getErrorDescription();
 					$this->view->setVar("notification_message", $vs_notification_message);
 				}
			}

 			if(sizeof($va_errors) + sizeof($va_general_errors) > 0) {
 				$va_error_list = array();
 				$vb_no_save_error = false;
 				foreach($va_errors as $o_e) {
 					$va_error_list[$o_e->getErrorDescription()] = "
".$o_e->getErrorDescription()."
\n";

 					switch($o_e->getErrorNumber()) {
 						case 1100:	// duplicate/invalid idno
 							if (!$vn_subject_id) {		// can't save new record if idno is not valid (when updating everything but idno is saved if it is invalid)
 								$vb_no_save_error = true;
 							}
 							break;
 					}
 				}
 				if ($vb_no_save_error) {
 					$vs_notification_message = _t("There are errors preventing ALL information from being saved. Correct the problems and click \"save\" again.\n
");
 					$this->view->setVar("notification_message", $vs_notification_message);
 				} else {
 					if($vs_message){
 						$vs_notification_message = $vs_message."
";
 					}
 					$vs_notification_message .= _t("There are errors preventing information in specific fields from being saved as noted below.\n").join("\n", $va_error_list);
 				}
 				$this->view->setVar("notification_message", $vs_notification_message);
 				$this->render('screen_html.php');
 			} else {
				if ($vs_message) { $vs_notification_message = $vs_message."
"; }
 				$this->opo_result_context->invalidateCache();
  				$this->opo_result_context->saveContext();

 				# trigger "SaveItem" hook
  				$this->opo_app_plugin_manager->hookSaveItem(array('id' => $vn_subject_id, 'table_num' => $t_subject->tableNum(), 'table_name' => $t_subject->tableName(), 'instance' => $t_subject, 'is_insert' => $vb_is_insert));

 				if ((bool)$this->opa_ui_info['set_post_submission_notification']) {
 					$vs_notification_message = $vs_message;
 				}
 				$this->view->setVar("notification_message", $vs_notification_message);
 				$this->render('screen_html.php');
 			}
 		}
 		# -------------------------------------------------------
 		/**
 		 * Generates display summary of record data based upon a bundle display for screen
 		 *
 		 * @param array $pa_options Array of options passed through to _initView
 		 */
 		protected function _initView($pa_options=null) {
 			// load required javascript
 			JavascriptLoadManager::register('bundleableEditor');
 			JavascriptLoadManager::register('imageScroller');
 			$t_subject = $this->opo_datamodel->getInstanceByTableName($this->ops_table_name);
 			$vn_subject_id = $this->request->getParameter($t_subject->primaryKey(), pInteger);
 			if (!$vn_subject_id || !$t_subject->load($vn_subject_id)) {
 				// empty (ie. new) rows don't have a type_id set, which means we'll have no idea which attributes to display
 				// so we get the type_id off of the request
 				if (!$vn_type_id = $this->request->getParameter($t_subject->getTypeFieldName(), pInteger)) {
 					$vn_type_id = null;
 				}

 				// then set the empty row's type_id
 				$t_subject->set($t_subject->getTypeFieldName(), $vn_type_id);

 				// then reload the definitions (which includes bundle specs)
 				$t_subject->reloadLabelDefinitions();
 			}

 			$t_ui = new ca_editor_uis();
 			if (isset($pa_options['ui']) && $pa_options['ui']) {
 				if (is_numeric($pa_options['ui'])) {
 					$t_ui->load((int)$pa_options['ui']);
 				}
 				if (!$t_ui->getPrimaryKey()) {
 					$t_ui->load(array('editor_code' => $pa_options['ui']));
 				}
 			}

 			if (!$t_ui->getPrimaryKey()) {
 				$t_ui = ca_editor_uis::loadDefaultUI($this->ops_table_name, $this->request, $t_subject->getTypeID());
 			}

 			$this->view->setVar($t_subject->primaryKey(), $vn_subject_id);
 			$this->view->setVar('subject_id', $vn_subject_id);
 			$this->view->setVar('t_subject', $t_subject);

 			return array($vn_subject_id, $t_subject, $t_ui);
 		}
 		# -------------------------------------------------------
		/**
		 * Returns current result contents
		 *
		 * @return ResultContext ResultContext instance.
		 */
		public function getResultContext() {
			return $this->opo_result_context;
		}
 		# -------------------------------------------------------
 		/**
 		 *
 		 */
 		protected function _getTypeIDForUI($t_subject) {
 			$vn_type_id = null;
 			if (isset($this->opa_ui_info) && is_array($this->opa_ui_info)) {
 				if(isset($this->opa_ui_info['type_id']) && ($vn_type_id = $this->opa_ui_info['type_id'])) {
 					return $vn_type_id;
 				}
 			}
 			$vs_notification_message = _t('Type "%1" configured for the Cataloging form "%2" is not valid', $this->opa_ui_info['type'], $this->ops_ui_code);
 			$this->view->setVar("notification_message", $vs_notification_message);
 			return null;
 		}
		# -------------------------------------------------------
 	}
 ?>