text:
package de.uni.freiburg.iig.telematik.swat.workbench;

import de.uni.freiburg.iig.telematik.swat.workbench.components.SwatComponents;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;

import de.invation.code.toval.graphic.component.DisplayFrame;
import de.invation.code.toval.graphic.dialog.ExceptionDialog;
import de.invation.code.toval.graphic.dialog.FileNameDialog;
import de.invation.code.toval.graphic.dialog.MessageDialog;
import de.invation.code.toval.graphic.dialog.StringDialog;
import de.invation.code.toval.properties.PropertyException;
import de.invation.code.toval.validate.ParameterException;
import de.uni.freiburg.iig.telematik.sepia.graphic.AbstractGraphicalPN;
import de.uni.freiburg.iig.telematik.sepia.graphic.GraphicalCPN;
import de.uni.freiburg.iig.telematik.sepia.graphic.GraphicalIFNet;
import de.uni.freiburg.iig.telematik.sepia.graphic.GraphicalPTNet;
import de.uni.freiburg.iig.telematik.sepia.graphic.GraphicalTimedNet;
import de.uni.freiburg.iig.telematik.sepia.petrinet.ifnet.IFNet;
import de.uni.freiburg.iig.telematik.sepia.petrinet.timedNet.TimedNet;
import de.uni.freiburg.iig.telematik.swat.analysis.modelchecker.lola.LolaPresenter;
import de.uni.freiburg.iig.telematik.swat.analysis.modelchecker.lola.LolaTransformator;
import de.uni.freiburg.iig.telematik.swat.icons.IconFactory;
import de.uni.freiburg.iig.telematik.swat.workbench.SwatState.OperatingMode;
import de.uni.freiburg.iig.telematik.swat.workbench.action.AFSqlLogImportAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.DeleteAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.EditPropertiesAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.ImportAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.LolaAnalyzeAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.PTImportAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.PopUpToolBarAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.RenameAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.SaveActiveComponentAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.SaveAllAction;
import de.uni.freiburg.iig.telematik.swat.workbench.action.ManageWorkingDirectoryAction;
import de.uni.freiburg.iig.telematik.swat.workbench.exception.SwatComponentException;
import de.uni.freiburg.iig.telematik.swat.workbench.listener.SwatStateListener;
import de.uni.freiburg.iig.telematik.swat.workbench.properties.SwatProperties;
import de.uni.freiburg.iig.telematik.wolfgang.editor.component.PNEditorComponent;
import de.uni.freiburg.iig.telematik.wolfgang.menu.WrapLayout;

/**
 * Model for Buttons. Holds buttons like "open", "save", ... With
 * {@link #getPanelButtons()} the buttons are available inside a {@link JPanel}.
 * Each button can be accesed through get(enum)
 *
 * @author richard
 *
 */
public class SwatToolbar extends JToolBar implements ActionListener, SwatStateListener {

    private static final long serialVersionUID = -4279345402764581310L;

    private static final Color TOOLBAR_BG_COLOR = new Color(185, 185, 185);
    private static final Color TOOLBAR_BORDER_COLOR = Color.black;

    private static final String ACTION_COMMAND_EDIT_MODE = "editMode";
    private static final String ACTION_COMMAND_ANALYSIS_MODE = "analysisMode";
    private static final int ICON_SPACING = 5;

    private JRadioButton rdbtnEdit = null;
    private JRadioButton rdbtnAnalysis = null;

    private SwatTabView tabView = null;
    private SwatTreeView treeView = null;

    private List<JComponent> standardItems = new LinkedList<JComponent>();

    public SwatToolbar(SwatTabView tabView, SwatTreeView treeView) {
        this.tabView = tabView;
        this.treeView = treeView;

        setBackground(TOOLBAR_BG_COLOR);
        setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, TOOLBAR_BORDER_COLOR));
        setFloatable(false);
        setRollover(true);

        setLayout(new WrapLayout(3));

        try {
			createButtons();
		} catch (ParameterException | PropertyException | IOException e1) {
			Workbench.errorMessage("Could not load Toolbar-Icons", e1, true);
		}

        addDefaultItems();

        try {
            SwatState.getInstance().addListener(this);
        } catch (ParameterException e) {
            // Cannot happen, since this is never null.
        	Workbench.errorMessage("Could not register SwatToolbar", e, true);
        }

        // try to get ICONSize
        try {
            //ICON_SIZE = SwatProperties.getInstance().getIconSize().getSize();
        } catch (Exception e) {
            // Cannot read property. Ignore and stay with default value (32)
        }

    }

    /**add default items to toolbar**/
    private void addDefaultItems() {
        for (JComponent button : standardItems) {
            add(button);
            button.setFocusable(false);
        }
        addSeparator();
    }

    /**
     * Put default buttons into linkedList {@link #standardItems} for later use
     *
     * @throws IOException
     * @throws PropertyException
     * @throws ParameterException
	 *
     */
    private void createButtons() throws ParameterException, PropertyException, IOException {
        standardItems.add(new JButton(new SaveActiveComponentAction()));
        standardItems.add(new SwatToolbarButton(ToolbarButtonType.SAVE_ALL));
        standardItems.add(new JButton(new DeleteAction()));
        standardItems.add(new JButton(new ManageWorkingDirectoryAction()));
        standardItems.add(getNewNetButton());
		//standardItems.add(new JButton(new ImportAction()));
        //standardItems.add(getImportButon());
        //standardItems.add(new SwatToolbarButton(ToolbarButtonType.AF_TEMPLATE));
        //		standardItems.add(new JButton(new AFtemplateImportAction()));
        //		standardItems.add(new JButton(new LogImportAction()));
        standardItems.add(new JButton(new ImportAction()));
        standardItems.add(new SwatToolbarButton(ToolbarButtonType.RENAME));
        standardItems.add(new SwatToolbarButton(ToolbarButtonType.EDIT_PROPERTY));
		//standardItems.add(getLolaButton());
        //standardItems.add(getAristaFlowButton());
        //standardItems.add(new JButton(new SimulateTimeAction()));
        //standardItems.add(new JButton(new SimulateInstanceAwareAction()));
        //standardItems.add(new SwatToolbarButton(ToolbarButtonType.PRISM));

        ButtonGroup group = new ButtonGroup();
        group.add(getAnalysisRadioButton());
        group.add(getEditRadioButton());
        getEditRadioButton().setSelected(true);
        //removeBorder();

        standardItems.add(getAnalysisRadioButton());
        standardItems.add(getEditRadioButton());
    }

    private void removeBorder() {
        Border emptyBorder = BorderFactory.createEmptyBorder();
        for (JComponent button : standardItems) {
            button.setBorder(emptyBorder);
        }
    }

    private JButton getLolaButton() throws ParameterException, PropertyException, IOException {
        JButton lola = new SwatToolbarButton(ToolbarButtonType.DETECTIVE);
        return lola;
    }

    private JButton getAristaFlowButton() throws ParameterException, PropertyException, IOException {
        JButton aristaFlow = new JButton(new AFSqlLogImportAction());
        return aristaFlow;
    }

    private JRadioButton getAnalysisRadioButton() {
        if (rdbtnAnalysis == null) {
            rdbtnAnalysis = new JRadioButton("Analyse");
            rdbtnAnalysis.setMnemonic(KeyEvent.VK_A);
            rdbtnAnalysis.setActionCommand(ACTION_COMMAND_ANALYSIS_MODE);
            rdbtnAnalysis.addActionListener(this);
        }
        return rdbtnAnalysis;
    }

    private JRadioButton getEditRadioButton() {
        if (rdbtnEdit == null) {
            rdbtnEdit = new JRadioButton("Edit");
            rdbtnEdit.setMnemonic(KeyEvent.VK_E);
            rdbtnEdit.setActionCommand(ACTION_COMMAND_EDIT_MODE);
            rdbtnEdit.addActionListener(this);
        }
        return rdbtnEdit;
    }

	//	private JButton getSwitchworkingDirectoryButton() throws ParameterException, PropertyException, IOException{
    //		if (openButton == null)
    //			openButton = new SwatToolbarButton(ToolbarButtonType.SWITCH_DIRECTORY);
    //		return openButton;
    //	}
    private JButton getNewNetButton() throws ParameterException, PropertyException, IOException {

        JButton newButton = new SwatToolbarButton(ToolbarButtonType.NEW);
        return newButton;
    }

    private String requestFileName(String message, String title) {
        return FileNameDialog.showDialog(SwingUtilities.getWindowAncestor(getParent()), message, title, false);
    }

    private File getAbsolutePathToWorkingDir(String name) throws PropertyException, ParameterException, IOException {
        File file = new File(SwatProperties.getInstance().getWorkingDirectory(), name);
        if (file.exists()) {
            throw new ParameterException("File already exists");
        }
        //TODO: Validate, test if SWATComponent already contains net with same name... etc?
        return file;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try {

            if (e.getActionCommand().equals(ACTION_COMMAND_ANALYSIS_MODE)) {
					if(Workbench.getInstance().getCurrentComponentNeedsParsing() && Workbench.getInstance().getCurrentComponentsSourceSizeTooBig()){
                                                JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this), "Entering analysis Mode requires parsing first");
                                                SwatState.getInstance().setOperatingMode(SwatToolbar.this, OperatingMode.EDIT_MODE);
                                                getEditRadioButton().setSelected(true);
					} else {
						SwatState.getInstance().setOperatingMode(SwatToolbar.this, OperatingMode.ANALYSIS_MODE);
                                        }
            } else if (e.getActionCommand().equals(ACTION_COMMAND_EDIT_MODE)) {
                SwatState.getInstance().setOperatingMode(SwatToolbar.this, OperatingMode.EDIT_MODE);
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void operatingModeChanged() {
        switch (SwatState.getInstance().getOperatingMode()) {
            case ANALYSIS_MODE:
                getAnalysisRadioButton().setSelected(true);
                break;
            case EDIT_MODE:
                getEditRadioButton().setSelected(true);
                break;
        }
        repaint();
    }

	//	public void addOpenActionListener(ActionListener listener) throws ParameterException, PropertyException, IOException {
    //		getSwitchworkingDirectoryButton().addActionListener(listener);
    //	}
    /**
     * reset Toolbar, restore standard components *
     */
    public void clear() {
        this.removeAll();
        //createButtons();
        addDefaultItems();
    }

    private class SwatToolbarButton extends JButton {

        private static final long serialVersionUID = 9184814296174960480L;
        private static final String iconNameFormat = "../resources/icons/%s/%s-%s.png";

        public SwatToolbarButton(ToolbarButtonType type) throws ParameterException, PropertyException, IOException {
            super(IconFactory.getIcon(type.toString().toLowerCase()));
            setBorder(BorderFactory.createEmptyBorder(0, ICON_SPACING, 0, ICON_SPACING));
            setBorderPainted(false);
            setRollover(true);
            setFocusable(false);
			//setContentAreaFilled(false);
            //setVerticalAlignment(CENTER);
            tryToSetPressedButton(type);

            switch (type) {
                case IMPORT:
                    setToolTipText("Import PT-Net from filesystem");
                    addActionListener(new PTImportAction());
                    break;
                case NEW:
                    SwatNewNetToolbar newNetTB = new SwatNewNetToolbar(tabView, treeView);
                    PopUpToolBarAction newNetAction = new PopUpToolBarAction("new net", "new", newNetTB);
                    newNetAction.setButton(this);
                    addActionListener(newNetAction);
                    break;
                case OPEN:
                    break;
                case SAVE_ALL:
                    addActionListener(new SaveAllAction());
                    break;
                case NEW_CPN:
                    setToolTipText("Create new CPnet");
                    addActionListener(new createNewAction(type));
                    break;
                case NEW_PT:
                    setToolTipText("Create new PTnet");
                    addActionListener(new createNewAction(type));
                    break;
                case NEW_IF:
                    setToolTipText("Create new IFnet");
                    addActionListener(new createNewAction(type));
                    break;
                case RENAME:
                    setToolTipText("Rename current net");
                    addActionListener(new RenameAction());
                    break;
                case EDIT_PROPERTY:
                    setToolTipText("Edit SWAT Properties");
                    addActionListener(new EditPropertiesAction());
                    break;
                case DETECTIVE:
                    setToolTipText("Convert to Lola");
                    setHorizontalTextPosition(SwingConstants.CENTER);
                    setVerticalTextPosition(SwingConstants.BOTTOM);
                    setIconTextGap(0);
                    setText("LOLA");
                    //addActionListener(new LolaTransformAction());
                    addActionListener(new LolaAnalyzeAction());
                    break;
            }
        }

        private void tryToSetPressedButton(ToolbarButtonType type) {
                try {
					setPressedIcon(IconFactory.getIconPressed(type.toString().toLowerCase()));
				} catch (ParameterException | PropertyException | IOException e) {
					//Workbench.errorMessage("Could not load icon for pressed button", e, false);
				}
                //setOpaque(false);

        }

    }

    private enum ToolbarButtonType {

        NEW, SAVE, SAVE_ALL, OPEN, IMPORT, SWITCH_DIRECTORY, NEW_PT, NEW_CPN, NEW_IF, NEW_RTPN, RENAME, DETECTIVE, ARISTAFLOW, PRISM, DELETE, AF_TEMPLATE, TIME, EDIT_PROPERTY;
    }

    class createNewAction implements ActionListener {

        private ToolbarButtonType type;

        public createNewAction(SwatToolbar.ToolbarButtonType type) {
            this.type = type;
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            String netName = requestFileName("Please choose a name for the new net:", "New Petri-Net");
            if (netName != null) {
				//IFNet newNet = new IFNet();
                //AbstractGraphicalPN<?, ?, ?, ?, ?, ?, ?> newNet = null;
                try {
					// Test new file name
                    //File file = getAbsolutePathToWorkingDir(netName);
                    AbstractGraphicalPN<?, ?, ?, ?, ?, ?, ?> net = null;
                    switch (type) {
                        case NEW_CPN:
                            net = new GraphicalCPN();
                            break;
                        case NEW_PT:
                            net = new GraphicalPTNet();
                            break;
                        case NEW_IF:
                            net = new GraphicalIFNet(new IFNet());
                            //newNet = new GraphicalIFNet();
                            break;
                        case NEW_RTPN:
                        	net = new GraphicalTimedNet(new TimedNet());
                        default:
                            break;
                    }

                    net.getPetriNet().setName(netName);
                    SwatComponents.getInstance().getContainerPetriNets().addComponent(net);

                } catch (Exception e2) {
                    ExceptionDialog.showException(SwingUtilities.getWindowAncestor(SwatToolbar.this), "Storage Exception", new Exception("Could not add Petri net"), true, false);
                }
            }
        }

        private String requestFileName(String message, String title) {
            return FileNameDialog.showDialog(SwingUtilities.getWindowAncestor(SwatToolbar.this.getParent()), message, title, false);
        }
    }

    class LolaTransformAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            try {
                PNEditorComponent editor = (PNEditorComponent) tabView.getSelectedComponent();
                LolaTransformator lola = new LolaTransformator(editor);
                LolaPresenter presenter = new LolaPresenter(lola.getNetAsLolaFormat());
                presenter.show();
                System.out.println("Generating runtime...");
                System.out.println("Starting Lola...");
                Process p = Runtime.getRuntime().exec("lola-boundednet");
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                System.out.println("Analyzing net...");
                writer.write(lola.getNetAsLolaFormat());
                writer.flush();
                writer.close();
                String result;
                System.out.println("Getting results");
                StringBuilder b = new StringBuilder();
                while ((result = reader.readLine()) != null) {
                    b.append(result);
                    System.out.println(result);
                    b.append("\r\n");
                }
                //System.out.println("result from lola: " + b.toString());
                LolaPresenter outcome = new LolaPresenter(b.toString());
                outcome.show();

            } catch (Exception e) {
                System.out.println("Something went wrong");
                e.printStackTrace();

            }

        }

    }

//    public void setEditMode(boolean editMode){
//            getAnalysisRadioButton().setSelected(!editMode);
//            getEditRadioButton().setSelected(editMode);
//            repaint();
//            SwatState.getInstance().setOperatingMode(this, editMode?OperatingMode.EDIT_MODE:OperatingMode.ANALYSIS_MODE);
//    }

    public static void main(String[] args) throws Exception {
        JPanel panel = new JPanel();
        panel.add(new SwatToolbar(SwatTabView.getInstance(), SwatTreeView.getInstance()));
        new DisplayFrame(panel, true);
    }
}


text:
package com.intellij.psi.stubsHierarchy.impl;

import java.util.Collections;
import java.util.Set;

abstract class QualifiedName {

  abstract void resolveCandidates(StubResolver resolver, Symbol.ClassSymbol place, Set<? super Symbol.ClassSymbol> result)
    throws IncompleteHierarchyException;

  static class OfComponents extends QualifiedName {
    @ShortName final int[] components;

    OfComponents(int[] components) {
      this.components = components;
    }

    @Override
    void resolveCandidates(StubResolver resolver, Symbol.ClassSymbol place, Set<? super Symbol.ClassSymbol> result)
      throws IncompleteHierarchyException {
      for (Symbol symbol : resolver.resolveBase(place, components)) {
        if (symbol instanceof Symbol.ClassSymbol) {
          result.add((Symbol.ClassSymbol)symbol);
        }
      }
    }
  }

  static class OfSingleComponent extends QualifiedName {
    @ShortName final int shortName;

    OfSingleComponent(@ShortName int shortName) {
      this.shortName = shortName;
    }

    @Override
    void resolveCandidates(StubResolver resolver, Symbol.ClassSymbol place, Set<? super Symbol.ClassSymbol> result)
      throws IncompleteHierarchyException {
      for (Symbol symbol : resolver.resolveUnqualified(place, shortName, false)) {
        if (symbol instanceof Symbol.ClassSymbol) {
          result.add((Symbol.ClassSymbol)symbol);
        }
      }
    }
  }

  static class Interned extends QualifiedName {
    @QNameHash final int id;

    Interned(int id) {
      this.id = id;
    }

    @Override
    void resolveCandidates(StubResolver resolver, Symbol.ClassSymbol place, Set<? super Symbol.ClassSymbol> result)
      throws IncompleteHierarchyException {
      Symbol.ClassSymbol[] candidates = resolver.findGlobalType(id);
      if (candidates.length == 0) {
        throw IncompleteHierarchyException.INSTANCE;
      }

      Collections.addAll(result, candidates);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php if (!defined('IN_PHPBB')) exit; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="<?php echo (isset($this->_rootref['S_CONTENT_DIRECTION'])) ? $this->_rootref['S_CONTENT_DIRECTION'] : ''; ?>" lang="<?php echo (isset($this->_rootref['S_USER_LANG'])) ? $this->_rootref['S_USER_LANG'] : ''; ?>" xml:lang="<?php echo (isset($this->_rootref['S_USER_LANG'])) ? $this->_rootref['S_USER_LANG'] : ''; ?>">

<meta http-equiv="content-type" content="text/html; charset=<?php echo (isset($this->_rootref['S_CONTENT_ENCODING'])) ? $this->_rootref['S_CONTENT_ENCODING'] : ''; ?>" />
<meta http-equiv="content-language" content="<?php echo (isset($this->_rootref['S_USER_LANG'])) ? $this->_rootref['S_USER_LANG'] : ''; ?>" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="imagetoolbar" content="no" />
<meta name="resource-type" content="document" />
<meta name="distribution" content="global" />
<meta name="copyright" content="2000, 2002, 2005, 2007 phpBB Group" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<?php echo (isset($this->_rootref['META'])) ? $this->_rootref['META'] : ''; ?>

<title><?php echo (isset($this->_rootref['SITENAME'])) ? $this->_rootref['SITENAME'] : ''; ?> • <?php if ($this->_rootref['S_IN_MCP']) {  echo ((isset($this->_rootref['L_MCP'])) ? $this->_rootref['L_MCP'] : ((isset($user->lang['MCP'])) ? $user->lang['MCP'] : '{ MCP }')); ?> • <?php } else if ($this->_rootref['S_IN_UCP']) {  echo ((isset($this->_rootref['L_UCP'])) ? $this->_rootref['L_UCP'] : ((isset($user->lang['UCP'])) ? $user->lang['UCP'] : '{ UCP }')); ?> • <?php } echo (isset($this->_rootref['PAGE_TITLE'])) ? $this->_rootref['PAGE_TITLE'] : ''; ?></title>

<link rel="stylesheet" href="<?php echo (isset($this->_rootref['T_STYLESHEET_LINK'])) ? $this->_rootref['T_STYLESHEET_LINK'] : ''; ?>" type="text/css" />

<body class="<?php echo (isset($this->_rootref['S_CONTENT_DIRECTION'])) ? $this->_rootref['S_CONTENT_DIRECTION'] : ''; ?>">


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('wooey', '0028_update_script_subparser_data'),
    ]

    operations = [
        migrations.AlterField(
            model_name='scriptparameter',
            name='parser',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'),
        ),
    ]


text:
import React from 'react';
import { storiesOf } from '@storybook/react';
import Pagination from '../src/Pagination';

const stories = storiesOf('Components/Pagination', module);

stories.addParameters({
  info: {
    text: `Add pagination links to help split up your long content into shorter, easier to understand blocks. You just have to provide the items and onSelect attribute, when clicked, the onSelect function will be called with the page number. Otherwise you can customize the page button with PaginationButton component.`
  }
});

stories.add('Default', () => <Pagination items={10} maxButtons={8} />);

stories.add('with activePage', () => <Pagination items={5} activePage={3} />);


text:
FROM nginx:stable

MAINTAINER Michał Kruczek <mkruczek@pgs-soft.com>

COPY ./php.conf /etc/nginx/conf.d/default.conf

ENV PROJECT_NAME demo
ENV PROJECT_WEB_DIR web
ENV PROJECT_INDEX_FILE index.php
ENV PROJECT_DEV_INDEX_FILE index_dev.php

EXPOSE 80

VOLUME /var/www
WORKDIR /var/www

COPY entrypoint.sh /entrypoint.sh

CMD ["/bin/bash", "/entrypoint.sh"]


text: Notification Station of XpressEngine


text:
package me.panavtec.cleancontacts.data.repository.contacts.datasources.api.responses;

import com.google.gson.annotations.Expose;
import me.panavtec.cleancontacts.data.repository.contacts.datasources.api.entities.ApiContact;

public class ApiContactResult {

  @Expose private ApiContact user;
  @Expose private String seed;

  public ApiContact getUser() {
    return user;
  }

  public void setUser(ApiContact user) {
    this.user = user;
  }

  public String getSeed() {
    return seed;
  }

  public void setSeed(String seed) {
    this.seed = seed;
  }
}


text:
<page-title ng-if="layoutOptions.pageTitles" title="Notifications" description="Toastr notifications plugin and their variants"></page-title>

Toastr Examples

					Example, Live Preview
					Usage Directions

						<a href="javascript:;" onclick="toastr.info('Are you the 6 fingered man?');" class="btn btn-info">Information Message

						Simple Toastr notification. To fire this notification the code below is executed:

toastr.info('Are you the 6 fingered man?');

						Success Message

						More advanced Toastr notification. It has close button and title.

						To fire this notification the code below is executed:

var opts = {
			"closeButton": true,
			"debug": false,
			"positionClass": "toast-bottom-right",
			"onclick": null,
			"showDuration": "300",
			"hideDuration": "1000",
			"timeOut": "5000",
			"extendedTimeOut": "1000",
			"showEasing": "swing",
			"hideEasing": "linear",
			"showMethod": "fadeIn",
			"hideMethod": "fadeOut"
		};

		toastr.success("So me by marianne admitted speaking.", "This is a title", opts);

						Danger Message

						This notification will be placed as full-width on top. It has close button and title.

						To fire this notification the code below is executed:

var opts = {
			"closeButton": true,
			"debug": false,
			"positionClass": "toast-top-full-width",
			"onclick": null,
			"showDuration": "300",
			"hideDuration": "1000",
			"timeOut": "5000",
			"extendedTimeOut": "1000",
			"showEasing": "swing",
			"hideEasing": "linear",
			"showMethod": "fadeIn",
			"hideMethod": "fadeOut"
		};

		toastr.error("Do to be agreeable conveying oh assurance. Wicket longer admire do barton vanity itself do in it. Preferred to sportsmen it engrossed listening.", "Fanny at wrong table ye in", opts);

						Warning Message

						This notification will be placed on bottom-right. It has close button and title.

						To fire this notification the code below is executed:

var opts = {
			"closeButton": true,
			"debug": false,
			"positionClass": "toast-bottom-left",
			"onclick": null,
			"showDuration": "300",
			"hideDuration": "1000",
			"timeOut": "5000",
			"extendedTimeOut": "1000",
			"showEasing": "swing",
			"hideEasing": "linear",
			"showMethod": "fadeIn",
			"hideMethod": "fadeOut"
		};

		toastr.warning("Park gate sell they west hard for the.", null, opts);


text:
using System.Drawing;
using Cirrious.MvvmCross.Binding.BindingContext;
using Cirrious.MvvmCross.Touch.Views;
using MonoTouch.UIKit;
using MonoTouch.Foundation;

namespace Splitter.Touch.Views
{
    [Register("SinglePageView")]
    public class SinglePageView : BaseViewController
    {
        public SinglePageView()
        {
            TypeOfView = ViewType.SingleView;
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            View.BackgroundColor = UIColor.LightGray;

            var splitViewButton = UIButton.FromType(UIButtonType.RoundedRect);
            splitViewButton.Frame = new RectangleF(View.Bounds.Width / 2 - 70, View.Bounds.Height / 2 - 20, 140, 40);
            splitViewButton.Font = UIFont.FromName("Helvetica", 22);
            splitViewButton.SetTitle("Split View", UIControlState.Normal);
            Add(splitViewButton);

            var modalButton = UIButton.FromType(UIButtonType.RoundedRect);
            modalButton.Frame = new RectangleF(View.Frame.Width / 2 - 70, View.Bounds.Height / 2 + 20, 140, 40);
            modalButton.Font = UIFont.FromName("Helvetica", 22);
            modalButton.SetTitle("Modal", UIControlState.Normal);
            Add(modalButton);

            var closeButton = UIButton.FromType(UIButtonType.RoundedRect);
            closeButton.Frame = new RectangleF(View.Bounds.Width / 2 - 70, View.Bounds.Height / 2 + 60, 140, 40);
            closeButton.Font = UIFont.FromName("Helvetica", 22);
            closeButton.SetTitle("Close", UIControlState.Normal);
            Add(closeButton);

            var set = this.CreateBindingSet<SinglePageView, Core.ViewModels.SinglePageViewModel>();
            set.Bind(splitViewButton).To(vm => vm.MenuCommand);
            set.Bind(modalButton).To(vm => vm.ModalCommand);
            set.Bind(closeButton).To(vm => vm.CloseCommand);
            set.Apply();
        }
    }
}


text:
<?php

/**
 * Description of VoiceDao
 *
 * @author Daniele Ambrosino
 */
abstract class VoiceDao extends MultimediaMessageDao
{

  protected static $instance;

  public static function getInstance()
  {
    if ( empty(static::$instance) )
    {
      static::$instance = new static();
    }
    return static::$instance;
  }

  protected function constructObject(array $data)
  {

  }

  public function get($id)
  {

  }

  public function update($object)
  {

  }

}


text: Sistema De Informacion  IPUC Pasoancho


text:
package algorithms.search;

import thirdparty.voronoi.VoronoiFortunesSweep;
import algorithms.FixedSizeSortedVector;
import algorithms.util.PairFloat;
import algorithms.util.PixelHelper;
import algorithms.util.PolygonAndPointPlotter;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.set.TLongSet;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import thirdparty.voronoi.VoronoiFortunesSweep.GraphEdge;
import thirdparty.voronoi.VoronoiFortunesSweep.Site;

public class KNearestNeighbors {

    private VoronoiFortunesSweep voronoi = null;

    private Map<PairFloat, Set<Integer>> siteIndexesMap = null;

    // TODO: may want to swap this out for a faster means of
    //    finding the nearest (x[i], y[i]) for a query point
    private KDTreeFloat kdTree = null;

    private float xmin = Float.MAX_VALUE;
    private float xmax = Float.NEGATIVE_INFINITY;
    private float ymin = Float.MAX_VALUE;
    private float ymax = Float.NEGATIVE_INFINITY;

    public KNearestNeighbors(int[] x, int[] y) {
        init(x, y);
    }

    public KNearestNeighbors(float[] x, float[] y) {
        init(x, y);
    }

    public KNearestNeighbors(TLongSet pixIdxs, int width, int height) {
        init(pixIdxs, width, height);
    }

    private void init(int[] x, int[] y) {

        if (x == null || x.length == 0 || y == null
            || y.length == 0 || (x.length != y.length)) {
            throw new IllegalArgumentException(
                "x and y cannot be null or empty "
                    + "and must be same lengths");
        }

        int n = x.length;

        float[] x2 = new float[n];
        float[] y2 = new float[n];

        for (int i = 0; i < n; ++i) {
            x2[i] = x[i];
            y2[i] = y[i];
        }

        init(x2, y2);
    }

    private void init(TLongSet pixIdxs, int width, int height) {

        PixelHelper ph = new PixelHelper();

        int[] xy = new int[2];

        float[] x = new float[pixIdxs.size()];
        float[] y = new float[x.length];
        TLongIterator iter = pixIdxs.iterator();
        int i = 0;
        while (iter.hasNext()) {
            long pixIdx = iter.next();
            ph.toPixelCoords(pixIdx, width, xy);
            x[i] = xy[0];
            y[i] = xy[1];
            ++i;
        }
        assert(i == x.length);

        init(x, y);
    }

    private void init(float[] x, float[] y) {

        if (x == null || x.length == 0 || y == null
            || y.length == 0 || (x.length != y.length)) {
            throw new IllegalArgumentException(
                "x and y cannot be null or empty "
                    + "and must be same lengths");
        }
        if (x.length < 3) {
            throw new IllegalArgumentException("x and y "
            + " must be at least length 3 in size");
        }

        int n = x.length;

        xmin = Float.MAX_VALUE;
        xmax = Float.NEGATIVE_INFINITY;
        ymin = Float.MAX_VALUE;
        ymax = Float.NEGATIVE_INFINITY;
        for (int i = 0; i < n; ++i) {
            float xp = x[i];
            float yp = y[i];
            if (xp < xmin) {
                xmin = xp;
            }
            if (xp > xmax) {
                xmax = xp;
            }
            if (yp < ymin) {
                ymin = yp;
            }
            if (yp > ymax) {
                ymax = yp;
            }
        }

        int minDist = 0;

        voronoi = new VoronoiFortunesSweep();

        // O(N * log_2(N)) to build
        voronoi.generateVoronoi(x, y, xmin, xmax, ymin, ymax,
            minDist);

        // TODO: consider a LinkedHashSet here as it is ordered, but the
        // "contains method is O(1).
        LinkedList<GraphEdge> edges = voronoi.getAllEdges();

        Site[] sites = voronoi.getSites();

        siteIndexesMap = new HashMap<PairFloat, Set<Integer>>();

        assert (!edges.isEmpty());
        for (GraphEdge edge : edges) {
            int s1 = edge.site1;
            int s2 = edge.site2;

            PairFloat p1 = sites[s1].getCoord();
            PairFloat p2 = sites[s2].getCoord();

            Set<Integer> indexes = siteIndexesMap.get(p1);
            if (indexes == null) {
                indexes = new HashSet<Integer>();
                siteIndexesMap.put(p1, indexes);
            }
            indexes.add(Integer.valueOf(s2));

            indexes = siteIndexesMap.get(p2);
            if (indexes == null) {
                indexes = new HashSet<Integer>();
                siteIndexesMap.put(p2, indexes);
            }
            indexes.add(Integer.valueOf(s1));
        }

        assert(sites.length == x.length);

        // points closer than minDist are not present,
        // so the map is possibly smaller than all points.
        // therefore, for this use of voronoi, need minDist=0.
        {//DEBUG
            if (siteIndexesMap.size() != x.length) {
                Logger.getLogger(this.getClass().getName())
                    .warning("siteMap.size=" + siteIndexesMap.size()
                    + " x.length=" + x.length);
            }
        }
        //assert(siteIndexesMap.size() == x.length);

        // retrieve the points from voronoi sites because they are sorted
        n = sites.length;
        float[] xp = new float[n];
        float[] yp = new float[n];
        for (int i = 0; i < n; ++i) {
            PairFloat p = sites[i].getCoord();
            xp[i] = p.getX();
            yp[i] = p.getY();
        }

        //O(N*lg_2(N)
        kdTree = new KDTreeFloat(xp, yp, true);
    }

    private float dist(float x, float y, PairFloat p) {
        float diffX = x - p.getX();
        float diffY = y - p.getY();
        return (float)Math.sqrt(diffX * diffX) + (diffY * diffY);
    }

    private static class PairDist implements Comparable<PairDist>{
        PairFloat s1;
        float dist;
        @Override
        public int compareTo(PairDist other) {
            return Float.compare(dist, other.dist);
        }
    }

    public List<PairFloat> findNearest(int k, float x, float y) {
        return findNearest(k, x, y, Float.MAX_VALUE);
    }

    public List<PairFloat> findNearest(int k, float x, float y, float maxDistance) {

        // O(log_2(N) at best, but some extreme queries are O(N).
        // nearest site(s). (if same distances, returns more than one).
        Set<PairFloat> nearest = kdTree.findNearestNeighbor(x, y);

        if (nearest == null) {
            return null;
        }

        /*
        a fixed vector of size k tracks the nearest and nearest
        adjacent.

        the search for k nearest continues in the adjacent sites
        as long as the adjacent site (whose neighbors should be
        searched) is nearer than the last item in the fixed vector.

        */

        // each fixed size vector comparison on insert is O(log_2(k))
        FixedSizeSortedVector<PairDist> vec =
            new FixedSizeSortedVector<PairDist>(k, PairDist.class);

        Site[] sites = voronoi.getSites();

        Set<PairFloat> visited = new HashSet<PairFloat>();

        ArrayDeque<PairFloat> queue = new ArrayDeque<PairFloat>();
        queue.addAll(nearest);

        while (!queue.isEmpty()) {

            PairFloat site = queue.pop();

            if (visited.contains(site)) {
                continue;
            }
            visited.add(site);

            float dist = dist(x, y, site);

            if (dist > maxDistance) {
                continue;
            }

            // if vec is not full or if site is closer than
            //  last full vec member, add site and add it's neighbors
            //  to queue

            int nV = vec.getNumberOfItems();
            if ((nV < k) || ((nV > 0) &&
                (dist < vec.getArray()[nV-1].dist))) {

                PairDist pd = new PairDist();
                pd.s1 = site;
                pd.dist = dist;
                vec.add(pd);

                // add neighbors to queue

                Set<Integer> siteIndexes = siteIndexesMap.get(site);

                if (siteIndexes == null) {
                    throw new IllegalStateException("error in algorithm:"
                        + " voronoi diagram has no neighbors for "
                        + " (" + site.getX() + "," + site.getY() + ")");
                }

                for (Integer index2 : siteIndexes) {
                    PairFloat site2 = sites[index2.intValue()].getCoord();
                    queue.add(site2);
                }
            }
        }

        List<PairFloat> output = new ArrayList<PairFloat>();
        PairDist[] a = vec.getArray();
        for (int i = 0; i < vec.getNumberOfItems(); ++i) {
            output.add(a[i].s1);
        }

        return output;
    }

    public void debug(int fileNumber) throws IOException {

        Site[] sites = voronoi.getSites();
        int n = sites.length;
        float[] x = new float[n];
        float[] y = new float[n];
        for (int i = 0; i < n; ++i) {
            x[i] = sites[i].getCoord().getX();
            y[i] = sites[i].getCoord().getY();
        }

        LinkedList<GraphEdge> edges = voronoi.getAllEdges();

        PolygonAndPointPlotter plotter =
            new PolygonAndPointPlotter(xmin, xmax, ymin, ymax);

        float[] xPolygon = null;
        float[] yPolygon = null;
        // intentionally null for this because the method will ignore ull
        plotter.addPlot(x, y, xPolygon, yPolygon, "points");

        int n2 = edges.size();
        xPolygon = new float[2*n2];
        yPolygon = new float[2*n2];
        int count = 0;
        for (GraphEdge edge : edges) {
            xPolygon[count] = edge.x1;
            yPolygon[count] = edge.y1;
            xPolygon[count + 1] = edge.x2;
            yPolygon[count + 1] = edge.y2;
            count += 2;
        }
        plotter.addPlotWithLines(x, y, xPolygon, yPolygon,
            "edges");
        String filePath = plotter.writeFile("debug_voron_" + fileNumber);
        System.out.println("wrote file=" + filePath);
    }

}


text:
class Token(dict):

    def __init__(self, token):
        self.update(token)

    @property
    def value(self):
        """
        :returns: The value of the token.
        """
        return self.get('value')

class TokensClient(object):

    def __init__(self, api):
        self.api = api

    def get(self):
        """Get an authentication token.

        :rtype: Token
        """
        response = self.api.get('/tokens')
        return Token(response)


text:
package sample.insurance.pageobjects;

import com.borland.silktest.jtf.common.TruelogScreenshotMode;
import com.borland.silktest.jtf.common.types.FindOptions;
import com.borland.silktest.jtf.xbrowser.DomButton;
import com.borland.silktest.jtf.xbrowser.DomElement;
import com.borland.silktest.jtf.xbrowser.DomTextField;

public class HomePage extends InsuranceMainPage {

	private final String locLogoutBtn = "//INPUT[@id='logout-form:logout']";
	private final String locEMailTxt = "Web.Login.EMail";
	private final String locPasswordTxt = "Web.Login.Password";
	private final String locLoginBtn = "Web.Login.Login";

	public HomePage() {
		super();
	}

	public HomePage login(String username, String password) {
		DomButton logout = browserWindow.<DomButton>find(locLogoutBtn, new FindOptions(false, 500));
		if (logout != null)
			logout.select();

		desktop.<DomTextField>find(locEMailTxt).setText(username);
		desktop.<DomTextField>find(locPasswordTxt).setText(password);
		desktop.logInfo("Login", TruelogScreenshotMode.ActiveWindow);
		desktop.<DomButton>find(locLoginBtn).select();
		desktop.logInfo("Logged In", TruelogScreenshotMode.ActiveWindow);

		return this;
	}

	public String getUserName() {
		DomElement userName = browserWindow.<DomElement> find(
				"//LABEL[@class='login' and @for='logout-form']", new FindOptions(false, 500));
		if (userName != null)
			return userName.getText();

		return "";
	}

	public HomePage logout() {
		DomButton logout = browserWindow.<DomButton>find(locLogoutBtn,
				new FindOptions(false, 500));
		if (logout != null)
			logout.select();

		return this;
	}

}


text:
from pyramid.config import Configurator
from pyramid.interfaces import IRouteRequest
from pyramid.interfaces import IViewClassifier
from pyramid.interfaces import IView
from pyramid.static import static_view
from zope.interface import Interface
from collections import OrderedDict
from pyramid_cli.cli import main

import click

PAD = 3
ANY_KEY = '*'
UNKNOWN_KEY = '<unknown>'

def _get_mapper(registry):
    config = Configurator(registry=registry)
    return config.get_routes_mapper()

def _get_print_format(max_name, max_pattern, max_view, max_method):
    fmt = '%-{0}s %-{1}s %-{2}s %-{3}s'.format(
        max_name + PAD,
        max_pattern + PAD,
        max_view + PAD,
        max_method + PAD,
    )
    return fmt

def _get_request_methods(route_request_methods, view_request_methods):
    has_route_methods = route_request_methods is not None
    has_view_methods = len(view_request_methods) > 0
    has_methods = has_route_methods or has_view_methods

    if has_route_methods is False and has_view_methods is False:
        request_methods = [ANY_KEY]
    elif has_route_methods is False and has_view_methods is True:
        request_methods = view_request_methods
    elif has_route_methods is True and has_view_methods is False:
        request_methods = route_request_methods
    else:
        request_methods = set(route_request_methods).intersection(
            view_request_methods
        )

    if has_methods and not request_methods:
        request_methods = '<route mismatch>'
    elif request_methods:
        request_methods = ','.join(request_methods)

    return request_methods

def _get_static_view(view_callable):
    if hasattr(view_callable, '__original_view__'):
        original_view = view_callable.__original_view__
    else:
        original_view = view_callable

    if isinstance(original_view, static_view):
        return original_view

def _get_view_module(view_callable, view_intr=None):
    if view_callable is None:
        return UNKNOWN_KEY

    static_view_callable = _get_static_view(view_callable)
    if static_view_callable is not None:
        if static_view_callable.package_name is not None:
            return '%s:%s' % (
                static_view_callable.package_name,
                static_view_callable.docroot
            )
        else:
            return static_view_callable.docroot

    if hasattr(view_callable, '__name__'):
        view_name = view_callable.__name__
    else:
        # Currently only MultiView hits this,
        # we could just not run _get_view_module
        # for them and remove this logic
        view_name = str(view_callable)

    view_module = '%s.%s' % (
        view_callable.__module__,
        view_name,
    )

    if view_intr is not None:
        if view_intr.get('attr') is not None:
            view_module = '%s.%s' % (view_module, view_intr['attr'])

    # If pyramid wraps something in wsgiapp or wsgiapp2 decorators
    # that is currently returned as pyramid.router.decorator, lets
    # hack a nice name in:
    if view_module == 'pyramid.router.decorator':
        view_module = '<wsgiapp>'

    return view_module

def get_route_data(route, registry):
    pattern = route.pattern

    if not pattern.startswith('/'):
        pattern = '/%s' % pattern

    request_iface = registry.queryUtility(
        IRouteRequest,
        name=route.name
    )
    route_request_methods = None
    view_request_methods = OrderedDict()
    view_callable = None

    route_intr = registry.introspector.get(
        'routes', route.name
    )

    view_callable = registry.adapters.lookup(
        (IViewClassifier, request_iface, Interface),
        IView,
        name='',
        default=None
    )
    view_module = _get_view_module(view_callable)

    # Introspectables can be turned off, so there could be a chance
    # that we have no `route_intr` but we do have a route + callable
    if route_intr is None:
        view_request_methods[view_module] = []
    else:
        route_request_methods = route_intr['request_methods']

        view_intr = registry.introspector.related(route_intr)

        if view_intr:
            for view in view_intr:
                # We don't want to run through root factories and other
                # related introspectors
                if view.category_name != 'views':
                    continue

                request_method = view.get('request_methods')
                view_callable = view['callable']
                view_module = _get_view_module(view_callable, view)

                if request_method is not None:
                    if view_module not in view_request_methods:
                        view_request_methods[view_module] = []

                    if request_method is not None:
                        view_request_methods[view_module].append(
                            request_method
                        )
                else:
                    if view_module not in view_request_methods:
                        view_request_methods[view_module] = []

        else:
            view_request_methods[view_module] = []

    final_routes = []

    for view_module, methods in view_request_methods.items():
        request_methods = _get_request_methods(
            route_request_methods,
            methods
        )

        final_routes.append((
            route.name,
            pattern,
            view_module,
            request_methods,
        ))

    return final_routes

@main.command()
@click.pass_obj
def routes(obj):
    registry = obj.pyramid_env['registry']
    mapper = _get_mapper(registry)

    max_name = len('Name')
    max_pattern = len('Pattern')
    max_view = len('View')
    max_method = len('Method')

    routes = mapper.get_routes()

    mapped_routes = []

    for route in routes:
        route_data = get_route_data(route, registry)

        for name, pattern, view, method in route_data:
            if len(name) > max_name:
                max_name = len(name)

            if len(pattern) > max_pattern:
                max_pattern = len(pattern)

            if len(view) > max_view:
                max_view = len(view)

            if len(method) > max_method:
                max_method = len(method)

            mapped_routes.append((name, pattern, view, method))

    fmt = _get_print_format(max_name, max_pattern, max_view, max_method)

    click.echo(fmt % ('Name', 'Pattern', 'View', 'Method'))
    click.echo(fmt % (
        '-' * max_name,
        '-' * max_pattern,
        '-' * max_view,
        '-' * max_method
    ))

    for route in mapped_routes:
        click.echo(fmt % route)


text:
require 'rubygems'
require 'test/unit'
require 'shoulda'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'clayburn-gen'

class Test::Unit::TestCase
end


text:
<?php
/**
 * Initializes Clockwork at the beginning of a request and
 * finalizes it at the end, adding the correct headers to
 * the response.
 *
 * @author Mark Guinn <mark@adaircreative.com>
 * @date 11.07.2014
 * @package clockwork
 */
namespace Clockwork\Support\Silverstripe;

use Clockwork\Clockwork;
use Clockwork\DataSource\PhpDataSource;
use Clockwork\Storage\FileStorage;
use DataModel;
use Session;
use SS_HTTPRequest;
use SS_HTTPResponse;
use Director;
use DB;

class RequestFilter implements \RequestFilter
{
	/** @var Clockwork */
    protected $clockwork;

    /**
     * Filter executed before a request processes
     *
     * @param SS_HTTPRequest $request Request container object
     * @param Session $session        Request session
     * @param DataModel $model        Current DataModel
     * @return boolean Whether to continue processing other filters. Null or true will continue processing (optional)
     */
    public function preRequest(SS_HTTPRequest $request, Session $session, DataModel $model) {
        if (Director::isDev() && class_exists('Clockwork\\Clockwork')) {

            $this->clockwork = new Clockwork();

            if (!DB::get_conn()) {
                global $databaseConfig;
                if ($databaseConfig) {
                    DB::connect($databaseConfig);
                }
            }

            // Wrap the current database adapter in a proxy object so we can log queries
            DB::set_conn(new DatabaseProxy(DB::get_conn()));
            $this->clockwork->addDataSource(new SilverstripeDataSource());

            // Attach a default datasource that comes with
            // the Clockwork library (grabs session info, etc)
            $this->clockwork->addDataSource(new PhpDataSource());

            // Give it a place to store data
            $this->clockwork->setStorage(new FileStorage(TEMP_FOLDER . '/clockwork'));
        }
    }

    /**
     * Filter executed AFTER a request
     *
     * @param SS_HTTPRequest $request   Request container object
     * @param SS_HTTPResponse $response Response output object
     * @param DataModel $model          Current DataModel
     * @return boolean Whether to continue processing other filters. Null or true will continue processing (optional)
     */
    public function postRequest(SS_HTTPRequest $request, SS_HTTPResponse $response, DataModel $model) {
        if (isset($this->clockwork)) {
            $response->addHeader("X-Clockwork-Id", $this->clockwork->getRequest()->id);
            $response->addHeader("X-Clockwork-Version", Clockwork::VERSION);
            $response->addHeader('X-Clockwork-Path', Director::baseURL() . '__clockwork/');
            $this->clockwork->resolveRequest();
            $this->clockwork->storeRequest();
        }
    }
}


text:
from datapackage_pipelines_knesset.common.processors.dump_to_sql import Processor as DumpToSqlProcessor
from .common import get_pipeline_processor_parameters, get_pipeline_spec_pipeline_names
from .mocks.dataservice import MockAddDataserviceCollectionResourceProcessor
import os

class MockDumpToSqlProcessor(DumpToSqlProcessor):

    def save_schemas(self):
        self._tablename = self._parameters["table"]
        save_schema = os.path.join(os.path.dirname(__file__), "mocks", "table_schema_{table_name}.{ext}")
        self._save_schema_json(save_schema)
        self._save_schema_html(save_schema)

def assert_dump_to_sql_table_schema(pipeline_spec_name, pipeline_name):
    datapackage = {"name": "_", "resources": []}
    processor_matcher = lambda step: step["run"] == "..datapackage_pipelines_knesset.dataservice.processors.add_dataservice_collection_resource"
    parameters = get_pipeline_processor_parameters(pipeline_spec_name, pipeline_name, processor_matcher)
    processor = MockAddDataserviceCollectionResourceProcessor(parameters, datapackage, [])
    datapackage, resources = processor.spew()
    processor_matcher = lambda step: step["run"] == "..datapackage_pipelines_knesset.common.processors.dump_to_sql"
    parameters = get_pipeline_processor_parameters(pipeline_spec_name, pipeline_name, processor_matcher)
    processor = MockDumpToSqlProcessor(parameters, datapackage, [])
    datapackage, resources, stats = processor.spew()
    for resource in resources:
        pass
    filenames = {ext: os.path.join(os.path.dirname(__file__), "mocks",
                                  "table_schema_{}.{}".format(pipeline_name, ext))
                 for ext in ["html", "json"]}
    for filename in filenames.values():
        if os.path.exists(filename):
            os.unlink(filename)
    processor.save_schemas()
    for ext, filename in filenames.items():
        if ext == "json":
            assert "fields" in fs.json_load(filename)
        else:
            assert f.read(6) == "<html>"

def test_dump_to_sql_table_schemas():
    for pipeline_spec_name in ["bills", "committees", "laws"]:
        processor_matcher = lambda step: step["run"] == "..datapackage_pipelines_knesset.dataservice.processors.add_dataservice_collection_resource"
        for pipeline_name in get_pipeline_spec_pipeline_names(pipeline_spec_name, processor_matcher):
            assert_dump_to_sql_table_schema(pipeline_spec_name, pipeline_name)


text:
This folder contains files demonstrating how to work with xgboost.

## xgboost.txt
The sample training data utilized in the main demo folder but in LibSVM format which is used by xgboost.

## featmap.txt
A configuration file telling xgboost the feature names that feature ordinals refer to.

## xgb.py
A bare-bones script for reading `xgboost.txt` and training a model for usage with the plugin.

## xgb-model.json
Included for convenience, this is the output of xgb.py, a JSON formatted model compatible with the LTR plugin.

# Notes
Although there are PyPI packages for xgboost, some users will find that installation fails in their local environments.  If this occurs the best workaround is to clone the xgboost repository and do a local build with the latest.

```
git clone --recursive https://github.com/dmlc/xgboost
cd xgboost
make -j4
cd python-package
python setup.py install
```

Note: If doing a global install you may need to run with root privileges, the above should work in a virtual environment.


text:
<StructureMap MementoStyle="Attribute">
  <DefaultInstance
    PluginType="StructureMap.Testing.Widget.IWidget,StructureMap.Testing.Widget"
    PluggedType="StructureMap.Testing.Widget.ColorWidget,StructureMap.Testing.Widget"
    Color="Red" />

  <DefaultInstance
    PluginType="StructureMap.Testing.Widget.Rule,StructureMap.Testing.Widget"
    PluggedType="StructureMap.Testing.Widget.ColorRule,StructureMap.Testing.Widget"
    Color="Blue"
    Scope="Singleton"
    Name="TheBlueOne"/>
</StructureMap>


text:
'use strict';

var shell = require('shelljs');
var Promise = require('promise');
var bunyan = require('bunyan');

var config = require('../config');

var log = bunyan.createLogger({
	name: 'disc'
});

var dir = config.dest;
if (config.module) {
	dir = config.demoDest;
}
var src = dir + 'main.js';
var dest = dir + 'disc.html';

module.exports = function() {
	return new Promise(function(resolve, reject) {
		if (config.prod) {
			return resolve();
		}
		var updateStart = Date.now();

		shell.exec('node_modules/.bin/discify ' + src + ' > ' + dest, function(code, output) {
			if (code === 0) {
				log.info('Updated disc.html in ' + (Date.now() - updateStart) + 'ms');
				resolve();
			} else {
				reject(output);
			}
		});
	});
};

if (require.main === module) {
	module.exports().then(function() {
		process.exit();
	}).catch(function(err) {
		throw(err);
	});
}


text:
package dcraft.web.ui.tags;

import dcraft.web.ui.UIElement;

public class ServerScript extends UIElement {
	public ServerScript() {
		super("dc.ServerScript");
	}

	@Override
	public UIElement newNode() {
		return new ServerScript();
	}
}


text:
class ArcIconCache : public arc::ArcIconCacheDelegate,
                     public crosapi::mojom::ArcObserver {
 public:
  ArcIconCache();
  ArcIconCache(const ArcIconCache&) = delete;
  ArcIconCache& operator=(const ArcIconCache&) = delete;
  ~ArcIconCache() override;

  // Start observing ARC in ash-chrome.
  void Start();

  // arc::ArcIconCacheDelegate:
  // Retrieves icons for the |activities| and calls |cb|.
  // See ActivityIconLoader::GetActivityIcons() for more details.
  GetResult GetActivityIcons(const std::vector<ActivityName>& activities,
                             OnIconsReadyCallback cb) override;

 private:
  THREAD_CHECKER(thread_checker_);

  // crosapi::mojom::ArcObserver
  void OnIconInvalidated(const std::string& package_name) override;

  // Cached activity icons.
  ActivityIconLoader icon_loader_;

  // Receives mojo messages from ash-chrome.
  mojo::Receiver<crosapi::mojom::ArcObserver> receiver_{this};
};

#endif  // CHROME_BROWSER_LACROS_ARC_ARC_ICON_CACHE_H_


text:
"""Slicer test."""

from absl.testing import parameterized
import apache_beam as beam
from apache_beam.testing import util
import numpy as np
import six
import tensorflow as tf
from tensorflow_model_analysis import constants
from tensorflow_model_analysis import types
from tensorflow_model_analysis.eval_saved_model import testutil
from tensorflow_model_analysis.extractors import slice_key_extractor
from tensorflow_model_analysis.post_export_metrics import metric_keys
from tensorflow_model_analysis.proto import config_pb2
from tensorflow_model_analysis.proto import metrics_for_slice_pb2
from tensorflow_model_analysis.slicer import slicer_lib as slicer

from google.protobuf import text_format

def make_features_dict(features_dict):
  result = {}
  for key, value in features_dict.items():
    result[key] = {'node': np.array(value)}
  return result

def create_fpls():
  fpl1 = types.FeaturesPredictionsLabels(
      input_ref=0,
      features=make_features_dict({
          'gender': ['f'],
          'age': [13],
          'interest': ['cars']
      }),
      predictions=make_features_dict({
          'kb': [1],
      }),
      labels=make_features_dict({'ad_risk_score': [0]}))
  fpl2 = types.FeaturesPredictionsLabels(
      input_ref=0,
      features=make_features_dict({
          'gender': ['m'],
          'age': [10],
          'interest': ['cars']
      }),
      predictions=make_features_dict({
          'kb': [1],
      }),
      labels=make_features_dict({'ad_risk_score': [0]}))
  return [fpl1, fpl2]

def wrap_fpl(fpl):
  return {
      constants.INPUT_KEY: fpl,
      constants.FEATURES_PREDICTIONS_LABELS_KEY: fpl
  }

class SlicerTest(testutil.TensorflowModelAnalysisTest, parameterized.TestCase):

  def setUp(self):
    super().setUp()
    self.longMessage = True  # pylint: disable=invalid-name

  def _makeFeaturesDict(self, features_dict):
    result = {}
    for key, value in features_dict.items():
      result[key] = {'node': np.array(value)}
    return result

  def assertSliceResult(self, name, features_dict, columns, features, expected):
    spec = slicer.SingleSliceSpec(columns=columns, features=features)
    msg = 'Test case %s: slice on columns %s, features %s' % (name, columns,
                                                              features)
    six.assertCountEqual(
        self, expected,
        slicer.get_slices_for_features_dicts([features_dict], None, [spec]),
        msg)

  def testDeserializeSliceKey(self):
    slice_metrics = text_format.Parse(
        """
          single_slice_keys {
            column: 'age'
            int64_value: 5
          }
          single_slice_keys {
            column: 'language'
            bytes_value: 'english'
          }
          single_slice_keys {
            column: 'price'
            float_value: 1.0
          }
        """, metrics_for_slice_pb2.SliceKey())

    got_slice_key = slicer.deserialize_slice_key(slice_metrics)
    self.assertCountEqual([('age', 5), ('language', 'english'), ('price', 1.0)],
                          got_slice_key)

  def testDeserializeCrossSliceKey(self):
    slice_metrics = text_format.Parse(
        """
          baseline_slice_key {
            single_slice_keys {
              column: 'age'
              int64_value: 5
            }
            single_slice_keys {
              column: 'language'
              bytes_value: 'english'
            }
            single_slice_keys {
              column: 'price'
              float_value: 1.0
            }
          }
          comparison_slice_key {
            single_slice_keys {
              column: 'age'
              int64_value: 8
            }
            single_slice_keys {
              column: 'language'
              bytes_value: 'hindi'
            }
          }
        """, metrics_for_slice_pb2.CrossSliceKey())

    got_slice_key = slicer.deserialize_cross_slice_key(slice_metrics)
    self.assertCountEqual(
        ((('age', 5), ('language', 'english'), ('price', 1.0)),
         (('age', 8), ('language', 'hindi'))), got_slice_key)

  def testSliceEquality(self):
    overall = slicer.SingleSliceSpec()
    age_column = slicer.SingleSliceSpec(columns=['age'])
    age_feature = slicer.SingleSliceSpec(features=[('age', 5)])
    age_and_gender = slicer.SingleSliceSpec(
        columns=['age'], features=[('gender', 'f')])

    # Note that we construct new instances of the slices to ensure that we
    # aren't just checking object identity.
    def check_equality_and_hash_equality(left, right):
      self.assertEqual(left, right)
      self.assertEqual(hash(left), hash(right))

    check_equality_and_hash_equality(overall, slicer.SingleSliceSpec())
    check_equality_and_hash_equality(age_column,
                                     slicer.SingleSliceSpec(columns=['age']))
    check_equality_and_hash_equality(
        age_feature, slicer.SingleSliceSpec(features=[('age', 5)]))
    check_equality_and_hash_equality(
        age_and_gender,
        slicer.SingleSliceSpec(columns=['age'], features=[('gender', 'f')]))

    self.assertNotEqual(overall, age_column)
    self.assertNotEqual(age_column, age_feature)
    self.assertNotEqual(age_column, age_and_gender)
    self.assertNotEqual(age_feature, age_and_gender)

    self.assertCountEqual([slicer.SingleSliceSpec()], [overall])
    self.assertCountEqual([
        slicer.SingleSliceSpec(columns=['age']),
        slicer.SingleSliceSpec(),
        slicer.SingleSliceSpec(features=[('age', 5)]),
        slicer.SingleSliceSpec(columns=['age'], features=[('gender', 'f')])
    ], [age_and_gender, age_feature, overall, age_column])

  def testNoOverlappingColumns(self):
    self.assertRaises(ValueError, slicer.SingleSliceSpec, ['age'], [('age', 5)])

  def testNonUTF8ValueRaisesValueError(self):
    column_name = 'column_name'
    invalid_value = b'\x8a'
    spec = slicer.SingleSliceSpec(columns=[column_name])
    features_dict = self._makeFeaturesDict({
        column_name: [invalid_value],
    })
    with self.assertRaisesRegex(ValueError, column_name):
      list(slicer.get_slices_for_features_dicts([features_dict], None, [spec]))

  def testGetSlicesForFeaturesDictUnivalent(self):
    test_cases = [
        ('Overall', [], [], [()]),
        ('Feature does not match', [], [('age', 99)], []),
        ('No such column', ['no_such_column'], [], []),
        ('Single column', ['age'], [], [(('age', 5),)]),
        ('Single feature', [], [('age', 5)], [(('age', 5),)]),
        ('Single feature type mismatch', [], [('age', '5')], [(('age', 5),)]),
        ('One column, one feature',
         ['gender'], [('age', 5)], [(('age', 5), ('gender', 'f'))]),
        ('Two features', ['interest', 'gender'], [('age', 5)],
         [(('age', 5), ('gender', 'f'), ('interest', 'cars'))]),
    ]  # pyformat: disable
    features_dict = self._makeFeaturesDict({
        'gender': ['f'],
        'age': [5],
        'interest': ['cars']
    })
    for (name, columns, features, expected) in test_cases:
      self.assertSliceResult(name, features_dict, columns, features, expected)

  def testGetSlicesForFeaturesDictMultivalent(self):
    test_cases = [
        (
            'One column',
            ['fruits'],
            [],
            [
                (('fruits', 'apples'),),
                (('fruits', 'pears'),)
            ],
        ),
        (
            'Two columns',
            ['fruits', 'interests'],
            [],
            [
                (('fruits', 'apples'), ('interests', 'cars')),
                (('fruits', 'apples'), ('interests', 'dogs')),
                (('fruits', 'pears'), ('interests', 'cars')),
                (('fruits', 'pears'), ('interests', 'dogs'))
            ],
        ),
        (
            'One feature',
            [],
            [('interests', 'cars')],
            [
                (('interests', 'cars'),)
            ],
        ),
        (
            'Two features',
            [],
            [('gender', 'f'), ('interests', 'cars')],
            [
                (('gender', 'f'), ('interests', 'cars'))
            ],
        ),
        (
            'One column, one feature',
            ['fruits'],
            [('interests', 'cars')],
            [
                (('fruits', 'apples'), ('interests', 'cars')),
                (('fruits', 'pears'), ('interests', 'cars'))
            ],
        ),
        (
            'One column, two features',
            ['fruits'],
            [('gender', 'f'), ('interests', 'cars')],
            [
                (('fruits', 'apples'), ('gender', 'f'), ('interests', 'cars')),
                (('fruits', 'pears'), ('gender', 'f'), ('interests', 'cars')),
            ],
        ),
        (
            'Two columns, one feature',
            ['interests', 'fruits'], [('gender', 'f')],
            [
                (('fruits', 'apples'), ('gender', 'f'), ('interests', 'cars')),
                (('fruits', 'pears'), ('gender', 'f'), ('interests', 'cars')),
                (('fruits', 'apples'), ('gender', 'f'), ('interests', 'dogs')),
                (('fruits', 'pears'), ('gender', 'f'), ('interests', 'dogs'))
            ],
        ),
        (
            'Two columns, two features',
            ['interests', 'fruits'],
            [('gender', 'f'), ('age', 5)],
            [
                (('age', 5), ('fruits', 'apples'), ('gender', 'f'),
                 ('interests', 'cars')),
                (('age', 5), ('fruits', 'pears'), ('gender', 'f'),
                 ('interests', 'cars')),
                (('age', 5), ('fruits', 'apples'), ('gender', 'f'),
                 ('interests', 'dogs')),
                (('age', 5), ('fruits', 'pears'), ('gender', 'f'),
                 ('interests', 'dogs'))
            ],
        )
    ]  # pyformat: disable

    features_dict = self._makeFeaturesDict({
        'gender': ['f'],
        'age': [5],
        'interests': ['cars', 'dogs'],
        'fruits': ['apples', 'pears']
    })

    for (name, columns, features, expected) in test_cases:
      self.assertSliceResult(name, features_dict, columns, features, expected)

  def testGetSlicesForFeaturesDictMultipleSingleSliceSpecs(self):
    features_dict = self._makeFeaturesDict({
        'gender': ['f'],
        'age': [5],
        'interest': ['cars']
    })

    spec_overall = slicer.SingleSliceSpec()
    spec_age = slicer.SingleSliceSpec(columns=['age'])
    spec_age4 = slicer.SingleSliceSpec(features=[('age', 4)])
    spec_age5_gender = slicer.SingleSliceSpec(
        columns=['gender'], features=[('age', 5)])

    slice_spec = [spec_overall, spec_age, spec_age4, spec_age5_gender]
    expected = [(), (('age', 5),), (('age', 5), ('gender', 'f'))]
    self.assertCountEqual(
        expected,
        slicer.get_slices_for_features_dicts([features_dict], None, slice_spec))

  def testStringifySliceKey(self):
    test_cases = [
        ('overall', (), 'Overall'),
        ('one bytes feature', (('age_str', '5'),), 'age_str:5'),
        ('one int64 feature', (('age', 1),), 'age:1'),
        ('mixed', (('age', 1), ('gender', 'f')), 'age_X_gender:1_X_f'),
        ('more', (('age', 1), ('gender', 'f'), ('interest', 'cars')),
         'age_X_gender_X_interest:1_X_f_X_cars'),
        ('unicode', (('text', b'\xe4\xb8\xad\xe6\x96\x87'),), u'text:\u4e2d\u6587'),
    ]  # pyformat: disable
    for (name, slice_key, stringified_key) in test_cases:
      self.assertEqual(
          stringified_key, slicer.stringify_slice_key(slice_key), msg=name)

  @parameterized.named_parameters(('empty_slice_keys', [], np.array([])),
                                  ('specific_and_overall_slice_key', [
                                      ('f', 1), ()
                                  ], np.array([('f', 1), ()], dtype=object)))
  def testSliceKeysToNumpy(self, slice_keys_tuples, expected_slice_keys_array):
    np.testing.assert_array_equal(
        slicer.slice_keys_to_numpy_array(slice_keys_tuples),
        expected_slice_keys_array)

  def testSliceKeysToNumpyOverall(self):
    actual = slicer.slice_keys_to_numpy_array([()])
    self.assertIsInstance(actual, np.ndarray)
    self.assertEqual(actual.dtype, object)
    self.assertEqual(actual.shape, (1,))
    self.assertEqual(actual[0], ())

  def testIsCrossSliceApplicable(self):
    test_cases = [
        (True, 'overall pass', ((), (('b', 2),)), config_pb2.CrossSlicingSpec(
            baseline_spec=config_pb2.SlicingSpec(),
            slicing_specs=[config_pb2.SlicingSpec(feature_values={'b': '2'})])),
        (True, 'value pass', ((('a', 1),), (('b', 2),)),
         config_pb2.CrossSlicingSpec(
             baseline_spec=config_pb2.SlicingSpec(feature_values={'a': '1'}),
             slicing_specs=[config_pb2.SlicingSpec(feature_values={'b': '2'})])),
        (True, 'baseline key pass', ((('a', 1),), (('b', 2),)),
         config_pb2.CrossSlicingSpec(
             baseline_spec=config_pb2.SlicingSpec(feature_keys=['a']),
             slicing_specs=[config_pb2.SlicingSpec(feature_values={'b': '2'})])),
        (True, 'comparison key pass', ((('a', 1),), (('b', 2),)),
         config_pb2.CrossSlicingSpec(
             baseline_spec=config_pb2.SlicingSpec(feature_values={'a': '1'}),
             slicing_specs=[config_pb2.SlicingSpec(feature_keys=['b'])])),
        (True, 'comparison multiple key pass', ((('a', 1),), (('c', 3),)),
         config_pb2.CrossSlicingSpec(
             baseline_spec=config_pb2.SlicingSpec(feature_values={'a': '1'}),
             slicing_specs=[config_pb2.SlicingSpec(feature_keys=['b']),
                            config_pb2.SlicingSpec(feature_keys=['c'])])),
        (False, 'overall fail', ((('a', 1),), (('b', 2),)),
         config_pb2.CrossSlicingSpec(
             baseline_spec=config_pb2.SlicingSpec(),
             slicing_specs=[config_pb2.SlicingSpec(feature_values={'b': '2'})])),
        (False, 'value fail', ((('a', 1),), (('b', 3),)),
         config_pb2.CrossSlicingSpec(
             baseline_spec=config_pb2.SlicingSpec(feature_values={'a': '1'}),
             slicing_specs=[config_pb2.SlicingSpec(feature_values={'b': '2'})])),
        (False, 'baseline key fail', ((('c', 1),), (('b', 2),)),
         config_pb2.CrossSlicingSpec(
             baseline_spec=config_pb2.SlicingSpec(feature_keys=['a']),
             slicing_specs=[config_pb2.SlicingSpec(feature_values={'b': '2'})])),
        (False, 'comparison key fail', ((('a', 1),), (('c', 3),)),
         config_pb2.CrossSlicingSpec(
             baseline_spec=config_pb2.SlicingSpec(feature_values={'a': '1'}),
             slicing_specs=[config_pb2.SlicingSpec(feature_keys=['b'])])),
        (False, 'comparison multiple key fail', ((('a', 1),), (('d', 3),)),
         config_pb2.CrossSlicingSpec(
             baseline_spec=config_pb2.SlicingSpec(feature_values={'a': '1'}),
             slicing_specs=[config_pb2.SlicingSpec(feature_keys=['b']),
                            config_pb2.SlicingSpec(feature_keys=['c'])])),
    ]  # pyformat: disable
    for (expected_result, name, sliced_key, slicing_spec) in test_cases:
      self.assertEqual(
          expected_result,
          slicer.is_cross_slice_applicable(
              cross_slice_key=sliced_key, cross_slicing_spec=slicing_spec),
          msg=name)

  def testGetSliceKeyType(self):
    test_cases = [
        (slicer.SliceKeyType, 'overall', ()),
        (slicer.SliceKeyType, 'one bytes feature', (('a', '5'),)),
        (slicer.SliceKeyType, 'one int64 feature', (('a', 1),)),
        (slicer.SliceKeyType, 'mixed', (('a', 1), ('b', 'f'))),
        (slicer.SliceKeyType, 'more', (('a', 1), ('b', 'f'), ('c', 'cars'))),
        (slicer.SliceKeyType, 'unicode',
         (('a', b'\xe4\xb8\xad\xe6\x96\x87'),)),
        (slicer.CrossSliceKeyType, 'CrossSlice overall', ((), ())),
        (slicer.CrossSliceKeyType, 'CrossSlice one slice key baseline',
         ((('a', '5'),), ())),
        (slicer.CrossSliceKeyType, 'CrossSlice one slice key comparison',
         ((), (('a', 1),))),
        (slicer.CrossSliceKeyType, 'CrossSlice two simple slice key',
         ((('a', 1),), (('b', 'f'),))),
        (slicer.CrossSliceKeyType, 'CrossSlice two multiple slice key',
         ((('a', 1), ('b', 'f'), ('c', '11')),
          (('a2', 1), ('b', 'm'), ('c', '11')))),
    ]  # pyformat: disable
    for (expected_result, name, slice_key) in test_cases:
      self.assertEqual(
          expected_result, slicer.get_slice_key_type(slice_key), msg=name)

    unrecognized_test_cases = [
        ('Unrecognized 1: ', ('a')),
        ('Unrecognized 2: ', ('a',)),
        ('Unrecognized 3: ', ('a', 1)),
        ('Unrecognized 4: ', (('a'))),
        ('Unrecognized 5: ', (('a',))),
        ('Unrecognized 6: ', ((), (), ())),
        ('Unrecognized 7: ', ((('a', 1),), (('b', 1),), (('c', 1),))),
        ('Unrecognized 8: ', ((('a', 1),), ('b', 1))),
        ('Unrecognized 9: ', (('a', 1), (('b', 1),))),
    ]  # pyformat: disable
    for (name, slice_key) in unrecognized_test_cases:
      with self.assertRaises(TypeError, msg=name + str(slice_key)):
        slicer.get_slice_key_type(slice_key)

  @parameterized.named_parameters(
      {
          'testcase_name': '_single_slice_spec',
          'slice_type': slicer.SingleSliceSpec,
          'slicing_spec': config_pb2.SlicingSpec(feature_values={'a': '1'}),
      }, {
          'testcase_name':
              '_cross_slice_spec',
          'slice_type':
              slicer.CrossSliceSpec,
          'slicing_spec':
              config_pb2.CrossSlicingSpec(
                  baseline_spec=config_pb2.SlicingSpec(),
                  slicing_specs=[
                      config_pb2.SlicingSpec(feature_values={'b': '2'})
                  ]),
      })
  def testDeserializeSliceSpec(self, slice_type, slicing_spec):
    slice_spec = slicer.deserialize_slice_spec(slicing_spec)
    self.assertIsInstance(slice_spec, slice_type)

  def testDeserializeSliceSpec_hashable(self):
    single_slice_spec = slicer.deserialize_slice_spec(
        config_pb2.SlicingSpec(feature_values={'a': '1'}))
    cross_slice_spec = slicer.deserialize_slice_spec(
        slicer.config_pb2.CrossSlicingSpec(
            baseline_spec=config_pb2.SlicingSpec(),
            slicing_specs=[config_pb2.SlicingSpec(feature_values={'b': '2'})]))
    # Check either of them can be hashed and used as keys.
    slice_map = {single_slice_spec: 1, cross_slice_spec: 2}
    self.assertEqual(slice_map[single_slice_spec], 1)
    self.assertEqual(slice_map[cross_slice_spec], 2)

  def testIsSliceApplicable(self):
    test_cases = [
        ('applicable', ['column1'],
         [('column3', 'value3'), ('column4', 'value4')],
         (('column1', 'value1'), ('column3', 'value3'), ('column4', 'value4')),
         True),
        ('wrongcolumns', ['column1', 'column2'],
         [('column3', 'value3'), ('column4', 'value4')],
         (('column1', 'value1'), ('column3', 'value3'), ('column4', 'value4')),
         False),
        ('wrongfeatures', ['column1'], [('column3', 'value3')],
         (('column1', 'value1'), ('column3', 'value3'), ('column4', 'value4')),
         False),
        ('nocolumns', [], [('column3', 'value3')],
         (('column1', 'value1'), ('column3', 'value3'), ('column4', 'value4')),
         False),
        ('nofeatures', ['column1'], [], (('column1', 'value1'),), True),
        ('empty slice key', ['column1'], [('column2', 'value1')], (), False),
        ('overall', [], [], (), True)
    ]  # pyformat: disable

    for (name, columns, features, slice_key, result) in test_cases:
      slice_spec = slicer.SingleSliceSpec(columns=columns, features=features)
      self.assertEqual(
          slice_spec.is_slice_applicable(slice_key), result, msg=name)

  def testSliceDefaultSlice(self):
    with beam.Pipeline() as pipeline:
      fpls = create_fpls()

      metrics = (
          pipeline
          | 'CreateTestInput' >> beam.Create(fpls)
          | 'WrapFpls' >> beam.Map(wrap_fpl)
          | 'ExtractSlices' >> slice_key_extractor.ExtractSliceKeys(
              [slicer.SingleSliceSpec()])
          | 'FanoutSlices' >> slicer.FanoutSlices())

      def check_result(got):
        try:
          self.assertLen(got, 2)
          expected_result = [
              ((), wrap_fpl(fpls[0])),
              ((), wrap_fpl(fpls[1])),
          ]
          self.assertEqual(len(got), len(expected_result))
          self.assertTrue(
              got[0] == expected_result[0] and got[1] == expected_result[1] or
              got[1] == expected_result[0] and got[0] == expected_result[1])
        except AssertionError as err:
          raise util.BeamAssertException(err)

      util.assert_that(metrics, check_result)

  def testSliceOneSlice(self):
    with beam.Pipeline() as pipeline:
      fpls = create_fpls()
      metrics = (
          pipeline
          | 'CreateTestInput' >> beam.Create(fpls, reshuffle=False)
          | 'WrapFpls' >> beam.Map(wrap_fpl)
          | 'ExtractSlices' >> slice_key_extractor.ExtractSliceKeys([
              slicer.SingleSliceSpec(),
              slicer.SingleSliceSpec(columns=['gender'])
          ])
          | 'FanoutSlices' >> slicer.FanoutSlices())

      def check_result(got):
        try:
          self.assertLen(got, 4)
          expected_result = [
              ((), wrap_fpl(fpls[0])),
              ((), wrap_fpl(fpls[1])),
              ((('gender', 'f'),), wrap_fpl(fpls[0])),
              ((('gender', 'm'),), wrap_fpl(fpls[1])),
          ]
          self.assertCountEqual(got, expected_result)
        except AssertionError as err:
          raise util.BeamAssertException(err)

      util.assert_that(metrics, check_result)

  def testMultidimSlices(self):
    data = [{
        'features': {
            'gender': [['f'], ['f']],
            'age': [[13], [13]],
            'interest': [['cars'], ['cars']]
        },
        'predictions': [[1], [1]],
        'labels': [[0], [0]],
        constants.SLICE_KEY_TYPES_KEY:
            np.array([
                slicer.slice_keys_to_numpy_array([(), (('gender', 'f'),)]),
                slicer.slice_keys_to_numpy_array([(), (('gender', 'f'),)])
            ])
    }, {
        'features': {
            'gender': [['f'], ['m']],
            'age': [[13], [10]],
            'interest': [['cars'], ['cars']]
        },
        'predictions': [[1], [1]],
        'labels': [[0], [0]],
        constants.SLICE_KEY_TYPES_KEY:
            np.array([
                slicer.slice_keys_to_numpy_array([(), (('gender', 'f'),)]),
                slicer.slice_keys_to_numpy_array([(), (('gender', 'm'),)])
            ])
    }]

    with beam.Pipeline() as pipeline:
      result = (
          pipeline
          | 'CreateTestInput' >> beam.Create(data, reshuffle=False)
          | 'FanoutSlices' >> slicer.FanoutSlices())

      def check_result(got):
        try:
          self.assertLen(got, 5)
          del data[0][constants.SLICE_KEY_TYPES_KEY]
          del data[1][constants.SLICE_KEY_TYPES_KEY]
          expected_result = [
              ((), data[0]),
              ((), data[1]),
              ((('gender', 'f'),), data[0]),
              ((('gender', 'f'),), data[1]),
              ((('gender', 'm'),), data[1]),
          ]
          self.assertCountEqual(got, expected_result)
        except AssertionError as err:
          raise util.BeamAssertException(err)

      util.assert_that(result, check_result)

  def testMultidimOverallSlices(self):
    data = [
        {
            constants.SLICE_KEY_TYPES_KEY:  # variable length batch case
                types.VarLenTensorValue.from_dense_rows([
                    slicer.slice_keys_to_numpy_array([(('gender', 'f'),), ()]),
                    slicer.slice_keys_to_numpy_array([()])
                ])
        },
        {
            constants.SLICE_KEY_TYPES_KEY:  # fixed length batch case
                np.array([
                    slicer.slice_keys_to_numpy_array([()]),
                    slicer.slice_keys_to_numpy_array([()])
                ])
        }
    ]

    with beam.Pipeline() as pipeline:
      result = (
          pipeline
          | 'CreateTestInput' >> beam.Create(data, reshuffle=False)
          | 'FanoutSlices' >> slicer.FanoutSlices())

      def check_result(got):
        try:
          del data[0][constants.SLICE_KEY_TYPES_KEY]
          del data[1][constants.SLICE_KEY_TYPES_KEY]
          expected_result = [
              ((('gender', 'f'),), data[0]),
              ((), data[0]),
              ((), data[1]),
          ]
          self.assertCountEqual(got, expected_result)
        except AssertionError as err:
          raise util.BeamAssertException(err)

      util.assert_that(result, check_result)

  def testFilterOutSlices(self):
    slice_key_1 = (('slice_key', 'slice1'),)
    slice_key_2 = (('slice_key', 'slice2'),)
    slice_key_3 = (('slice_key', 'slice3'),)

    values_list = [(slice_key_1, {
        'val11': 'val12'
    }), (slice_key_2, {
        'val21': 'val22'
    })]
    slice_counts_list = [(slice_key_1, 2), (slice_key_2, 1), (slice_key_3, 0)]

    def check_output(got):
      try:
        self.assertLen(got, 2)
        slices = {}
        for (k, v) in got:
          slices[k] = v

        self.assertEqual(slices[slice_key_1], {'val11': 'val12'})
        self.assertIn(metric_keys.ERROR_METRIC, slices[slice_key_2])
      except AssertionError as err:
        raise util.BeamAssertException(err)

    with beam.Pipeline() as pipeline:
      slice_counts_pcoll = (
          pipeline | 'CreateSliceCountsPColl' >> beam.Create(slice_counts_list))
      output_dict = (
          pipeline
          | 'CreateValuesPColl' >> beam.Create(values_list)
          | 'FilterOutSlices' >> slicer.FilterOutSlices(
              slice_counts_pcoll,
              min_slice_size=2,
              error_metric_key=metric_keys.ERROR_METRIC))
      util.assert_that(output_dict, check_output)

  @parameterized.named_parameters(
      {
          'testcase_name': 'matching_single_spec',
          'slice_key': (('f1', 1),),
          'slice_specs': [slicer.SingleSliceSpec(features=[('f1', 1)])],
          'expected_result': True
      },
      {
          'testcase_name': 'matching_single_spec_with_float',
          'slice_key': (('f1', '1.0'),),
          'slice_specs': [slicer.SingleSliceSpec(features=[('f1', '1.0')])],
          'expected_result': True
      },
      {
          'testcase_name': 'non_matching_single_spec',
          'slice_key': (('f1', 1),),
          'slice_specs': [slicer.SingleSliceSpec(columns=['f2'])],
          'expected_result': False
      },
      {
          'testcase_name': 'matching_multiple_specs',
          'slice_key': (('f1', 1),),
          'slice_specs': [
              slicer.SingleSliceSpec(columns=['f1']),
              slicer.SingleSliceSpec(columns=['f2'])
          ],
          'expected_result': True
      },
      {
          'testcase_name': 'empty_specs',
          'slice_key': (('f1', 1),),
          'slice_specs': [],
          'expected_result': False
      },
  )
  def testSliceKeyMatchesSliceSpecs(self, slice_key, slice_specs,
                                    expected_result):
    self.assertEqual(
        expected_result,
        slicer.slice_key_matches_slice_specs(slice_key, slice_specs))

if __name__ == '__main__':
  tf.test.main()


text:
@interface DemoVC6 : BABaseViewController

- (void)reloadNotiView;

@end


text:
start:    mov eax, 2  # EAX is prime candidate

checkPrime: mov ebx, 2  # EBX is factor candidate

checkFactor:  cmp eax, ebx
    je primeFound

    mod eax, ebx
    rem ecx
    cmp ecx, 0
    je nextPrime

    inc ebx
    jmp checkFactor  # test comment

primeFound: prn eax

nextPrime:  inc eax
    cmp eax, 100
    jl checkPrime


text:
<?php

namespace frontend\controllers;

use Yii;
use app\models\BorangPenilaianKaunseling;
use frontend\models\BorangPenilaianKaunselingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

use app\models\general\GeneralVariable;

// table reference
use app\models\RefKategoriMasalahKaunseling;
use app\models\RefLatarbelakangKes;
use app\models\Atlet;
use app\models\Jurulatih;
use app\models\RefJenisKlien;

/**
 * BorangPenilaianKaunselingController implements the CRUD actions for BorangPenilaianKaunseling model.
 */
class BorangPenilaianKaunselingController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all BorangPenilaianKaunseling models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $searchModel = new BorangPenilaianKaunselingSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BorangPenilaianKaunseling model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = $this->findModel($id);

		$jenisKlienID = $model->jenis_klien;

        $ref = Atlet::findOne(['atlet_id' => $model->atlet]);
        $model->atlet = $ref['nameAndIC'];

		$ref = Jurulatih::findOne(['jurulatih_id' => $model->jurulatih]);
        $model->jurulatih = $ref['nama'];

        $ref = RefLatarbelakangKes::findOne(['id' => $model->kategori_permasalahan]);
        $model->kategori_permasalahan = $ref['desc'];

		$ref = RefJenisKlien::findOne(['id' => $model->jenis_klien]);
        $model->jenis_klien = $ref['desc'];

        return $this->render('view', [
            'model' => $model,
            'readonly' => true,
			'jenisKlienID' => $jenisKlienID,
        ]);
    }

    /**
     * Creates a new BorangPenilaianKaunseling model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = new BorangPenilaianKaunseling();

        $model->profil_konsultan_id =  Yii::$app->user->identity->id;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->borang_penilaian_kaunseling_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'readonly' => false,
            ]);
        }
    }

    /**
     * Updates an existing BorangPenilaianKaunseling model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = $this->findModel($id);
		$jenisKlienID = $model->jenis_klien;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->borang_penilaian_kaunseling_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'readonly' => false,
				'jenisKlienID' => $jenisKlienID,
            ]);
        }
    }

    /**
     * Deletes an existing BorangPenilaianKaunseling model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BorangPenilaianKaunseling model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return BorangPenilaianKaunseling the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BorangPenilaianKaunseling::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
You are welcome to fork this repository. We'd love getting pull requests. We work in master, so if it's committed there it's assumed that it's good to go live. We'll likely develop a more advanced branching strategy later.

## Environment Setup
 Here are some recommendations for setting up your environment so that the code you write smells like the main project.

* [editorconfig](http://editorconfig.org/) so we have the same spacing style
* [jshint](http://www.jshint.com/) for all files (we have a [.jshintrc](../.jshintrc), and lint is run on every commit with [travis](../.travis.yml))
* phantomjs - to automatically run all the qunit tests for you
    * Mac - `brew install phantomjs` is the easiest. [Alternatives](http://ariya.ofilabs.com/2012/02/phantomjs-and-mac-os-x.html)
    * *nix - [Download](http://phantomjs.org/download.html) or [Build from source](http://phantomjs.org/build.html)
* casperjs -
    * Mac - `brew install casperjs` [Additional instructions](http://casperjs.org/installation.html)

## Testing
We recommend [Test Driven Development](http://en.wikipedia.org/wiki/Test-driven_development) be used, and we aim for 100% coverage. If you use `grunt watch`, you can have it run the tests every time you write a file.

We use travis-ci for automagic testing on every commit. Current test status:

[![Build Status](https://secure.travis-ci.org/pilotfish/pilotfish.png)](http://travis-ci.org/pilotfish/pilotfish)

### Running Tests

* `grunt test` will run the qunit tests
* `grunt server casperjs` will run all the casperjs tests

## Deployment/Release
To release, the files are run through a set of checks and then copied to the [/dist/](../dist/) directory. The minified versions are also created, along with any building of CSS or images.

We tag them in git with `release/$version`, making it easy for folks to go to that point in history. For example, to see where it all started, check out the [0.1.0 version of Pilotfish](https://github.com/pilotfish/pilotfish/tree/release/0.1.0). Each plugin also has it's own version, and releases are tagged as `release/plugin/$plugin/$version`. [Full tag listing](https://github.com/pilotfish/pilotfish/tags)

Grunt tasks for release:

* `grunt release_core`
	1. `lint`, `test`, and other sanity checks
	1. minify (create [pilotfish.min.js](../pilotfish.min.js]))
	1. Generate documentation
	1. Copy pilotfish.js and pilotfish.min.js to:
		* /dist/latest/
		* /dist/$major/
		* /dist/$major/$minor
		* /dist/$major/$minor/$patch
	1. git add/commit files in /dist/
	1. git push with tags
* `grunt release_plugin[:$plugin]`
* `grunt release_cdn`. This is how files get to http://cdn.pilotfish.io/client/. Assumes that the [pilotfish.github.com](https://github.com/pilotfish/pilotfish.github.com) repo is checked out at in the same directory as this repo.
	1. Santy checks
	1. copy the files from dist to ../pilotfish.github.com/client/
	1. git add/commit
	1. git tag with current release.
	1. git push (with tags)

See `grunt --help` for more info.

## Coding Philosophy
In order to ensure high quality code, we ask that contributors follow some coding standards.

Our overarching principals are **simplicity, readability, and maintainability.**

This should be fun!

### Pedantic coding standards
Most of the suggestions below apply to Javascript in specific, since most of the project is written in javascript. For the most part, we follow the [jQuery Core Style Guidelines](http://docs.jquery.com/JQuery_Core_Style_Guidelines), but we'd like to call out the following additional points:

* Spaces, not tabs. 4 of them. Pro tip: Use an editor that supports [editorconfig](http://editorconfig.org/), and this will be handled for you.
* Minification is the computer's job, not yours. Use explicit variable names.
* Braces on the same line, or I am afraid this won't work out.
* Cleverness is seldom required. When it is, comment it.
* Be considerate of other contributors. Will someone who reads your code later understand what you've done?
* Names matter. Use names that make sense for clarity.
* Minimize the use of assumed globals, explicitly reference `window` when you need to.
* Always use semicolons;
* Always use braces, no one-line shortcuts.
* Triple equals where it is a good idea. Don't leave type to chance.

Have a suggestion? Fork this page and issue a pull request! :)

## External resources
Here are a few interesting resources:

* http://neil.rashbrook.org/JS.htm
* https://developer.mozilla.org/En/Mozilla_Coding_Style_Guide
* http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml
* https://developers.google.com/closure/compiler/docs/js-for-compiler
* http://substack.net/posts/b96642


text:
export MDCComponent from './MDCComponent'

export default from './MDCComponent'