text:
package org.sleuthkit.autopsy.report;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.event.ListDataListener;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.BlackboardArtifact;
import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
import org.sleuthkit.datamodel.TskCoreException;

public class ArtifactSelectionDialog extends javax.swing.JDialog {
    private static final Logger logger = Logger.getLogger(ArtifactSelectionDialog.class.getName());
    private static ArtifactSelectionDialog instance;
    private ArtifactModel model;
    private ArtifactRenderer renderer;

    private Map<BlackboardArtifact.ARTIFACT_TYPE, Boolean> artifactStates;
    private List<BlackboardArtifact.ARTIFACT_TYPE> artifacts;

    /**
     * Creates new form ArtifactSelectionDialog
     */
    public ArtifactSelectionDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        populateList();
        customInit();
    }

    /**
     * Populate the list of artifacts with all important artifacts.
     */
    private void populateList() {
        try {
            ArrayList<BlackboardArtifact.ARTIFACT_TYPE> doNotReport = new ArrayList<>();
            doNotReport.add(BlackboardArtifact.ARTIFACT_TYPE.TSK_GEN_INFO);

            artifacts = Case.getCurrentCase().getSleuthkitCase().getBlackboardArtifactTypesInUse();

            artifacts.removeAll(doNotReport);

            Collections.sort(artifacts, new Comparator<BlackboardArtifact.ARTIFACT_TYPE>() {
                @Override
                public int compare(ARTIFACT_TYPE o1, ARTIFACT_TYPE o2) {
                    return o1.getDisplayName().compareTo(o2.getDisplayName());
                }
            });

            artifactStates = new EnumMap<>(BlackboardArtifact.ARTIFACT_TYPE.class);
            for (BlackboardArtifact.ARTIFACT_TYPE type : artifacts) {
                artifactStates.put(type, Boolean.TRUE);
            }
        } catch (TskCoreException ex) {
            Logger.getLogger(ArtifactSelectionDialog.class.getName()).log(Level.SEVERE, "Error getting list of artifacts in use: " + ex.getLocalizedMessage());
            return;
        }
    }

    private void customInit() {
        model = new ArtifactModel();
        renderer = new ArtifactRenderer();
        artifactList.setModel(model);
        artifactList.setCellRenderer(renderer);
        artifactList.setVisibleRowCount(-1);

        artifactList.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent evt) {
                JList list = (JList) evt.getSource();
                int index = list.locationToIndex(evt.getPoint());
                BlackboardArtifact.ARTIFACT_TYPE type = model.getElementAt(index);
                artifactStates.put(type, !artifactStates.get(type));
                list.repaint();
            }
        });
    }

    /**
     * Returns a list of the artifact types we want to report on.
     */
    static List<ARTIFACT_TYPE> getImportantArtifactTypes() {
        List<ARTIFACT_TYPE> types = new ArrayList<ARTIFACT_TYPE>();
        types.add(ARTIFACT_TYPE.TSK_WEB_BOOKMARK);
        types.add(ARTIFACT_TYPE.TSK_WEB_COOKIE);
        types.add(ARTIFACT_TYPE.TSK_WEB_HISTORY);
        types.add(ARTIFACT_TYPE.TSK_WEB_DOWNLOAD);
        types.add(ARTIFACT_TYPE.TSK_RECENT_OBJECT);
        types.add(ARTIFACT_TYPE.TSK_INSTALLED_PROG);
        types.add(ARTIFACT_TYPE.TSK_KEYWORD_HIT);
        types.add(ARTIFACT_TYPE.TSK_HASHSET_HIT);
        types.add(ARTIFACT_TYPE.TSK_DEVICE_ATTACHED);
        types.add(ARTIFACT_TYPE.TSK_WEB_SEARCH_QUERY);
        types.add(ARTIFACT_TYPE.TSK_METADATA_EXIF);
        types.add(ARTIFACT_TYPE.TSK_TAG_FILE);
        types.add(ARTIFACT_TYPE.TSK_TAG_ARTIFACT);
        return types;
    }

    /**
     * Display this dialog, and return the selected artifacts.
     */
    Map<BlackboardArtifact.ARTIFACT_TYPE, Boolean> display() {
        this.setTitle("Advanced Artifact Selection");
        Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
        // set the popUp window / JFrame
        int w = this.getSize().width;
        int h = this.getSize().height;

        // set the location of the popUp Window on the center of the screen
        setLocation((screenDimension.width - w) / 2, (screenDimension.height - h) / 2);

        this.setVisible(true);
        return artifactStates;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        artifactScrollPane = new javax.swing.JScrollPane();
        artifactList = new javax.swing.JList<>();
        okButton = new javax.swing.JButton();
        titleLabel = new javax.swing.JLabel();
        selectAllButton = new javax.swing.JButton();
        deselectAllButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        artifactList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        artifactList.setLayoutOrientation(javax.swing.JList.HORIZONTAL_WRAP);
        artifactScrollPane.setViewportView(artifactList);

        org.openide.awt.Mnemonics.setLocalizedText(okButton, org.openide.util.NbBundle.getMessage(ArtifactSelectionDialog.class, "ArtifactSelectionDialog.okButton.text")); // NOI18N
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(titleLabel, org.openide.util.NbBundle.getMessage(ArtifactSelectionDialog.class, "ArtifactSelectionDialog.titleLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(selectAllButton, org.openide.util.NbBundle.getMessage(ArtifactSelectionDialog.class, "ArtifactSelectionDialog.selectAllButton.text")); // NOI18N
        selectAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectAllButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(deselectAllButton, org.openide.util.NbBundle.getMessage(ArtifactSelectionDialog.class, "ArtifactSelectionDialog.deselectAllButton.text")); // NOI18N
        deselectAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deselectAllButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(artifactScrollPane)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(deselectAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(selectAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(titleLabel)
                        .addGap(0, 221, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(okButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(titleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(artifactScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(selectAllButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(deselectAllButton)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(11, 11, 11)
                .addComponent(okButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        dispose();
    }//GEN-LAST:event_okButtonActionPerformed

    private void selectAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectAllButtonActionPerformed
        for (ARTIFACT_TYPE type : artifacts) {
            artifactStates.put(type, Boolean.TRUE);
        }
        artifactList.repaint();
    }//GEN-LAST:event_selectAllButtonActionPerformed

    private void deselectAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deselectAllButtonActionPerformed
        for (ARTIFACT_TYPE type : artifacts) {
            artifactStates.put(type, Boolean.FALSE);
        }
        artifactList.repaint();
    }//GEN-LAST:event_deselectAllButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList<ARTIFACT_TYPE> artifactList;
    private javax.swing.JScrollPane artifactScrollPane;
    private javax.swing.JButton deselectAllButton;
    private javax.swing.JButton okButton;
    private javax.swing.JButton selectAllButton;
    private javax.swing.JLabel titleLabel;
    // End of variables declaration//GEN-END:variables

    private class ArtifactModel implements ListModel<ARTIFACT_TYPE> {

        @Override
        public int getSize() {
            return artifacts.size();
        }

        @Override
        public ARTIFACT_TYPE getElementAt(int index) {
            return artifacts.get(index);
        }

        @Override
        public void addListDataListener(ListDataListener l) {
        }

        @Override
        public void removeListDataListener(ListDataListener l) {
        }
    }

    private class ArtifactRenderer extends JCheckBox implements ListCellRenderer<BlackboardArtifact.ARTIFACT_TYPE> {

        @Override
        public Component getListCellRendererComponent(JList<? extends ARTIFACT_TYPE> list, ARTIFACT_TYPE value, int index, boolean isSelected, boolean cellHasFocus) {
            if (value != null) {
                setEnabled(list.isEnabled());
                setSelected(artifactStates.get(value));
                setFont(list.getFont());
                setBackground(list.getBackground());
                setForeground(list.getForeground());
                setText(value.getDisplayName());
                return this;
            }
            return new JLabel();
        }

    }

}


text:
package persistence.simple.spring;

import org.hamcrest.core.StringContains;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import persistence.simple.spring.model.Settings;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayOutputStream;
import java.io.StringReader;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:serialization.xml")
public class SettingsOxmSerializationTest {

    private Settings settings;

    @Autowired
    private Marshaller marshaller;

    @Autowired
    private Unmarshaller unmarshaller;

    @Before
    public void setUp() throws Exception {
        settings = new Settings();
        settings.setMessage("Hello OXM");
        settings.setFooEnabled(true);
    }

    @Test
    public void testMarshallSettings() throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        marshaller.marshal(settings, new StreamResult(bos));

        String result = bos.toString("UTF-8");
        System.out.println(result);

        assertThat(result, StringContains.containsString("<?xml"));
        assertThat(result, StringContains.containsString("<message>Hello OXM</message>"));
    }

    @Test
    public void testUnmarshallSettings() throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
                "<settings>" +
                "<fooEnabled>true</fooEnabled>" +
                "<message>Hello OXM</message>" +
                "<message1>Hello OXM</message1>" +
                "</settings>";

        Settings result = (Settings) unmarshaller.unmarshal(new StreamSource(new StringReader(xml)));

        assertThat(result.getMessage(), is("Hello OXM"));
        assertThat(result.isFooEnabled(), is(true));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class Google_Service_CloudComposer_ComposerEmpty extends Google_Model
{
}


text:
import app from "../../../app";
import FauxtonAPI from "../../../core/api";
import ActionTypes from "./header.actiontypes";
import ActionsQueryOptions from "../queryoptions/actions";

export default {

  toggleIncludeDocs: function (state, bulkDocsCollection) {
    var params = app.getParams();

    if (state) {
      delete params.include_docs;
      delete params.conflicts;
    } else {
      params.include_docs = true;
      params.conflicts = true;
    }

    app.utils.localStorageSet('include_docs_bulkdocs', bulkDocsCollection.toJSON());

    ActionsQueryOptions.runQuery(params);
  },

  toggleTableView: function (state) {
    FauxtonAPI.dispatch({
      type: ActionTypes.TOGGLE_TABLEVIEW,
      options: {
        enable: state
      }
    });
  }

};


text:
import endpoint from './model/endpoint';
import fetchBackend from './http/fetch';
import http from './service/http';
import { member } from './model/decorator';
import requestBackend from './http/request';
import scope from './model/scope';

const instances = [];

function restful(baseUrl, httpBackend) {
    const rootScope = scope();
    rootScope.assign('config', 'entityIdentifier', 'id');
    if (!baseUrl && typeof(window) !== 'undefined' && window.location) {
        rootScope.set('url', `${window.location.protocol}//${window.location.host}`);
    } else {
        rootScope.set('url', baseUrl);
    }

    const rootEndpoint = member(endpoint(http(httpBackend))(rootScope));

    instances.push(rootEndpoint);

    return rootEndpoint;
}

restful._instances = () => instances;
restful._flush = () => instances.length = 0;

export { fetchBackend, requestBackend };
export default restful;


text:
require_relative '../models/unpaid_ratio'

require_relative '../modules/market'
require_relative '../modules/area'
require_relative '../modules/use'
require_relative '../modules/scope'
require_relative '../modules/sheet_names'
require 'date'
include Market
include Area
include Use
include Scope
include SheetNames


text:
"""OriginalityReports API Version 1.0.

This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from .base import BaseCanvasAPI
from .base import BaseModel

class OriginalityReportsAPI(BaseCanvasAPI):
    """OriginalityReports API Version 1.0."""

    def __init__(self, *args, **kwargs):
        """Init method for OriginalityReportsAPI."""
        super(OriginalityReportsAPI, self).__init__(*args, **kwargs)
        self.logger = logging.getLogger("py3canvas.OriginalityReportsAPI")

    def create_originality_report(
        self,
        assignment_id,
        originality_report_originality_score,
        submission_id,
        originality_report_attempt=None,
        originality_report_error_message=None,
        originality_report_file_id=None,
        originality_report_originality_report_file_id=None,
        originality_report_originality_report_url=None,
        originality_report_tool_setting_resource_type_code=None,
        originality_report_tool_setting_resource_url=None,
        originality_report_workflow_state=None,
    ):
        """
        Create an Originality Report.

        Create a new OriginalityReport for the specified file
        """
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - assignment_id
        """
            ID
        """
        path["assignment_id"] = assignment_id

        # REQUIRED - PATH - submission_id
        """
            ID
        """
        path["submission_id"] = submission_id

        # OPTIONAL - originality_report[file_id]
        """
            The id of the file being given an originality score. Required
        if creating a report associated with a file.
        """
        if originality_report_file_id is not None:
            data["originality_report[file_id]"] = originality_report_file_id

        # REQUIRED - originality_report[originality_score]
        """
            A number between 0 and 100 representing the measure of the
        specified file's originality.
        """
        data[
            "originality_report[originality_score]"
        ] = originality_report_originality_score

        # OPTIONAL - originality_report[originality_report_url]
        """
            The URL where the originality report for the specified
        file may be found.
        """
        if originality_report_originality_report_url is not None:
            data[
                "originality_report[originality_report_url]"
            ] = originality_report_originality_report_url

        # OPTIONAL - originality_report[originality_report_file_id]
        """
            The ID of the file within Canvas that contains the originality
        report for the submitted file provided in the request URL.
        """
        if originality_report_originality_report_file_id is not None:
            data[
                "originality_report[originality_report_file_id]"
            ] = originality_report_originality_report_file_id

        # OPTIONAL - originality_report[tool_setting][resource_type_code]
        """
            The resource type code of the resource handler Canvas should use for the
        LTI launch for viewing originality reports. If set Canvas will launch
        to the message with type 'basic-lti-launch-request' in the specified
        resource handler rather than using the originality_report_url.
        """
        if originality_report_tool_setting_resource_type_code is not None:
            data[
                "originality_report[tool_setting][resource_type_code]"
            ] = originality_report_tool_setting_resource_type_code

        # OPTIONAL - originality_report[tool_setting][resource_url]
        """
            The URL Canvas should launch to when showing an LTI originality report.
        Note that this value is inferred from the specified resource handler's
        message "path" value (See `resource_type_code`) unless
        it is specified. If this parameter is used a `resource_type_code`
        must also be specified.
        """
        if originality_report_tool_setting_resource_url is not None:
            data[
                "originality_report[tool_setting][resource_url]"
            ] = originality_report_tool_setting_resource_url

        # OPTIONAL - originality_report[workflow_state]
        """
            May be set to "pending", "error", or "scored". If an originality score
        is provided a workflow state of "scored" will be inferred.
        """
        if originality_report_workflow_state is not None:
            data[
                "originality_report[workflow_state]"
            ] = originality_report_workflow_state

        # OPTIONAL - originality_report[error_message]
        """
            A message describing the error. If set, the "workflow_state"
        will be set to "error."
        """
        if originality_report_error_message is not None:
            data["originality_report[error_message]"] = originality_report_error_message

        # OPTIONAL - originality_report[attempt]
        """
            If no `file_id` is given, and no file is required for the assignment
        (that is, the assignment allows an online text entry), this parameter
        may be given to clarify which attempt number the report is for (in the
        case of resubmissions). If this field is omitted and no `file_id` is
        given, the report will be created (or updated, if it exists) for the
        first submission attempt with no associated file.
        """
        if originality_report_attempt is not None:
            data["originality_report[attempt]"] = originality_report_attempt

        self.logger.debug(
            "POST /api/lti/assignments/{assignment_id}/submissions/{submission_id}/originality_report with query params: {params} and form data: {data}".format(
                params=params, data=data, **path
            )
        )
        return self.generic_request(
            "POST",
            "/api/lti/assignments/{assignment_id}/submissions/{submission_id}/originality_report".format(
                **path
            ),
            data=data,
            params=params,
            single_item=True,
        )

    def edit_originality_report_submissions(
        self,
        assignment_id,
        id,
        submission_id,
        originality_report_error_message=None,
        originality_report_originality_report_file_id=None,
        originality_report_originality_report_url=None,
        originality_report_originality_score=None,
        originality_report_tool_setting_resource_type_code=None,
        originality_report_tool_setting_resource_url=None,
        originality_report_workflow_state=None,
    ):
        """
        Edit an Originality Report.

        Modify an existing originality report. An alternative to this endpoint is
        to POST the same parameters listed below to the CREATE endpoint.
        """
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - assignment_id
        """
            ID
        """
        path["assignment_id"] = assignment_id

        # REQUIRED - PATH - submission_id
        """
            ID
        """
        path["submission_id"] = submission_id

        # REQUIRED - PATH - id
        """
            ID
        """
        path["id"] = id

        # OPTIONAL - originality_report[originality_score]
        """
            A number between 0 and 100 representing the measure of the
        specified file's originality.
        """
        if originality_report_originality_score is not None:
            data[
                "originality_report[originality_score]"
            ] = originality_report_originality_score

        # OPTIONAL - originality_report[originality_report_url]
        """
            The URL where the originality report for the specified
        file may be found.
        """
        if originality_report_originality_report_url is not None:
            data[
                "originality_report[originality_report_url]"
            ] = originality_report_originality_report_url

        # OPTIONAL - originality_report[originality_report_file_id]
        """
            The ID of the file within Canvas that contains the originality
        report for the submitted file provided in the request URL.
        """
        if originality_report_originality_report_file_id is not None:
            data[
                "originality_report[originality_report_file_id]"
            ] = originality_report_originality_report_file_id

        # OPTIONAL - originality_report[tool_setting][resource_type_code]
        """
            The resource type code of the resource handler Canvas should use for the
        LTI launch for viewing originality reports. If set Canvas will launch
        to the message with type 'basic-lti-launch-request' in the specified
        resource handler rather than using the originality_report_url.
        """
        if originality_report_tool_setting_resource_type_code is not None:
            data[
                "originality_report[tool_setting][resource_type_code]"
            ] = originality_report_tool_setting_resource_type_code

        # OPTIONAL - originality_report[tool_setting][resource_url]
        """
            The URL Canvas should launch to when showing an LTI originality report.
        Note that this value is inferred from the specified resource handler's
        message "path" value (See `resource_type_code`) unless
        it is specified. If this parameter is used a `resource_type_code`
        must also be specified.
        """
        if originality_report_tool_setting_resource_url is not None:
            data[
                "originality_report[tool_setting][resource_url]"
            ] = originality_report_tool_setting_resource_url

        # OPTIONAL - originality_report[workflow_state]
        """
            May be set to "pending", "error", or "scored". If an originality score
        is provided a workflow state of "scored" will be inferred.
        """
        if originality_report_workflow_state is not None:
            data[
                "originality_report[workflow_state]"
            ] = originality_report_workflow_state

        # OPTIONAL - originality_report[error_message]
        """
            A message describing the error. If set, the "workflow_state"
        will be set to "error."
        """
        if originality_report_error_message is not None:
            data["originality_report[error_message]"] = originality_report_error_message

        self.logger.debug(
            "PUT /api/lti/assignments/{assignment_id}/submissions/{submission_id}/originality_report/{id} with query params: {params} and form data: {data}".format(
                params=params, data=data, **path
            )
        )
        return self.generic_request(
            "PUT",
            "/api/lti/assignments/{assignment_id}/submissions/{submission_id}/originality_report/{id}".format(
                **path
            ),
            data=data,
            params=params,
            single_item=True,
        )

    def edit_originality_report_files(
        self,
        assignment_id,
        file_id,
        originality_report_error_message=None,
        originality_report_originality_report_file_id=None,
        originality_report_originality_report_url=None,
        originality_report_originality_score=None,
        originality_report_tool_setting_resource_type_code=None,
        originality_report_tool_setting_resource_url=None,
        originality_report_workflow_state=None,
    ):
        """
        Edit an Originality Report.

        Modify an existing originality report. An alternative to this endpoint is
        to POST the same parameters listed below to the CREATE endpoint.
        """
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - assignment_id
        """
            ID
        """
        path["assignment_id"] = assignment_id

        # REQUIRED - PATH - file_id
        """
            ID
        """
        path["file_id"] = file_id

        # OPTIONAL - originality_report[originality_score]
        """
            A number between 0 and 100 representing the measure of the
        specified file's originality.
        """
        if originality_report_originality_score is not None:
            data[
                "originality_report[originality_score]"
            ] = originality_report_originality_score

        # OPTIONAL - originality_report[originality_report_url]
        """
            The URL where the originality report for the specified
        file may be found.
        """
        if originality_report_originality_report_url is not None:
            data[
                "originality_report[originality_report_url]"
            ] = originality_report_originality_report_url

        # OPTIONAL - originality_report[originality_report_file_id]
        """
            The ID of the file within Canvas that contains the originality
        report for the submitted file provided in the request URL.
        """
        if originality_report_originality_report_file_id is not None:
            data[
                "originality_report[originality_report_file_id]"
            ] = originality_report_originality_report_file_id

        # OPTIONAL - originality_report[tool_setting][resource_type_code]
        """
            The resource type code of the resource handler Canvas should use for the
        LTI launch for viewing originality reports. If set Canvas will launch
        to the message with type 'basic-lti-launch-request' in the specified
        resource handler rather than using the originality_report_url.
        """
        if originality_report_tool_setting_resource_type_code is not None:
            data[
                "originality_report[tool_setting][resource_type_code]"
            ] = originality_report_tool_setting_resource_type_code

        # OPTIONAL - originality_report[tool_setting][resource_url]
        """
            The URL Canvas should launch to when showing an LTI originality report.
        Note that this value is inferred from the specified resource handler's
        message "path" value (See `resource_type_code`) unless
        it is specified. If this parameter is used a `resource_type_code`
        must also be specified.
        """
        if originality_report_tool_setting_resource_url is not None:
            data[
                "originality_report[tool_setting][resource_url]"
            ] = originality_report_tool_setting_resource_url

        # OPTIONAL - originality_report[workflow_state]
        """
            May be set to "pending", "error", or "scored". If an originality score
        is provided a workflow state of "scored" will be inferred.
        """
        if originality_report_workflow_state is not None:
            data[
                "originality_report[workflow_state]"
            ] = originality_report_workflow_state

        # OPTIONAL - originality_report[error_message]
        """
            A message describing the error. If set, the "workflow_state"
        will be set to "error."
        """
        if originality_report_error_message is not None:
            data["originality_report[error_message]"] = originality_report_error_message

        self.logger.debug(
            "PUT /api/lti/assignments/{assignment_id}/files/{file_id}/originality_report with query params: {params} and form data: {data}".format(
                params=params, data=data, **path
            )
        )
        return self.generic_request(
            "PUT",
            "/api/lti/assignments/{assignment_id}/files/{file_id}/originality_report".format(
                **path
            ),
            data=data,
            params=params,
            single_item=True,
        )

    def show_originality_report_submissions(self, assignment_id, id, submission_id):
        """
        Show an Originality Report.

        Get a single originality report
        """
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - assignment_id
        """
            ID
        """
        path["assignment_id"] = assignment_id

        # REQUIRED - PATH - submission_id
        """
            ID
        """
        path["submission_id"] = submission_id

        # REQUIRED - PATH - id
        """
            ID
        """
        path["id"] = id

        self.logger.debug(
            "GET /api/lti/assignments/{assignment_id}/submissions/{submission_id}/originality_report/{id} with query params: {params} and form data: {data}".format(
                params=params, data=data, **path
            )
        )
        return self.generic_request(
            "GET",
            "/api/lti/assignments/{assignment_id}/submissions/{submission_id}/originality_report/{id}".format(
                **path
            ),
            data=data,
            params=params,
            single_item=True,
        )

    def show_originality_report_files(self, assignment_id, file_id):
        """
        Show an Originality Report.

        Get a single originality report
        """
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - assignment_id
        """
            ID
        """
        path["assignment_id"] = assignment_id

        # REQUIRED - PATH - file_id
        """
            ID
        """
        path["file_id"] = file_id

        self.logger.debug(
            "GET /api/lti/assignments/{assignment_id}/files/{file_id}/originality_report with query params: {params} and form data: {data}".format(
                params=params, data=data, **path
            )
        )
        return self.generic_request(
            "GET",
            "/api/lti/assignments/{assignment_id}/files/{file_id}/originality_report".format(
                **path
            ),
            data=data,
            params=params,
            single_item=True,
        )

class Toolsetting(BaseModel):
    """Toolsetting Model."""

    def __init__(self, resource_type_code=None, resource_url=None):
        """Init method for Toolsetting class."""
        self._resource_type_code = resource_type_code
        self._resource_url = resource_url

        self.logger = logging.getLogger("py3canvas.Toolsetting")

    @property
    def resource_type_code(self):
        """the resource type code of the resource handler to use to display originality reports."""
        return self._resource_type_code

    @resource_type_code.setter
    def resource_type_code(self, value):
        """Setter for resource_type_code property."""
        self.logger.warn(
            "Setting values on resource_type_code will NOT update the remote Canvas instance."
        )
        self._resource_type_code = value

    @property
    def resource_url(self):
        """a URL that may be used to override the launch URL inferred by the specified resource_type_code. If used a 'resource_type_code' must also be specified."""
        return self._resource_url

    @resource_url.setter
    def resource_url(self, value):
        """Setter for resource_url property."""
        self.logger.warn(
            "Setting values on resource_url will NOT update the remote Canvas instance."
        )
        self._resource_url = value

class Originalityreport(BaseModel):
    """Originalityreport Model."""

    def __init__(
        self,
        id=None,
        file_id=None,
        originality_score=None,
        originality_report_file_id=None,
        originality_report_url=None,
        tool_setting=None,
        error_report=None,
        submission_time=None,
        root_account_id=None,
    ):
        """Init method for Originalityreport class."""
        self._id = id
        self._file_id = file_id
        self._originality_score = originality_score
        self._originality_report_file_id = originality_report_file_id
        self._originality_report_url = originality_report_url
        self._tool_setting = tool_setting
        self._error_report = error_report
        self._submission_time = submission_time
        self._root_account_id = root_account_id

        self.logger = logging.getLogger("py3canvas.Originalityreport")

    @property
    def id(self):
        """The id of the OriginalityReport."""
        return self._id

    @id.setter
    def id(self, value):
        """Setter for id property."""
        self.logger.warn(
            "Setting values on id will NOT update the remote Canvas instance."
        )
        self._id = value

    @property
    def file_id(self):
        """The id of the file receiving the originality score."""
        return self._file_id

    @file_id.setter
    def file_id(self, value):
        """Setter for file_id property."""
        self.logger.warn(
            "Setting values on file_id will NOT update the remote Canvas instance."
        )
        self._file_id = value

    @property
    def originality_score(self):
        """A number between 0 and 100 representing the originality score."""
        return self._originality_score

    @originality_score.setter
    def originality_score(self, value):
        """Setter for originality_score property."""
        self.logger.warn(
            "Setting values on originality_score will NOT update the remote Canvas instance."
        )
        self._originality_score = value

    @property
    def originality_report_file_id(self):
        """The ID of the file within Canvas containing the originality report document (if provided)."""
        return self._originality_report_file_id

    @originality_report_file_id.setter
    def originality_report_file_id(self, value):
        """Setter for originality_report_file_id property."""
        self.logger.warn(
            "Setting values on originality_report_file_id will NOT update the remote Canvas instance."
        )
        self._originality_report_file_id = value

    @property
    def originality_report_url(self):
        """A non-LTI launch URL where the originality score of the file may be found."""
        return self._originality_report_url

    @originality_report_url.setter
    def originality_report_url(self, value):
        """Setter for originality_report_url property."""
        self.logger.warn(
            "Setting values on originality_report_url will NOT update the remote Canvas instance."
        )
        self._originality_report_url = value

    @property
    def tool_setting(self):
        """A ToolSetting object containing optional 'resource_type_code' and 'resource_url'."""
        return self._tool_setting

    @tool_setting.setter
    def tool_setting(self, value):
        """Setter for tool_setting property."""
        self.logger.warn(
            "Setting values on tool_setting will NOT update the remote Canvas instance."
        )
        self._tool_setting = value

    @property
    def error_report(self):
        """A message describing the error. If set, the workflow_state will become 'error.'."""
        return self._error_report

    @error_report.setter
    def error_report(self, value):
        """Setter for error_report property."""
        self.logger.warn(
            "Setting values on error_report will NOT update the remote Canvas instance."
        )
        self._error_report = value

    @property
    def submission_time(self):
        """The submitted_at date time of the submission."""
        return self._submission_time

    @submission_time.setter
    def submission_time(self, value):
        """Setter for submission_time property."""
        self.logger.warn(
            "Setting values on submission_time will NOT update the remote Canvas instance."
        )
        self._submission_time = value

    @property
    def root_account_id(self):
        """The id of the root Account associated with the OriginalityReport."""
        return self._root_account_id

    @root_account_id.setter
    def root_account_id(self, value):
        """Setter for root_account_id property."""
        self.logger.warn(
            "Setting values on root_account_id will NOT update the remote Canvas instance."
        )
        self._root_account_id = value


text:
from org.robotframework import RobotRunner
from robotide.lib.robot import run_cli, rebot_cli
from robotide.lib.robot.libdoc import libdoc_cli
from robotide.lib.robot.tidy import tidy_cli
from robotide.lib.robot.testdoc import testdoc_cli

USAGE = """robotframework.jar - Robot Framework runner.

Usage: java -jar robotframework.jar [command] [options] [input(s)]

Available commands:
  run     - Run Robot Framework tests. The default, if no command is given.
  rebot   - Post process Robot Framework output files.
  libdoc  - Create test library or resource file documentation.
  tidy    - Clean-up and changed format of test data files.
  testdoc - Create documentation from Robot Framework test data files.

Run `java -jar robotframework.jar command --help` for more information about
an individual command.

Examples:
  java -jar robotframework.jar mytests.txt
  java -jar robotframework.jar run mytests.txt
  java -jar robotframework.jar rebot --log mylog.html out.xml
  java -jar robotframework.jar tidy --format txt mytests.html
"""

class JarRunner(RobotRunner):
    """Used for Java-Jython interop when RF is executed from .jar file"""
    _commands = {'run': run_cli, 'rebot': rebot_cli, 'tidy': tidy_cli,
                 'libdoc': libdoc_cli, 'testdoc': testdoc_cli}

    def run(self, args):
        try:
            self._run(args)
        except SystemExit as err:
            return err.code

    def _run(self, args):
        if not args or args[0] in ('-h', '--help'):
            print USAGE
            raise SystemExit(0)
        command, args = self._parse_command_line(args)
        command(args) # Always calls sys.exit()

    def _parse_command_line(self, args):
        try:
            return self._commands[args[0]], args[1:]
        except KeyError:
            return run_cli, args


text:
"""
Provides an asynchronous, crypto and compression aware socket for connecting to
servers and processing incoming packet data.
Coordinates with the Timers plugin to honor wall-clock timers
"""

import logging
import select
import socket
import time

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import ciphers
from cryptography.hazmat.primitives.ciphers import algorithms, modes

from spock import utils
from spock.mcp import mcdata, mcpacket
from spock.plugins.base import PluginBase
from spock.utils import pl_announce

logger = logging.getLogger('spock')
backend = default_backend()

class AESCipher(object):
    def __init__(self, shared_secret):
        cipher = ciphers.Cipher(algorithms.AES(shared_secret),
                                modes.CFB8(shared_secret), backend)
        # Name courtesy of dx
        self.encryptifier = cipher.encryptor()
        self.decryptifier = cipher.decryptor()

    def encrypt(self, data):
        return self.encryptifier.update(data)

    def decrypt(self, data):
        return self.decryptifier.update(data)

class SelectSocket(socket.socket):
    """
    Provides an asynchronous socket with a poll method built on
    top of select.select for cross-platform compatiability
    """
    def __init__(self, timer):
        super(SelectSocket, self).__init__(socket.AF_INET, socket.SOCK_STREAM)
        self.sending = False
        self.timer = timer

    def poll(self):
        flags = []
        if self.sending:
            self.sending = False
            slist = [(self,), (self,), (self,)]
        else:
            slist = [(self,), (), (self,)]
        timeout = self.timer.get_timeout()
        if timeout >= 0:
            slist.append(timeout)
        try:
            rlist, wlist, xlist = select.select(*slist)
        except select.error as e:
            logger.error("SELECTSOCKET: Socket Error: %s", str(e))
            rlist, wlist, xlist = [], [], []
        if rlist:
            flags.append('SOCKET_RECV')
        if wlist:
            flags.append('SOCKET_SEND')
        if xlist:
            flags.append('SOCKET_ERR')
        return flags

class NetCore(object):
    def __init__(self, sock, event):
        self.sock = sock
        self.event = event
        self.host = None
        self.port = None
        self.connected = False
        self.encrypted = False
        self.proto_state = mcdata.HANDSHAKE_STATE
        self.comp_state = mcdata.PROTO_COMP_OFF
        self.comp_threshold = -1
        self.sbuff = b''
        self.rbuff = utils.BoundBuffer()

    def connect(self, host='localhost', port=25565):
        self.host = host
        self.port = port
        try:
            logger.info("NETCORE: Attempting to connect to host: %s port: %s",
                        host, port)
            # Set the connect to be a blocking operation
            self.sock.setblocking(True)
            self.sock.connect((self.host, self.port))
            self.sock.setblocking(False)
            self.connected = True
            self.event.emit('connect', (self.host, self.port))
            logger.info("NETCORE: Connected to host: %s port: %s", host, port)
        except socket.error as error:
            logger.error("NETCORE: Error on Connect: %s", str(error))

    def set_proto_state(self, state):
        self.proto_state = state
        self.event.emit(mcdata.state_lookup[state] + '_STATE')

    def set_comp_state(self, threshold):
        self.comp_threshold = threshold
        if threshold >= 0:
            self.comp_state = mcdata.PROTO_COMP_ON

    def push(self, packet):
        data = packet.encode(self.comp_state, self.comp_threshold)
        self.sbuff += (self.cipher.encrypt(data) if self.encrypted else data)
        self.event.emit(packet.ident, packet)
        self.event.emit(packet.str_ident, packet)
        self.sock.sending = True

    def push_packet(self, ident, data):
        self.push(mcpacket.Packet(ident, data))

    def read_packet(self, data=b''):
        self.rbuff.append(
            self.cipher.decrypt(data) if self.encrypted else data)
        while self.rbuff:
            self.rbuff.save()
            try:
                packet = mcpacket.Packet(ident=(
                    self.proto_state,
                    mcdata.SERVER_TO_CLIENT
                )).decode(self.rbuff, self.comp_state)
            except utils.BufferUnderflowException:
                self.rbuff.revert()
                break
            except mcpacket.PacketDecodeFailure as err:
                logger.warning('NETCORE: Packet decode failed')
                logger.warning(
                    'NETCORE: Failed packet ident is probably: %s',
                    err.packet.str_ident
                )
                self.event.emit('PACKET_ERR', err)
                break
            self.event.emit(packet.ident, packet)
            self.event.emit(packet.str_ident, packet)

    def enable_crypto(self, secret_key):
        self.cipher = AESCipher(secret_key)
        self.encrypted = True

    def disable_crypto(self):
        self.cipher = None
        self.encrypted = False

    def reset(self, sock):
        self.__init__(sock, self.event)

@pl_announce('Net')
class NetPlugin(PluginBase):
    requires = ('Event', 'Timers')
    defaults = {
        'bufsize': 4096,
        'sock_quit': True,
    }
    events = {
        'event_tick': 'tick',
        'SOCKET_RECV': 'handle_recv',
        'SOCKET_SEND': 'handle_send',
        'SOCKET_ERR': 'handle_err',
        'SOCKET_HUP': 'handle_hup',
        'PLAY<Disconnect': 'handle_disconnect',
        'HANDSHAKE>Handshake': 'handle_handshake',
        'LOGIN<Login Success': 'handle_login_success',
        'LOGIN<Set Compression': 'handle_comp',
        'PLAY<Set Compression': 'handle_comp',
        'kill': 'handle_kill',
    }

    def __init__(self, ploader, settings):
        super(NetPlugin, self).__init__(ploader, settings)
        self.bufsize = self.settings['bufsize']
        self.sock_quit = self.settings['sock_quit']
        self.sock = SelectSocket(self.timers)
        self.net = NetCore(self.sock, self.event)
        self.sock_dead = False
        ploader.provides('Net', self.net)

    def tick(self, name, data):
        if self.net.connected:
            for flag in self.sock.poll():
                self.event.emit(flag)
        else:
            timeout = self.timers.get_timeout()
            if timeout == -1:
                time.sleep(1)
            else:
                time.sleep(timeout)

    # SOCKET_RECV - Socket is ready to recieve data
    def handle_recv(self, name, data):
        if self.net.connected:
            try:
                data = self.sock.recv(self.bufsize)
                if not data:
                    self.event.emit('SOCKET_HUP')
                    return
                self.net.read_packet(data)
            except socket.error as error:
                self.event.emit('SOCKET_ERR', error)

    # SOCKET_SEND - Socket is ready to send data and Send buffer contains
    # data to send
    def handle_send(self, name, data):
        if self.net.connected:
            try:
                sent = self.sock.send(self.net.sbuff)
                self.net.sbuff = self.net.sbuff[sent:]
                if self.net.sbuff:
                    self.sock.sending = True
            except socket.error as error:
                logger.error(str(error))
                self.event.emit('SOCKET_ERR', error)

    # SOCKET_ERR - Socket Error has occured
    def handle_err(self, name, data):
        self.sock.close()
        self.sock = SelectSocket(self.timers)
        self.net.reset(self.sock)
        logger.error("NETPLUGIN: Socket Error: %s", data)
        self.event.emit('disconnect', data)
        if self.sock_quit and not self.event.kill_event:
            self.sock_dead = True
            self.event.kill()

    # SOCKET_HUP - Socket has hung up
    def handle_hup(self, name, data):
        self.sock.close()
        self.sock = SelectSocket(self.timers)
        self.net.reset(self.sock)
        logger.error("NETPLUGIN: Socket has hung up")
        self.event.emit('disconnect', "Socket Hung Up")
        if self.sock_quit and not self.event.kill_event:
            self.sock_dead = True
            self.event.kill()

    # Handshake - Change to whatever the next state is going to be
    def handle_handshake(self, name, packet):
        self.net.set_proto_state(packet.data['next_state'])

    # Login Success - Change to Play state
    def handle_login_success(self, name, packet):
        self.net.set_proto_state(mcdata.PLAY_STATE)

    # Handle Set Compression packets
    def handle_comp(self, name, packet):
        self.net.set_comp_state(packet.data['threshold'])

    def handle_disconnect(self, name, packet):
        logger.info("NETPLUGIN: Disconnected: %s", packet.data['reason'])
        self.event.emit('disconnect', packet.data['reason'])

    # Kill event - Try to shutdown the socket politely
    def handle_kill(self, name, data):
        logger.info("NETPLUGIN: Kill event recieved, shutting down socket")
        if not self.sock_dead:
            self.sock.shutdown(socket.SHUT_WR)
        self.sock.close()


text:
var selftest = require('../tool-testing/selftest.js');
var Sandbox = selftest.Sandbox;

import * as files from "../fs/files";
import { execSync } from 'child_process';
// Default maxBuffer for execSync is 1024 * 1024 bytes, so this is 10x that.
const maxBuffer = 10 * 1024 * 1024;

selftest.define("bundle", function () {
  var s = new Sandbox();
  var run;

  s.createApp("myapp", "standard-app");
  s.cd("myapp");
  run = s.run("bundle", "../myapp.tgz");
  run.waitSecs(60);
  run.expectExit(0);

  var tarball = files.pathJoin(s.cwd, "../myapp.tgz");
  selftest.expectEqual(files.exists(tarball), true);
});

selftest.define("bundle - verify sanitized asset names", function () {
  const s = new Sandbox();
  let run;

  s.createApp("sanitized-app", "sanitized-app");
  s.cd("sanitized-app");
  run = s.run("bundle", "../sanitized-app.tgz");
  run.waitSecs(60);
  run.expectExit(0);

  const tarball = files.pathJoin(s.cwd, "../sanitized-app.tgz");
  const sanitizedFilename = 'Meteor_-@2x.png';
  selftest.expectTrue(
    execSync(`tar -tf ${tarball}`, {
      maxBuffer,
    }).toString().indexOf(sanitizedFilename) > -1
  );
});

selftest.define("build - linked external npm package (#10177)", function () {
  const s = new Sandbox();

  s.mkdir("external-package");
  s.cd("external-package");

  s.write(
    "package.json",
    JSON.stringify({
      name: "external-package",
      version: "1.2.3",
      "private": true,
      main: "index.js"
    }, null, 2) + "\n"
  );

  s.write(
    "index.js",
    "exports.id = module.id;\n"
  );

  s.cd(s.home);

  s.createApp("app", "linked-external-npm-package");
  s.cd("app");

  const run = s.run();
  run.waitSecs(30);
  run.match("external-package/index.js");
  run.stop();

  const build = s.run("build", "../build");
  build.waitSecs(60);
  build.expectExit(0);

  selftest.expectTrue(execSync(
    "tar -tf " + files.pathJoin(s.home, "build", "app.tar.gz"),
    { maxBuffer },
  ).toString("utf8").split("\n").includes(
    "bundle/programs/server/npm/node_modules/external-package/package.json"
  ));
});

selftest.define("build - link npm package named 'config' (#10892)", function () {
  const s = new Sandbox();

  s.mkdir("config-package");
  s.cd("config-package");

  s.write(
      "package.json",
      JSON.stringify({
        name: "config",
        version: "1.0.0",
        private: true,
        main: "index.js"
      }, null, 2) + "\n"
  );

  s.write(
      "index.js",
      "exports.id = module.id;\n"
  );

  s.cd(s.home);

  s.createApp("app", "link-config-npm-package");
  s.cd("app");

  const run = s.run();
  run.waitSecs(30);
  run.match("config-package/index.js");
  run.stop();

  const build = s.run("build", "../build");
  build.waitSecs(60);
  build.expectExit(0);

  const command = "cd " + files.pathJoin(s.home, "build") + " && tar -xzf app.tar.gz bundle/programs/server/packages/modules.js && grep -c \"meteorInstall({\\\"node_modules\\\":{\\\"config\\\":\" bundle/programs/server/packages/modules.js";
  const commandResult = execSync(command,{ maxBuffer }).toString("utf8");

  selftest.expectTrue(commandResult === "1\n");
});

selftest.define("bundle - isobuild crashes with ERR_INVALID_ARG_TYPE when encountering broken symlinks (#11241)", function () {
  const s = new Sandbox({ fakeMongo: true });

  s.createApp("myapp", "standard-app");
  s.cd("myapp");

  //Add bad symlink
  s.mkdir("node_modules/.bin");
  const symlink = files.pathJoin(s.cwd, "node_modules/.bin/bad");
  try {
    files.unlink(symlink);
  } catch (e) {
    if (e.code !== "ENOENT") throw e;
  }
  files.symlink("nonexistent", symlink);

  const run = s.run();
  run.match("myapp");
  run.match("proxy");

  //make sure we get the useful error, not the cryptic one
  run.matchErr("Broken symbolic link encountered at");
});


text:
@extends('app')

@section('content')

Articles

    @foreach($articles as $article)

id])}}"> {{ $article->title }}

{{$article->excerpt}}

    @endforeach

@endsection
@stop


text: module.exports = 'plugin';


text:
 * This line loads in image into background (surface)
background = pygame.image.load("street.jpg")

* This line draws the background
screen.blit(background, (0, 0))

## Display text

* You have to call this at the start,

pygame.font.init()

* Set up a font, try changing the size, Roboto

myfont = pygame.font.SysFont("Arial", 30)

* Draw the text to a surface
* Try changing the 'Hello Dojo;
* Try changing the color
* Try changing False to True, anti aliasing
* Try changing the position (0,0)  x , y
textsurface = myfont.render('Hello DoJo', False, (255, 0, 0))

* blit the surface to the screen
screen.blit(textsurface, (0, 0))

## Score

* Add a global variable called score and set to zero
score = 0

* Find the code that get run when a player eats a pill
* Add to score
score = score + 1

* Print the score out
print ("Score", score)

* Does it update?
* We need to make the global variable available to the function

global score

* Change the text to print the score out
scoreText = "Score " + str(score)
textsurface = myfont.render(scoreText, False, (255, 0, 0))

## Draw text centered (Extended)

* get the text surface width

textRect = textsurface.get_rect()
textWidth = textRect.width

* subtract it from screen width and divide by 2
textX = (640 - textWidth) / 2

screen.blit(textsurface, (textX, 0))


text:
package mimir.lenses;

import mimir.Database
import mimir.algebra._
import mimir.ctables._;

/**
 * A Lens defines a Virtual PC-Table.  A lens consists of two components:
 *
 * 1. A VG-Operator (i.e., a project+select including VGTerms)
 *    - Used to define the `C-Table` fragment of the VPC-Table.
 * 2. A Model (i.e., a probability distribution over VGTerms)
 *    - Used to define the `P` fragment of the VPC-Table
 *
 */

abstract case class Lens(name: String, args: List[Expression], source: Operator)
{
  /**
   * `view` emits an Operator that defines the Virtual C-Table for the lens
   */
  def view: Operator;

  /**
   * Return the lens' model.  This model must define a mapping for all VGTerms created
   * by `view`
   */
  def model: Model;

  /**
   * Initialize the lens' model by building it from scratch.  Typically this involves
   * using `db` to evaluate `source`
   */
  def build(db: Database): Unit;

  /**
   * Serialize the lens' model and store it in `db`.  The `name` parameter may be
   * used as a unique identifier for the model.
   */
  def save(db: Database): Unit = {};

  /**
   * Initialize the lens' model by loading the serialized representation stored by
   * `save`.
   */
  def load(db: Database): Unit = build(db);

  // def globalVar(vid: Int) = PVar(iview, id, vid, List[Expression]())
  def rowVar(vid: Int)   = VGTerm((name,model), vid, List[Expression](Var("ROWID")))
  def rowVar(vid: Int, args: List[Expression])
                         = VGTerm((name,model), vid, Var("ROWID") :: args)
  // def groupVar(vid: Int, group: List[Expression]) = PVar(iview, id, vid, group)
  // def varName(vid: Int): String = { iview+"_"+id+"_"+vid }

  def stringArg(id: Int): String = Eval.evalString(args(id))
  def longArg(id: Int): Long     = Eval.evalInt(args(id))
  def doubleArg(id: Int): Double = Eval.evalFloat(args(id))
  def lensType: String
  def schema(): List[(String, Type.T)]
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<workingSetManager>
<workingSet aggregate="true" factoryID="org.eclipse.ui.internal.WorkingSetFactory" id="1497941657916_0" label="Window Working Set" name="Aggregate for window 1497941657915"/>
</workingSetManager>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ZipFile (Apache Ant API)</title>
<meta name="date" content="2012-05-22">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.tools.zip

Class ZipFile

java.lang.Object

org.apache.tools.zip.ZipFile

public class ZipFile
extends java.lang.Object

Replacement for java.util.ZipFile.

This class adds support for file name encodings other than UTF-8
 (which is required to work on ZIP files created by native zip tools
 and is able to skip a preamble like the one found in self
 extracting archives.  Furthermore it returns instances of
 org.apache.tools.zip.ZipEntry instead of
 java.util.zip.ZipEntry.

It doesn't extend java.util.zip.ZipFile as it would
 have to reimplement all methods anyway.  Like
 java.util.ZipFile, it uses RandomAccessFile under the
 covers and supports compressed and uncompressed entries.

The method signatures mimic the ones of
 java.util.zip.ZipFile, with a couple of exceptions:

There is no getName method.

entries has been renamed to getEntries.

getEntries and getEntry return
   org.apache.tools.zip.ZipEntry instances.

close is allowed to throw IOException.

Constructor Summary

Constructors

Constructor and Description

ZipFile(java.io.File f)

Opens the given file for reading, assuming the platform's
 native encoding for file names.

ZipFile(java.io.File f,
       java.lang.String encoding)

Opens the given file for reading, assuming the specified
 encoding for file names and scanning for unicode extra fields.

ZipFile(java.io.File f,
       java.lang.String encoding,
       boolean useUnicodeExtraFields)

Opens the given file for reading, assuming the specified
 encoding for file names.

ZipFile(java.lang.String name)

Opens the given file for reading, assuming the platform's
 native encoding for file names.

ZipFile(java.lang.String name,
       java.lang.String encoding)

Opens the given file for reading, assuming the specified
 encoding for file names, scanning unicode extra fields.

Method Summary

Methods

Modifier and Type
Method and Description

void
close()

Closes the archive.

static void
closeQuietly(ZipFile zipfile)

close a zipfile quietly; throw no io fault, do nothing
 on a null parameter

protected static java.util.Date
fromDosTime(ZipLong zipDosTime)

Convert a DOS date/time field to a Date object.

java.lang.String
getEncoding()

The encoding to use for filenames and the file comment.

java.util.Enumeration
getEntries()

Returns all entries.

ZipEntry
getEntry(java.lang.String name)

Returns a named entry - or null if no entry by
 that name exists.

java.io.InputStream
getInputStream(ZipEntry ze)

Returns an InputStream for reading the contents of the given entry.

protected java.lang.String
getString(byte[] bytes)

Retrieve a String from the given bytes using the encoding set
 for this ZipFile.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ZipFile

public ZipFile(java.io.File f)
        throws java.io.IOException

Opens the given file for reading, assuming the platform's
 native encoding for file names.

Parameters:

f - the archive.

Throws:

java.io.IOException - if an error occurs while reading the file.

ZipFile

public ZipFile(java.lang.String name)
        throws java.io.IOException

Opens the given file for reading, assuming the platform's
 native encoding for file names.

Parameters:

name - name of the archive.

Throws:

java.io.IOException - if an error occurs while reading the file.

ZipFile

public ZipFile(java.lang.String name,
       java.lang.String encoding)
        throws java.io.IOException

Opens the given file for reading, assuming the specified
 encoding for file names, scanning unicode extra fields.

Parameters:

name - name of the archive.

encoding - the encoding to use for file names

Throws:

java.io.IOException - if an error occurs while reading the file.

ZipFile

public ZipFile(java.io.File f,
       java.lang.String encoding)
        throws java.io.IOException

Opens the given file for reading, assuming the specified
 encoding for file names and scanning for unicode extra fields.

Parameters:

f - the archive.

encoding - the encoding to use for file names, use null
 for the platform's default encoding

Throws:

java.io.IOException - if an error occurs while reading the file.

ZipFile

public ZipFile(java.io.File f,
       java.lang.String encoding,
       boolean useUnicodeExtraFields)
        throws java.io.IOException

Opens the given file for reading, assuming the specified
 encoding for file names.

Parameters:

f - the archive.

encoding - the encoding to use for file names, use null
 for the platform's default encoding

useUnicodeExtraFields - whether to use InfoZIP Unicode
 Extra Fields (if present) to set the file names.

Throws:

java.io.IOException - if an error occurs while reading the file.

Method Detail

getEncoding

public java.lang.String getEncoding()

The encoding to use for filenames and the file comment.

Returns:

null if using the platform's default character encoding.

close

public void close()
           throws java.io.IOException

Closes the archive.

Throws:

java.io.IOException - if an error occurs closing the archive.

closeQuietly

public static void closeQuietly(ZipFile zipfile)

close a zipfile quietly; throw no io fault, do nothing
 on a null parameter

Parameters:

zipfile - file to close, can be null

getEntries

public java.util.Enumeration getEntries()

Returns all entries.

Returns:

all entries as ZipEntry instances

getEntry

public ZipEntry getEntry(java.lang.String name)

Returns a named entry - or null if no entry by
 that name exists.

Parameters:

name - name of the entry.

Returns:

the ZipEntry corresponding to the given name - or
 null if not present.

getInputStream

public java.io.InputStream getInputStream(ZipEntry ze)
                                   throws java.io.IOException,
                                          java.util.zip.ZipException

Returns an InputStream for reading the contents of the given entry.

Parameters:

ze - the entry to get the stream for.

Returns:

a stream to read the entry from.

Throws:

java.io.IOException - if unable to create an input stream from the zipenty

java.util.zip.ZipException - if the zipentry has an unsupported
 compression method

fromDosTime

protected static java.util.Date fromDosTime(ZipLong zipDosTime)

Convert a DOS date/time field to a Date object.

Parameters:

zipDosTime - contains the stored DOS time.

Returns:

a Date instance corresponding to the given time.

getString

protected java.lang.String getString(byte[] bytes)
                              throws java.util.zip.ZipException

Retrieve a String from the given bytes using the encoding set
 for this ZipFile.

Parameters:

bytes - the byte array to transform

Returns:

String obtained by using the given encoding

Throws:

java.util.zip.ZipException - if the encoding cannot be recognized.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ochrolechia szatalaensis var. macrospora Verseghy

### Remarks
null


text:
package couchserver

import (
	"context"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/flimzy/diff"
	"github.com/flimzy/kivik"
	"github.com/flimzy/kivik/errors"
)

type mockCreator struct {
	backend
}

func (p *mockCreator) CreateDB(_ context.Context, _ string, _ ...kivik.Options) error {
	return nil
}

type errCreator struct {
	backend
}

func (p *errCreator) CreateDB(_ context.Context, _ string, _ ...kivik.Options) error {
	return errors.New("failure")
}

func TestPutDB(t *testing.T) {
	t.Run("Success", func(t *testing.T) {
		h := &Handler{client: &mockCreator{}}
		resp := callEndpoint(h, "PUT", "/foo")
		if resp.StatusCode != http.StatusOK {
			t.Errorf("Expected 200, got %s", resp.Status)
		}
		expected := map[string]interface{}{
			"ok": true,
		}
		if d := diff.AsJSON(expected, resp.Body); d != nil {
			t.Error(d)
		}
	})
	t.Run("Error", func(t *testing.T) {
		h := &Handler{client: &errCreator{}}
		resp := callEndpoint(h, "PUT", "/foo")
		if resp.StatusCode != http.StatusInternalServerError {
			t.Errorf("Expected 500, got %s", resp.Status)
		}
	})
}

type mockNotExists struct{ backend }

func (d *mockNotExists) DBExists(_ context.Context, _ string, _ ...kivik.Options) (bool, error) {
	return false, nil
}

type mockExists struct{ backend }

func (d *mockExists) DBExists(_ context.Context, _ string, _ ...kivik.Options) (bool, error) {
	return true, nil
}

type mockErrExists struct{ backend }

func (d *mockErrExists) DBExists(_ context.Context, _ string, _ ...kivik.Options) (bool, error) {
	return false, errors.New("failure")
}

func TestHeadDB(t *testing.T) {
	t.Run("NotExists", func(t *testing.T) {
		h := &Handler{client: &mockNotExists{}}
		resp := callEndpoint(h, "HEAD", "/notexist")
		if resp.StatusCode != http.StatusNotFound {
			t.Errorf("Expected 404/NotFound, got %s", resp.Status)
		}
	})

	t.Run("Exists", func(t *testing.T) {
		h := &Handler{client: &mockExists{}}
		resp := callEndpoint(h, "HEAD", "/exists")
		if resp.StatusCode != http.StatusOK {
			t.Errorf("Expected 200/OK, got %s", resp.Status)
		}
	})

	t.Run("Error", func(t *testing.T) {
		h := &Handler{client: &mockErrExists{}}
		resp := callEndpoint(h, "HEAD", "/exists")
		if resp.StatusCode != http.StatusInternalServerError {
			t.Errorf("Expected 500, got %s", resp.Status)
		}
	})
}

type mockFoundDB struct{ db }

// expected := map[string]interface{}{
// 	"committed_update_seq": 292786,
// 	"compact_running":      false,
// 	"data_size":            65031503,
// 	"disk_format_version":  6,
// 	"instance_start_time":  "1376269325408900",
// 	"purge_seq":            1,
// }

var testStats = &kivik.DBStats{
	Name:           "receipts",
	CompactRunning: false,
	DocCount:       6146,
	DeletedCount:   64637,
	UpdateSeq:      "292786",
	DiskSize:       137433211,
	ActiveSize:     1,
}

func (d *mockFoundDB) Stats(_ context.Context) (*kivik.DBStats, error) {
	return testStats, nil
}

type mockGetFound struct{ backend }

func (c *mockGetFound) DB(_ context.Context, _ string, _ ...kivik.Options) (db, error) {
	return &mockFoundDB{}, nil
}

type mockGetNotFound struct{ backend }

func (c *mockGetNotFound) DB(_ context.Context, _ string, _ ...kivik.Options) (db, error) {
	return nil, errors.Status(http.StatusNotFound, "database not found")
}

type errClient struct{ backend }

func (c *errClient) DB(_ context.Context, _ string, _ ...kivik.Options) (db, error) {
	return nil, errors.New("failure")
}

func TestGetDB(t *testing.T) {
	t.Run("Endpoint exists for GET", func(t *testing.T) {
		h := &Handler{client: &mockGetNotFound{}}
		resp := callEndpointEndClose(h, "GET", "/exists")
		if resp.StatusCode == http.StatusMethodNotAllowed {
			t.Error("Expected another response than method not allowed")
		}
	})

	t.Run("Not found", func(t *testing.T) {
		h := &Handler{client: &mockGetNotFound{}}
		resp := callEndpointEndClose(h, "GET", "/notexists")
		if resp.StatusCode != http.StatusNotFound {
			t.Errorf("Expected 404, got %s", resp.Status)
		}
	})

	t.Run("Found", func(t *testing.T) {
		h := &Handler{client: &mockGetFound{}}
		resp := callEndpointEndClose(h, "GET", "/asdf")
		if resp.StatusCode != http.StatusOK {
			t.Errorf("Expected 200, got %s", resp.Status)
		}
	})

	t.Run("Error", func(t *testing.T) {
		h2 := &Handler{client: &errClient{}}
		resp := callEndpointEndClose(h2, "GET", "/error")
		if resp.StatusCode != http.StatusInternalServerError {
			t.Errorf("Expected 500, got %s", resp.Status)
		}
	})

	t.Run("Response", func(t *testing.T) {
		h := &Handler{client: &mockGetFound{}}
		resp := callEndpoint(h, "GET", "/asdf")
		if cc := resp.Header.Get("Cache-Control"); cc != "must-revalidate" {
			t.Errorf("Cache-Control header doesn't match, got %s", cc)
		}
		if contentType := resp.Header.Get("Content-Type"); contentType != "application/json" {
			t.Errorf("Content-Type header doesn't match, got %s", contentType)
		}
		var body interface{}
		buf, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			t.Fatal(err)
		}
		resp.Body.Close()
		if err = json.Unmarshal(buf, &body); err != nil {
			t.Errorf("JSON error, %s", err)
		}
		expected := testStats
		if difftext := diff.AsJSON(expected, body); difftext != nil {
			t.Error(difftext)
		}
	})
}

func callEndpoint(h *Handler, method string, path string) *http.Response {
	w := httptest.NewRecorder()
	req := httptest.NewRequest(method, path, nil)
	handler := h.Main()
	handler.ServeHTTP(w, req)
	resp := w.Result()
	return resp
}

func callEndpointEndClose(h *Handler, method string, path string) *http.Response {
	resp := callEndpoint(h, method, path)
	resp.Body.Close()
	return resp
}


text:
package com.facebook.buck.cli;

import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.parser.PartialGraph;
import com.facebook.buck.rules.ArtifactCache;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.DependencyGraph;
import com.facebook.buck.rules.InputRule;
import com.facebook.buck.util.BuckConstant;
import com.facebook.buck.util.ProjectFilesystem;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.TreeMultimap;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.Set;

/**
 * Outputs targets that own a specified list of files.
 */
public class AuditOwnerCommand extends AbstractCommandRunner<AuditOwnerOptions> {

  private static final String FILE_INDENT = "    ";

  public AuditOwnerCommand(CommandRunnerParams params) {
    super(params);
  }

  @VisibleForTesting
  static final class OwnersReport {
    final ImmutableSetMultimap<BuildRule, InputRule> owners;
    final ImmutableSet<InputRule> inputsWithNoOwners;
    final ImmutableSet<String> nonExistentInputs;
    final ImmutableSet<String> nonFileInputs;

    public OwnersReport(SetMultimap<BuildRule, InputRule> owners,
                        Set<InputRule> inputsWithNoOwners,
                        Set<String> nonExistentInputs,
                        Set<String> nonFileInputs) {
      this.owners = ImmutableSetMultimap.copyOf(owners);
      this.inputsWithNoOwners = ImmutableSet.copyOf(inputsWithNoOwners);
      this.nonExistentInputs = ImmutableSet.copyOf(nonExistentInputs);
      this.nonFileInputs = ImmutableSet.copyOf(nonFileInputs);
    }
  }

  @VisibleForTesting
  AuditOwnerCommand(PrintStream stdOut,
                    PrintStream stdErr,
                    Console console,
                    ProjectFilesystem projectFilesystem,
                    ArtifactCache artifactCache) {
    super(stdOut, stdErr, console, projectFilesystem, artifactCache);
  }

  @Override
  AuditOwnerOptions createOptions(BuckConfig buckConfig) {
    return new AuditOwnerOptions(buckConfig);
  }

  @Override
  int runCommandWithOptions(AuditOwnerOptions options) throws IOException {

    // Build full graph.
    PartialGraph graph;
    try {
      graph = PartialGraph.createFullGraph(
          getProjectFilesystem().getProjectRoot(),
          getArtifactCache(),
          options.getDefaultIncludes());
    } catch (NoSuchBuildTargetException e) {
      console.printFailureWithoutStacktrace(e);
      return 1;
    }

    OwnersReport report = generateOwnersReport(graph.getDependencyGraph(), options);
    printReport(options, report);
    return 0;
  }

  @VisibleForTesting
  OwnersReport generateOwnersReport(DependencyGraph graph, AuditOwnerOptions options) {

    // Process arguments assuming they are all relative file paths
    Set<InputRule> inputs = Sets.newHashSet();
    Set<String> nonExistentInputs = Sets.newHashSet();
    Set<String> nonFileInputs = Sets.newHashSet();

    for (String filePath : options.getArguments()) {
      File file = getProjectFilesystem().getFileForRelativePath(filePath);
      if (!file.exists()) {
        nonExistentInputs.add(filePath);
      } else if (!file.isFile()) {
        nonFileInputs.add(filePath);
      } else {
        inputs.add(new InputRule(filePath));
      }
    }

    // Try to find owners for each valid and existing file
    Set<InputRule> inputsWithNoOwners = Sets.newHashSet(inputs);
    SetMultimap<BuildRule, InputRule> owners = createOwnersMap();
    for (BuildRule rule : graph.getNodes()) {
      for (InputRule ruleInput : rule.getInputs()) {
        if (inputs.contains(ruleInput)) {
          inputsWithNoOwners.remove(ruleInput);
          owners.put(rule, ruleInput);
        }
      }
    }

    // Try to guess owners for nonexistent files
    if (options.isGuessForDeletedEnabled()) {
      guessOwnersForNonExistentFiles(graph, owners, nonExistentInputs);
    }

    return new OwnersReport(owners, inputsWithNoOwners, nonExistentInputs, nonFileInputs);
  }

  /**
   * Guess target owners for deleted/missing files by finding first
   * BUCK file and assuming that all targets in this file used
   * missing file as input.
   */
  private void guessOwnersForNonExistentFiles(DependencyGraph graph,
      SetMultimap<BuildRule, InputRule> owners, Set<String> nonExistentFiles) {

    for (String nonExistentFile : nonExistentFiles) {
      File file = getProjectFilesystem().getFileForRelativePath(nonExistentFile);
      File buck = findBuckFileFor(file);
      for (BuildRule rule : graph.getNodes()) {
        if (rule.getType() == BuildRuleType.PROJECT_CONFIG) {
          continue;
        }
        File ruleBuck = rule.getBuildTarget().getBuildFile();
        try {
          if (buck.getCanonicalFile().equals(ruleBuck.getCanonicalFile())) {
            owners.put(rule, new InputRule(nonExistentFile));
          }
        } catch (IOException ex) {
          throw Throwables.propagate(ex);
        }
      }
    }
  }

  private File findBuckFileFor(File file) {
    File dir = file;
    if (!dir.isDirectory()) {
      dir = dir.getParentFile();
    }

    File projectRoot = getProjectFilesystem().getProjectRoot();
    while (dir != null && !dir.equals(projectRoot)) {
      File buck = new File(dir, BuckConstant.BUILD_RULES_FILE_NAME);
      if (buck.exists()) {
        return buck;
      }
      dir = dir.getParentFile();
    }
    throw new RuntimeException("Failed to find BUCK file for " + file.getPath());
  }

  private void printReport(AuditOwnerOptions options, OwnersReport report) {

    if (options.isFullReportEnabled()) {
      printFullReport(report);
    } else {
      printOwnersOnlyReport(report);
    }
  }

  /**
   * Print only targets which were identified as owners.
   */
  private void printOwnersOnlyReport(OwnersReport report) {
    Set<BuildRule> sortedRules = report.owners.keySet();
    for (BuildRule rule : sortedRules) {
      console.getStdOut().println(rule.getFullyQualifiedName());
    }
  }

  /**
   * Print detailed report on all owners.
   */
  private void printFullReport(OwnersReport report) {
    PrintStream out = console.getStdOut();
    if (report.owners.isEmpty()) {
      out.println(ansi.asErrorText("No owners found"));
    } else {
      out.println(ansi.asSuccessText("Owners:"));
      for (BuildRule rule : report.owners.keySet()) {
        out.println(rule.getFullyQualifiedName());
        Set<InputRule> files = report.owners.get(rule);
        for (InputRule input : files) {
          out.println(FILE_INDENT + input);
        }
      }
    }

    if (!report.inputsWithNoOwners.isEmpty()) {
      out.println();
      out.println(ansi.asErrorText("Files without owners:"));
      for (InputRule input : report.inputsWithNoOwners) {
        out.println(FILE_INDENT + input);
      }
    }

    if (!report.nonExistentInputs.isEmpty()) {
      out.println();
      out.println(ansi.asErrorText("Non existent files:"));
      for (String input : report.nonExistentInputs) {
        out.println(FILE_INDENT + input);
      }
    }

    if (!report.nonFileInputs.isEmpty()) {
      out.println();
      out.println(ansi.asErrorText("Non-file inputs:"));
      for (String input : report.nonFileInputs) {
        out.println(FILE_INDENT + input);
      }
    }
  }

  private SetMultimap<BuildRule, InputRule> createOwnersMap() {
    Comparator<BuildRule> keyComparator = new Comparator<BuildRule>() {
      @Override
      public int compare(BuildRule o1, BuildRule o2) {
        return o1.getFullyQualifiedName().compareTo(o2.getFullyQualifiedName());
      }
    };

    Comparator<InputRule> valueComparator = new Comparator<InputRule>() {
      @Override
      public int compare(InputRule o1, InputRule o2) {
        return o1.compareTo(o2);
      }
    };

    return TreeMultimap.create(keyComparator, valueComparator);
  }

  @Override
  String getUsageIntro() {
    return "prints targets that own specified files";
  }

}


text:
/*
Open Weather Map Instructions:

1)
- Use either $.ajax or $.get to GET the current weather data for New York City
- Use the API docs to figure out how to properly structure the weatherUrl below (http://openweathermap.org/current)
	- Hint: search the docs for "city name"
- Be sure to include in the weatherUrl the option to receive data in your units of choice (imperial, metric, etc.)
	- Hint: search the docs for "units format"
- First, print the response to the console, then, using the API's response, print the following data to #nyc-weather:
	- The current "temp"
	- The current "hummidity"
	- The current wind "speed"

2)
- Add a form to to the index.html page that allows the user to enter a city and a state
- Capture this form's submit event and dynamically create the weatherUrl below from the user's input
- Print this result to the DOM

3) Bonus:
- Change the background color based on the temperature; ie colder temps should be blue, and hotter temps red

4) Intermediate Bonus:
- Implement handlebars.js templates :)

5) Legendary Bonus:
- Sign up for the flicker API: https://www.flickr.com/services/api/
- Use the flicker search photo library: https://www.flickr.com/services/api/flickr.photos.search.html
- Hint: you will have to convert the responses from the search API into images: https://www.flickr.com/services/api/misc.urls.html
- Instead of changing the background color based on temperature, change the background to first result the flicker API returns for the city
- Ex: user enters "Brooklyn" - search flicker API for "Brooklyn" and use the first image

*/

$(document).ready(function () {
  var apiKey = '19ab861f15cfd2e8216a3be1ed615598';
  var weatherUrl = '';
});


text:
tor cheeor cKheos olSheeosol cPheol cPheor chodar
ytol oteeor Sheol oteey qokeody qokeeody cThey
toaiin cTheodal chos cKheody keody chodol oty
or chor chkchol chokchor s or SheocKhy choly
daiin chodaiin cThey tol Sheor qokeol okol
lor cKheey chol cholody cheol cTheor sor
oiir or cKhor chkey cKhocThy or chocKhy
ykeor secheeol Sheol qokeeey chol daiin

todar Sheo cThody ShokocFhy chopcho dory
otcho dol ShocThody ShocKhy otchodor chocty
teol cheody Shodol qokchod s aiin chokey
dcheor cheol cheodain ol dy d chs archeody
oteeo dSho qotchos


text:
using Globals;
using Softv.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;

namespace SoftvWCFService.Contracts
{
    [ServiceContract]
    public interface ICOLONIA
    {
        [OperationContract]
        COLONIAEntity GetCOLONIA(int? Clv_Colonia);
        [OperationContract]
        COLONIAEntity GetDeepCOLONIA(int? Clv_Colonia);
        [OperationContract]
        IEnumerable<COLONIAEntity> GetCOLONIAList();
        [OperationContract]
        SoftvList<COLONIAEntity> GetCOLONIAPagedList(int page, int pageSize);
        [OperationContract]
        SoftvList<COLONIAEntity> GetCOLONIAPagedListXml(int page, int pageSize, String xml);
        [OperationContract]
        int AddCOLONIA(COLONIAEntity objCOLONIA);
        [OperationContract]
        int UpdateCOLONIA(COLONIAEntity objCOLONIA);
        [OperationContract]
        int DeleteCOLONIA(String BaseRemoteIp, int BaseIdUser, int? Clv_Colonia);

    }
}


text:
import json
import urllib

from tempest.api_schema.response.compute.v2 import floating_ips as schema
from tempest import exceptions
from tempest.services.compute.json import base

class FloatingIPsClientJSON(base.ComputeClient):

    def list_floating_ips(self, params=None):
        """Returns a list of all floating IPs filtered by any parameters."""
        url = 'os-floating-ips'
        if params:
            url += '?%s' % urllib.urlencode(params)

        resp, body = self.get(url)
        body = json.loads(body)
        self.validate_response(schema.list_floating_ips, resp, body)
        return resp, body['floating_ips']

    def get_floating_ip_details(self, floating_ip_id):
        """Get the details of a floating IP."""
        url = "os-floating-ips/%s" % str(floating_ip_id)
        resp, body = self.get(url)
        body = json.loads(body)
        if resp.status == 404:
            raise exceptions.NotFound(body)
        self.validate_response(schema.floating_ip, resp, body)
        return resp, body['floating_ip']

    def create_floating_ip(self, pool_name=None):
        """Allocate a floating IP to the project."""
        url = 'os-floating-ips'
        post_body = {'pool': pool_name}
        post_body = json.dumps(post_body)
        resp, body = self.post(url, post_body)
        body = json.loads(body)
        self.validate_response(schema.floating_ip, resp, body)
        return resp, body['floating_ip']

    def delete_floating_ip(self, floating_ip_id):
        """Deletes the provided floating IP from the project."""
        url = "os-floating-ips/%s" % str(floating_ip_id)
        resp, body = self.delete(url)
        self.validate_response(schema.add_remove_floating_ip, resp, body)
        return resp, body

    def associate_floating_ip_to_server(self, floating_ip, server_id):
        """Associate the provided floating IP to a specific server."""
        url = "servers/%s/action" % str(server_id)
        post_body = {
            'addFloatingIp': {
                'address': floating_ip,
            }
        }

        post_body = json.dumps(post_body)
        resp, body = self.post(url, post_body)
        self.validate_response(schema.add_remove_floating_ip, resp, body)
        return resp, body

    def disassociate_floating_ip_from_server(self, floating_ip, server_id):
        """Disassociate the provided floating IP from a specific server."""
        url = "servers/%s/action" % str(server_id)
        post_body = {
            'removeFloatingIp': {
                'address': floating_ip,
            }
        }

        post_body = json.dumps(post_body)
        resp, body = self.post(url, post_body)
        self.validate_response(schema.add_remove_floating_ip, resp, body)
        return resp, body

    def is_resource_deleted(self, id):
        try:
            self.get_floating_ip_details(id)
        except exceptions.NotFound:
            return True
        return False

    @property
    def resource_type(self):
        """Returns the primary type of resource this client works with."""
        return 'floating_ip'

    def list_floating_ip_pools(self, params=None):
        """Returns a list of all floating IP Pools."""
        url = 'os-floating-ip-pools'
        if params:
            url += '?%s' % urllib.urlencode(params)

        resp, body = self.get(url)
        body = json.loads(body)
        self.validate_response(schema.floating_ip_pools, resp, body)
        return resp, body['floating_ip_pools']

    def create_floating_ips_bulk(self, ip_range, pool, interface):
        """Allocate floating IPs in bulk."""
        post_body = {
            'ip_range': ip_range,
            'pool': pool,
            'interface': interface
        }
        post_body = json.dumps({'floating_ips_bulk_create': post_body})
        resp, body = self.post('os-floating-ips-bulk', post_body)
        body = json.loads(body)
        self.validate_response(schema.create_floating_ips_bulk, resp, body)
        return resp, body['floating_ips_bulk_create']

    def list_floating_ips_bulk(self):
        """Returns a list of all floating IPs bulk."""
        resp, body = self.get('os-floating-ips-bulk')
        body = json.loads(body)
        self.validate_response(schema.list_floating_ips_bulk, resp, body)
        return resp, body['floating_ip_info']

    def delete_floating_ips_bulk(self, ip_range):
        """Deletes the provided floating IPs bulk."""
        post_body = json.dumps({'ip_range': ip_range})
        resp, body = self.put('os-floating-ips-bulk/delete', post_body)
        body = json.loads(body)
        self.validate_response(schema.delete_floating_ips_bulk, resp, body)
        return resp, body['floating_ips_bulk_delete']


text:
General Concepts
================

Serializer vs Signer
--------------------

ItsDangerous provides two levels of data handling. The :doc:`/signer` is
the basic system that signs a given ``bytes`` value based on the given
signing parameters. The :doc:`/serializer` wraps a signer to enable
serializing and signing other data besides ``bytes``.

Typically, you'll want to use a serializer, not a signer. You can
configure the signing parameters through the serializer, and even
provide fallback signers to upgrade old tokens to new parameters.

The Secret Key
--------------

Signatures are secured by the ``secret_key``. Typically one secret key
is used with all signers, and the salt is used to distinguish different
contexts. Changing the secret key will invalidate existing tokens.

It should be a long random string of bytes. This value must be kept
secret and should not be saved in source code or committed to version
control. If an attacker learns the secret key, they can change and
resign data to look valid. If you suspect this happened, change the
secret key to invalidate existing tokens.

One way to keep the secret key separate is to read it from an
environment variable. When deploying for the first time, generate a key
and set the environment variable when running the application. All
process managers (like systemd) and hosting services have a way to
specify environment variables.

.. code-block:: python

    import os
    from itsdangerous.serializer import Serializer
    SECRET_KEY = os.environ.get("SECRET_KEY")
    s = Serializer(SECRET_KEY)

.. code-block:: text

    $ export SECRET_KEY="base64 encoded random bytes"
    $ python application.py

One way to generate a key is to use :func:`os.urandom`.

.. code-block:: text

    $ python3 -c 'import os; print(os.urandom(16).hex())'

The Salt
--------

The salt is combined with the secret key to derive a unique key for
distinguishing different contexts. Unlike the secret key, the salt
doesn't have to be random, and can be saved in code. It only has to be
unique between contexts, not private.

For example, you want to email activation links to activate user
accounts, and upgrade links to upgrade users to a paid accounts. If all
you sign is the user id, and you don't use different salts, a user could
reuse the token from the activation link to upgrade the account. If you
use different salts, the signatures will be different and will not be
valid in the other context.

.. code-block:: python

    from itsdangerous.url_safe import URLSafeSerializer

    s1 = URLSafeSerializer("secret-key", salt="activate")
    s1.dumps(42)
    'NDI.MHQqszw6Wc81wOBQszCrEE_RlzY'

    s2 = URLSafeSerializer("secret-key", salt="upgrade")
    s2.dumps(42)
    'NDI.c0MpsD6gzpilOAeUPra3NShPXsE'

The second serializer can't load data dumped with the first because the
salts differ.

.. code-block:: python

    s2.loads(s1.dumps(42))
    Traceback (most recent call last):
      ...
    BadSignature: Signature does not match

Only the serializer with the same salt can load the data.

.. code-block:: python

    s2.loads(s2.dumps(42))
    42

Key Rotation
------------

Key rotation can provide an extra layer of mitigation against an
attacker discovering a secret key. A rotation system will keep a list of
valid keys, generating a new key and removing the oldest key
periodically. If it takes four weeks for an attacker to crack a key, but
the key is rotated out after three weeks, they will not be able to use
any keys they crack. However, if a user doesn't refresh their token
within three weeks it will be invalid too.

The system that generates and maintains this list is outside the scope
of ItsDangerous, but ItsDangerous does support validating against a list
of keys.

Instead of passing a single key, you can pass a list of keys, oldest to
newest. When signing the last (newest) key will be used, and when
validating each key will be tried from newest to oldest before raising
a validation error.

.. code-block:: python

    SECRET_KEYS = ["2b9cd98e", "169d7886", "b6af09f5"]

    # sign some data with the latest key
    s = Serializer(SECRET_KEYS)
    t = s.dumps({"id": 42})

    # rotate a new key in and the oldest key out
    SECRET_KEYS.append("cf9b3588")
    del SECRET_KEYS[0]

    s = Serializer(SECRET_KEYS)
    s.loads(t)  # valid even though it was signed with a previous key

Digest Method Security
----------------------

A signer is configured with a ``digest_method``, a hash function that
is used as an intermediate step when generating the HMAC signature. The
default method is :func:`hashlib.sha1`. Occasionally, users are
concerned about this default because they have heard about hash
collisions with SHA-1.

When used as the intermediate, iterated step in HMAC, SHA-1 is not
insecure. In fact, even MD5 is still secure in HMAC. The security of the
hash alone doesn't apply when used in HMAC.

If a project considers SHA-1 a risk anyway, they can configure the
signer with a different digest method such as :func:`hashlib.sha512`.
A fallback signer for SHA-1 can be configured so that old tokens will be
upgraded. SHA-512 produces a longer hash, so tokens will take up more
space, which is relevant in cookies and URLs.


text:
/*
    The original source for this example is
    Copyright (c) 1994-2008 John E. Stone
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:
    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.
    3. The name of the author may not be used to endorse or promote products
       derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.
*/

/*
 * sphere.h - This file contains the defines for spheres etc.
 *
 *  $Id: sphere.h,v 1.2 2007-02-22 17:54:16 Exp $
 */

object * newsphere(void *, vector, flt);

#ifdef SPHERE_PRIVATE

typedef struct {
  unsigned int id;                      /* Unique Object serial number    */
  void * nextobj;                       /* pointer to next object in list */
  object_methods * methods;             /* this object's methods          */
  texture * tex;                        /* object texture                 */
  vector ctr;
  flt rad;
} sphere;

static int sphere_bbox(void * obj, vector * min, vector * max);
static void sphere_intersect(sphere *, ray *);
static void sphere_normal(sphere *, vector *, ray *, vector *);

#endif /* SPHERE_PRIVATE */


text:
Beer Recipe
===========

Generate html web pages from BeerXML files exported from beer recipe programs like BeerSmith or Brew Pal.

Wrapper around nrb-beerxml to make calculations and simplify making output templates.

Usage
-----

```bash
$ ruby bin/beer_recipe -h
Usage:
  bin/beer_recipe <beer.xml> [--format=<format>]
  bin/beer_recipe -h | --help
  bin/beer_recipe --version
```

Format may be 'html' or 'text', but defaults to html.