text:
import _ from 'lodash'
import React, {PureComponent} from 'react'
import {connect} from 'react-redux'

import {scrollTop} from '../../utils'

import Empty from '../../components/empty'
import Paginator from '../../components/paginator'

import * as actions from './redux'
import SupplierTable from './supplier-table'

class SupplierList extends PureComponent {
  constructor(props) {
    super(props)
    this.go = this.go.bind(this)
  }

  componentDidMount() {
    this.props.getSupplierList()
  }

  go(offset) {
    scrollTop()

    this.props.getSupplierList({
      params: {
        ...this.props.params,
        offset,
      },
    })
  }

  render() {
    const {
      objects,
      meta,
      supplier_status_dirty,

      reloadSupplierList,
      updateSupplierStatus,
    } = this.props

    if (objects === null) return null

    if (_.result(objects, 'length') === 0) {
      return (
        <Empty />
      )
    }

    return (

        <SupplierTable
          supplier_status_dirty={supplier_status_dirty}
          items={objects}
          reloadSupplierList={reloadSupplierList}
          onUpdateSupplierStatus={updateSupplierStatus}
        />

          <Paginator
            {...meta}
            go={this.go}
          />

    )
  }
}

export default connect(
  state => ({
    ...state.supplier_list,
    supplier_status_dirty: state.supplier_status_dirty,
  }),
  actions
)(SupplierList)


text:
"""This example populates a specific first party audience segment.

To determine which first party audience segments exist, run
get_first_party_audience_segments.py.
"""

# Import appropriate modules from the client library.
from googleads import dfp

AUDIENCE_SEGMENT_ID = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'

def main(client, audience_segment_id):
  # Initialize client object.
  client = dfp.DfpClient.LoadFromStorage()

  # Initialize appropriate service.
  audience_segment_service = client.GetService(
      'AudienceSegmentService', version='v201502')

  # Create statement object to get the specified first party audience segment.
  values = (
      [{'key': 'type',
        'value': {
            'xsi_type': 'TextValue',
            'value': 'FIRST_PARTY'
            }
       },
       {'key': 'audience_segment_id',
        'value': {
            'xsi_type': 'NumberValue',
            'value': AUDIENCE_SEGMENT_ID
            }
       }])
  query = 'WHERE Type = :type AND Id = :audience_segment_id'
  statement = dfp.FilterStatement(query, values, 1)

  response = audience_segment_service.getAudienceSegmentsByStatement(
      statement.ToStatement())

  if 'results' in response:
    segments = response['results']

    for segment in segments:
      print ('Audience segment with id \'%s\' and name \'%s\' will be populated.'
             % (segment['id'], segment['name']))

    action = {
        'xsi_type': 'PopulateAudienceSegments'
    }

    populated_audience_segments = (
        audience_segment_service.performAudienceSegmentAction(
            action, statement.ToStatement()))

    print ('%s audience segment populated' %
           populated_audience_segments['numChanges'])
  else:
    print 'No Results Found'

if __name__ == '__main__':
  # Initialize client object.
  dfp_client = dfp.DfpClient.LoadFromStorage()
  main(dfp_client, AUDIENCE_SEGMENT_ID)

redpajama_set_name: RedPajamaGithub


text:
<?php

defined('_JEXEC') or die;

JHtml::_('behavior.keepalive');
JHtml::_('behavior.core');
JHtml::_('jquery.framework');
JHtml::_('script', 'com_finder/indexer.js', false, true);
JFactory::getDocument()->addScriptDeclaration('var msg = "' . JText::_('COM_FINDER_INDEXER_MESSAGE_COMPLETE') . '";');
?>

<?php echo JText::_('COM_FINDER_INDEXER_HEADER_INIT'); ?>

<?php echo JText::_('COM_FINDER_INDEXER_MESSAGE_INIT'); ?>

	<input id="finder-indexer-token" type="hidden" name="<?php echo JFactory::getSession()->getFormToken(); ?>" value="1" />


text:
package runtime

import (
    "github.com/allada/gdd/protocol/shared"
)

type EvaluateCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
    Expression string `json:"expression"`// Expression to evaluate.
    ObjectGroup *string `json:"objectGroup,omitempty"`// Symbolic group name that can be used to release multiple objects.
    IncludeCommandLineAPI *bool `json:"includeCommandLineAPI,omitempty"`// Determines whether Command Line API should be available during the evaluation.
    Silent *bool `json:"silent,omitempty"`// In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state.
    ContextId *ExecutionContextId `json:"contextId,omitempty"`// Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page.
    ReturnByValue *bool `json:"returnByValue,omitempty"`// Whether the result is expected to be a JSON object that should be sent by value.
    GeneratePreview *bool `json:"generatePreview,omitempty"`// [Experimental] Whether preview should be generated for the result.
    UserGesture *bool `json:"userGesture,omitempty"`// [Experimental] Whether execution should be treated as initiated by user in the UI.
    AwaitPromise *bool `json:"awaitPromise,omitempty"`// Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error.
}
type EvaluateReturn struct {
    Result RemoteObject `json:"result"`// Evaluation result.
    ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty"`// Exception details.
}

func (c *EvaluateCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *EvaluateCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *EvaluateCommand) Respond(r *EvaluateReturn) {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, r)
}

type AwaitPromiseCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
    PromiseObjectId RemoteObjectId `json:"promiseObjectId"`// Identifier of the promise.
    ReturnByValue *bool `json:"returnByValue,omitempty"`// Whether the result is expected to be a JSON object that should be sent by value.
    GeneratePreview *bool `json:"generatePreview,omitempty"`// Whether preview should be generated for the result.
}
type AwaitPromiseReturn struct {
    Result RemoteObject `json:"result"`// Promise result. Will contain rejected value if promise was rejected.
    ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty"`// Exception details if stack strace is available.
}

func (c *AwaitPromiseCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *AwaitPromiseCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *AwaitPromiseCommand) Respond(r *AwaitPromiseReturn) {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, r)
}

type CallFunctionOnCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
    ObjectId RemoteObjectId `json:"objectId"`// Identifier of the object to call function on.
    FunctionDeclaration string `json:"functionDeclaration"`// Declaration of the function to call.
    Arguments *[]CallArgument `json:"arguments,omitempty"`// Call arguments. All call arguments must belong to the same JavaScript world as the target object.
    Silent *bool `json:"silent,omitempty"`// In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state.
    ReturnByValue *bool `json:"returnByValue,omitempty"`// Whether the result is expected to be a JSON object which should be sent by value.
    GeneratePreview *bool `json:"generatePreview,omitempty"`// [Experimental] Whether preview should be generated for the result.
    UserGesture *bool `json:"userGesture,omitempty"`// [Experimental] Whether execution should be treated as initiated by user in the UI.
    AwaitPromise *bool `json:"awaitPromise,omitempty"`// Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error.
}
type CallFunctionOnReturn struct {
    Result RemoteObject `json:"result"`// Call result.
    ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty"`// Exception details.
}

func (c *CallFunctionOnCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *CallFunctionOnCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *CallFunctionOnCommand) Respond(r *CallFunctionOnReturn) {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, r)
}

type GetPropertiesCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
    ObjectId RemoteObjectId `json:"objectId"`// Identifier of the object to return properties for.
    OwnProperties *bool `json:"ownProperties,omitempty"`// If true, returns properties belonging only to the element itself, not to its prototype chain.
    AccessorPropertiesOnly *bool `json:"accessorPropertiesOnly,omitempty"`// [Experimental] If true, returns accessor properties (with getter/setter) only; internal properties are not returned either.
    GeneratePreview *bool `json:"generatePreview,omitempty"`// [Experimental] Whether preview should be generated for the results.
}
type GetPropertiesReturn struct {
    Result []PropertyDescriptor `json:"result"`// Object properties.
    InternalProperties *[]InternalPropertyDescriptor `json:"internalProperties,omitempty"`// Internal object properties (only of the element itself).
    ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty"`// Exception details.
}

func (c *GetPropertiesCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *GetPropertiesCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *GetPropertiesCommand) Respond(r *GetPropertiesReturn) {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, r)
}

type ReleaseObjectCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
    ObjectId RemoteObjectId `json:"objectId"`// Identifier of the object to release.
}
type ReleaseObjectReturn struct {
}

func (c *ReleaseObjectCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *ReleaseObjectCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *ReleaseObjectCommand) Respond() {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, struct{}{})
}

type ReleaseObjectGroupCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
    ObjectGroup string `json:"objectGroup"`// Symbolic object group name.
}
type ReleaseObjectGroupReturn struct {
}

func (c *ReleaseObjectGroupCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *ReleaseObjectGroupCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *ReleaseObjectGroupCommand) Respond() {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, struct{}{})
}

type RunIfWaitingForDebuggerCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
}
type RunIfWaitingForDebuggerReturn struct {
}

func (c *RunIfWaitingForDebuggerCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *RunIfWaitingForDebuggerCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *RunIfWaitingForDebuggerCommand) Respond() {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, struct{}{})
}

type EnableCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
}
type EnableReturn struct {
}

func (c *EnableCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *EnableCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *EnableCommand) Respond() {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, struct{}{})
}

type DisableCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
}
type DisableReturn struct {
}

func (c *DisableCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *DisableCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *DisableCommand) Respond() {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, struct{}{})
}

type DiscardConsoleEntriesCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
}
type DiscardConsoleEntriesReturn struct {
}

func (c *DiscardConsoleEntriesCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *DiscardConsoleEntriesCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *DiscardConsoleEntriesCommand) Respond() {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, struct{}{})
}

type SetCustomObjectFormatterEnabledCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
    Enabled bool `json:"enabled"`
}
type SetCustomObjectFormatterEnabledReturn struct {
}

func (c *SetCustomObjectFormatterEnabledCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *SetCustomObjectFormatterEnabledCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *SetCustomObjectFormatterEnabledCommand) Respond() {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, struct{}{})
}

type CompileScriptCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
    Expression string `json:"expression"`// Expression to compile.
    SourceURL string `json:"sourceURL"`// Source url to be set for the script.
    PersistScript bool `json:"persistScript"`// Specifies whether the compiled script should be persisted.
    ExecutionContextId *ExecutionContextId `json:"executionContextId,omitempty"`// Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page.
}
type CompileScriptReturn struct {
    ScriptId *ScriptId `json:"scriptId,omitempty"`// Id of the script.
    ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty"`// Exception details.
}

func (c *CompileScriptCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *CompileScriptCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *CompileScriptCommand) Respond(r *CompileScriptReturn) {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, r)
}

type RunScriptCommand struct {
    DestinationTargetID string
    responseId int64
    conn *shared.Connection
    ScriptId ScriptId `json:"scriptId"`// Id of the script to run.
    ExecutionContextId *ExecutionContextId `json:"executionContextId,omitempty"`// Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page.
    ObjectGroup *string `json:"objectGroup,omitempty"`// Symbolic group name that can be used to release multiple objects.
    Silent *bool `json:"silent,omitempty"`// In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state.
    IncludeCommandLineAPI *bool `json:"includeCommandLineAPI,omitempty"`// Determines whether Command Line API should be available during the evaluation.
    ReturnByValue *bool `json:"returnByValue,omitempty"`// Whether the result is expected to be a JSON object which should be sent by value.
    GeneratePreview *bool `json:"generatePreview,omitempty"`// Whether preview should be generated for the result.
    AwaitPromise *bool `json:"awaitPromise,omitempty"`// Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error.
}
type RunScriptReturn struct {
    Result RemoteObject `json:"result"`// Run result.
    ExceptionDetails *ExceptionDetails `json:"exceptionDetails,omitempty"`// Exception details.
}

func (c *RunScriptCommand) Initalize(targetId string, responseId int64, conn *shared.Connection) {
    c.DestinationTargetID = targetId
    c.responseId = responseId
    c.conn = conn
}

func (c *RunScriptCommand) RespondWithError(code shared.ResponseErrorCodes, message string) {
    c.conn.SendErrorResult(c.responseId, c.DestinationTargetID, code, message)
}

func (c *RunScriptCommand) Respond(r *RunScriptReturn) {
    c.conn.SendResult(c.responseId, c.DestinationTargetID, r)
}


text:
var fs = require("fs"),
	path = require("path");
module.exports = function Helpers(config) {

	function cleanOutFile(filePath) {
		fs.truncateSync(filePath, 0);
		if(config && config.logger) {
			config.logger.info("+cleared out file: " + filePath);
		}
	}

	function createFile(filePath) {
		if(ensureDirectories(filePath)) {
			fs.writeFileSync(filePath, "");
			if(config && config.logger) {
				config.logger.info("+created ast output file: ");
			}
		}
		cleanOutFile(filePath)
	}

	function ensureDirectories(filePath) {
		var parentDir = path.dirname(filePath);
		if(fs.existsSync(parentDir)) {
			return true;
		}

		ensureDirectories(parentDir);
		fs.mkdirSync(parentDir);
		return true;
	}

	return {
		cleanOutFile: cleanOutFile,
		createFile: createFile,
		ensureDirectories: ensureDirectories
	}
};


text:
<?php namespace Roots\Sage\Template;

/**
 * Interface WrapperInterface
 * @package Roots\Sage
 * @author QWp6t
 */
interface WrapperInterface
{

    /**
     * Get wrapper template file
     *
     * @return string Wrapper template (FQPN of, e.g., `base-page.php`, `base.php`)
     */
    public function getWrapper();

    /**
     * @return string Wrapped template (FQPN of, e.g., `page.php`, `single.php`, `singular.php`)
     */
    public function getTemplate();

    /**
     * @return string Slug of the WrapperInterface; e.g., `base`
     */
    public function getSlug();

}


text:
<?php

namespace Magento\Framework\Model\ResourceModel\Db\VersionControl;

/**
 * Class Metadata represents a list of entity fields that are applicable for persistence operations
 */
class Metadata
{
    /**
     * @var array
     */
    protected $metadataInfo = [];

    /**
     * Returns list of entity fields that are applicable for persistence operations
     *
     * @param \Magento\Framework\DataObject $entity
     * @return array
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function getFields(\Magento\Framework\DataObject $entity)
    {
        $entityClass = get_class($entity);
        if (!isset($this->metadataInfo[$entityClass])) {
            $this->metadataInfo[$entityClass] =
                array_fill_keys(
                    array_keys(
                        $entity->getResource()->getConnection()->describeTable(
                            $entity->getResource()->getMainTable()
                        )
                    ),
                    null
                );
        }
        return $this->metadataInfo[$entityClass];
    }
}


text:
{-
 Codec for de/encoding form data shipped in URL query strings
 or in POST request bodies. (application/x-www-form-urlencoded)
 (cf. RFC 3986.)
-}
module Codec.URLEncoder
       ( encodeString
       , decodeString
       ) where

import qualified Codec.Binary.UTF8.String as UTF8 ( encodeString )
import Codec.Percent ( getEncodedChar, getDecodedChar )

encodeString :: String -> String
encodeString str = go (UTF8.encodeString str)
 where
  go "" = ""
  go (' ':xs) = '+':go xs
  go ('\r':'\n':xs) = '%':'0':'D':'%':'0':'A':go xs
  go ('\r':xs) = go ('\r':'\n':xs)
  go ('\n':xs) = go ('\r':'\n':xs)
  go (x:xs) =
    case getEncodedChar x of
      Nothing -> x : go xs
      Just ss -> ss ++ go xs

decodeString :: String -> String
decodeString "" = ""
decodeString ('+':xs) = ' ':decodeString xs
decodeString ls@(x:xs) =
  case getDecodedChar ls of
    Nothing -> x : decodeString xs
    Just (ch,xs1) -> ch : decodeString xs1


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

<title>Uses of Class com.drew.metadata.iptc.IptcDirectory (Metadata-Extractor - JavaDoc - An Open Source Java Library for Image File Metadata)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.drew.metadata.iptc.IptcDirectory

Packages that use IptcDirectory

Package
Description

com.drew.metadata.iptc

Contains classes for the extraction and modelling of IPTC metadata.

Uses of IptcDirectory in com.drew.metadata.iptc

Constructors in com.drew.metadata.iptc with parameters of type IptcDirectory

Constructor and Description

IptcDescriptor(IptcDirectory directory)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2003-2012 Drew Noakes. All Rights Reserved.


text:
SPEC_BEGIN(CJMUSICGENRESPEC)

describe(@"Music Genre Model", ^{
  NSDictionary *stub = @{
                         @"id": @1,
                         @"parentId": @50,
                         @"name": @"House",
                         @"inferred": @NO
                         };

  __block CJMusicGenre *genre;
  beforeEach(^{
    genre = [[CJMusicGenre alloc] initWithInfo:stub];
  });

  describe(@".musicGenreWithInfo:", ^{
    it(@"Returns a new instance of a CJMusicGenre with the provided info", ^{
      genre = [CJMusicGenre musicGenreWithInfo:stub];

      [[genre.Id should] equal:stub[@"id"]];
    });
  });

  context(@"Mapping", ^{
    describe(@"#Id", ^{
      it(@"produces a correct mapping", ^{
        [[genre.Id should] equal:stub[@"id"]];
      });
    });

    describe(@"#parentId", ^{
      it(@"produces a correct mapping", ^{
        [[genre.parentId should] equal:stub[@"parentId"]];
      });
    });

    describe(@"#name", ^{
      it(@"produces a correct mapping", ^{
        [[genre.name should] equal:stub[@"name"]];
      });
    });

    describe(@"#inferred", ^{
      it(@"produces a correct mapping", ^{
        [[theValue(genre.inferred) should] equal:stub[@"inferred"]];
      });
    });
  });
});

SPEC_END


text:
module Forem
  class ModerationController < Forem::ApplicationController
    before_filter :ensure_moderator_or_admin

    helper 'forem/posts'

    def index
      @posts = forum.posts.pending_review.topic_not_pending_review
      @topics = forum.topics.pending_review
    end

    def posts
      Post.moderate!(params[:posts] || [])
      flash[:notice] = t('forem.posts.moderation.success')
      redirect_to :back
    end

    def topic
      if params[:topic]
        topic = forum.topics.find(params[:topic_id])
        topic.moderate!(params[:topic][:moderation_option])
        flash[:notice] = t("forem.topic.moderation.success")
      else
        flash[:error] = t("forem.topic.moderation.no_option_selected")
      end
      redirect_to :back
    end

    private

    def forum
      @forum = Forum.find(params[:forum_id])
    end

    helper_method :forum

    def ensure_moderator_or_admin
      if !forem_admin? && !forum.moderator?(forem_user)
        raise CanCan::AccessDenied
      end
    end

  end
end


text:
package org.zaproxy.zap.view;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.parosproxy.paros.extension.AbstractPanel;
import org.parosproxy.paros.extension.option.OptionsParamView;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.view.TabbedPanel;
import org.zaproxy.zap.utils.DisplayUtils;

/**
 * A tabbed panel that adds the option to hide individual tabs via a cross button on the tab.
 */
public class TabbedPanel2 extends TabbedPanel {

	private static final long serialVersionUID = 1L;

	private List<Component> fullTabList = new ArrayList<>();
	private List<Component> removedTabList = new ArrayList<>();

	private static final Icon PLUS_ICON = new ImageIcon(
			TabbedPanel2.class.getResource("/resource/icon/fugue/plus.png"));

	// A fake component that never actually get displayed - used for the 'hidden tab list tab'
	private Component hiddenComponent = new JLabel();

	private final Logger logger = Logger.getLogger(TabbedPanel2.class);

	private int prevTabIndex = -1;

	public TabbedPanel2() {
		super();

		this.addChangeListener(new ChangeListener() {
		    @Override
		    public void stateChanged(ChangeEvent e) {
		    	setCloseButtonStates();
		    	if (getSelectedComponent() != null && getSelectedComponent().equals(hiddenComponent)) {
		    		// The 'hidden tab list tab' has been selected - this is a special case
		    		if (prevTabIndex == indexOfComponent(hiddenComponent)) {
		    			// Happens when we delete the tab to the left of the hidden one
		    			setSelectedIndex(prevTabIndex-1);
		    		} else {
		    			// Hidden tab list tab selected - show popup and select previous tab
		    			setSelectedIndex(prevTabIndex);
		    			showHiddenTabPopup();
		    		}
		    	} else {
		    		prevTabIndex = getSelectedIndex();
		    	}
		    }
		});
	}

	/**
	 * Show a popup containing a list of all of the hidden tabs - selecting one will reveal that tab
	 */
	private void showHiddenTabPopup() {
		JPopupMenu menu = new JPopupMenu();
		if (getMousePosition() == null) {
			// Startup
			return;
		}
		// Sort the list so the tabs are always in alphabetic order
		Collections.sort(this.removedTabList, new Comparator<Component>(){
			@Override
			public int compare(Component o1, Component o2) {
				return o1.getName().compareTo(o2.getName());
			}});

		for (Component c : this.removedTabList) {
			if (c instanceof AbstractPanel) {
				final AbstractPanel ap = (AbstractPanel)c;
				JMenuItem mi = new JMenuItem(ap.getName());
				mi.setIcon(ap.getIcon());
				mi.addActionListener(new ActionListener(){
					@Override
					public void actionPerformed(ActionEvent e) {
						setVisible(ap, true);
						ap.setTabFocus();
					}});
				menu.add(mi);
			}
		}
		menu.show(this, this.getMousePosition().x, this.getMousePosition().y);
	}

	/**
	 * @deprecated (2.5.0) The implementation is not correct, not all state is correctly cloned.
	 */
	@Deprecated
	@SuppressWarnings("javadoc")
	public TabbedPanel2 clone(TabbedPanel2 tabbedPanel) {
		TabbedPanel2 t = new TabbedPanel2();
		t.fullTabList = new ArrayList<>(tabbedPanel.fullTabList);
		t.removedTabList = new ArrayList<>(tabbedPanel.removedTabList);
		return t;
	}

	private void setCloseButtonStates() {
		// Hide all 'close' buttons except for the selected tab
        for (int i = 0; i < this.getTabCount(); i++) {
        	Component tabCom = this.getTabComponentAt(i);
        	if (tabCom != null && tabCom instanceof TabbedPanelTab) {
        		TabbedPanelTab jp = (TabbedPanelTab) tabCom;
        		jp.setEnabled(i == getSelectedIndex());
        	}
        }
	}

	public void pinVisibleTabs() {
        for (int i = 0; i < this.getTabCount(); i++) {
        	Component tabCom = this.getTabComponentAt(i);
        	if (tabCom != null && tabCom instanceof TabbedPanelTab && tabCom.isVisible()) {
        		TabbedPanelTab jp = (TabbedPanelTab) tabCom;
        		jp.setPinned(true);
        		this.saveTabState(jp.getAbstractPanel());
        	}
        }
	}

	public void unpinTabs() {
        for (int i = 0; i < this.getTabCount(); i++) {
        	Component tabCom = this.getTabComponentAt(i);
        	if (tabCom != null && tabCom instanceof TabbedPanelTab && tabCom.isVisible()) {
        		TabbedPanelTab jp = (TabbedPanelTab) tabCom;
        		jp.setPinned(false);
        		this.saveTabState(jp.getAbstractPanel());
        	}
        }
	}

	/**
	 * Returns a name save to be used in the XML config file
	 * @param str
	 * @return
	 */
	private String safeName(String str) {
		return str.replaceAll("[^A-Za-z0-9]", "");

	}

	private boolean isTabPinned(Component c) {
		boolean showByDefault = false;
		if (c instanceof AbstractPanel) {
			showByDefault = ((AbstractPanel)c).isShowByDefault();
		}
		return Model.getSingleton().getOptionsParam().getConfig().getBoolean(
				OptionsParamView.TAB_PIN_OPTION + "." + safeName(c.getName()), showByDefault);

	}

	protected void saveTabState(AbstractPanel ap) {
		if (ap == null) {
			return;
		}
		Model.getSingleton().getOptionsParam().getConfig().setProperty(
				OptionsParamView.TAB_PIN_OPTION + "." + safeName(ap.getName()), ap.isPinned());
		try {
			Model.getSingleton().getOptionsParam().getConfig().save();
		} catch (ConfigurationException e) {
			logger.error(e.getMessage(), e);
		}
	}

	/*
	 * Returns true if the specified component is a visible tab panel (typically an AbstractPanel)
	 */
	public boolean isTabVisible(Component c) {
		if (! this.fullTabList.contains(c)) {
			// Not a known tab
			return false;
		}
		return ! this.removedTabList.contains(c);
	}

	public void setVisible(Component c, boolean visible) {
		if (visible) {
			if (this.removedTabList.contains(c)) {

				if (c instanceof AbstractPanel) {
					// Dont use the addTab(AbstractPanel) methods as we need to force visibility
					AbstractPanel panel = (AbstractPanel)c;
					this.addTab(c.getName(), panel.getIcon(), panel, panel.isHideable(), true, panel.getTabIndex());
				} else {
					// Work out the index to add it back in
					int index = this.fullTabList.indexOf(c);
					while (index >= 0) {
						if (index > 0 && ! this.removedTabList.contains(this.fullTabList.get(index -1))) {
							// Found the first preceding tab that isnt hidden
							break;
						}
						index--;
					}

					this.addTab(c.getName(), null, c, true, true, index);
				}
				this.removedTabList.remove(c);
			}

		} else {
			if (! this.removedTabList.contains(c)) {
				remove(c);
				this.removedTabList.add(c);
			}
		}
		handleHiddenTabListTab();
	}

	@Override
	public void addTab(String title, Icon icon, final Component c) {
		if (c instanceof AbstractPanel) {
			this.addTab((AbstractPanel)c);
		} else {
			this.addTab(title, icon, c, false, true, this.getTabCount());
		}
	}

	public void addTab(AbstractPanel panel) {
		boolean visible = ! panel.isHideable() || this.isTabPinned(panel);
		this.addTab(panel.getName(), panel.getIcon(), panel, panel.isHideable(), visible, panel.getTabIndex());

	}

	public void addTab(String title, Icon icon, final Component c, boolean hideable, boolean visible, int index) {
		if (c instanceof AbstractPanel) {
			((AbstractPanel)c).setParent(this);
			((AbstractPanel)c).setTabIndex(index);
			((AbstractPanel)c).setHideable(hideable);
		}

		if (index == -1 || index > this.getTabCount()) {
			index = this.getTabCount();
		}
		if (icon instanceof ImageIcon) {
			icon = DisplayUtils.getScaledIcon((ImageIcon)icon);
		}

		super.insertTab(title, icon, c, c.getName(), index);

		if ( ! this.fullTabList.contains(c)) {
			this.fullTabList.add(c);
		}

		int pos = this.indexOfComponent(c);
		// Now assign the component for the tab

		this.setTabComponentAt(pos, new TabbedPanelTab(this, title, icon, c, hideable, this.isTabPinned(c)));

		if (! visible) {
			setVisible(c, false);
		} else {
			this.removedTabList.remove(c);
		}

		handleHiddenTabListTab();

		if ((index == 0 || getTabCount() == 1) && indexOfComponent(c) != -1) {
			// Its now the first one, give it focus
			setSelectedComponent(c);
		}
	}

	private void handleHiddenTabListTab() {
		if (indexOfComponent(hiddenComponent) >= 0) {
			// Tab is showing, remove it - it might not be needed or may no longer be at the end
			super.remove(hiddenComponent);
		}
		if (this.removedTabList.size() > 0) {
			// Only re-add tab if there are hidden ones
			super.addTab("", PLUS_ICON, hiddenComponent);
		}
	}

	/**
	 * Temporarily lock/unlock the specified tab, eg if its active and mustnt be closed.
	 * Locked (AbstractPanel) tabs will not have the pin/close tab buttons displayed
	 * @param panel
	 * @param hideable
	 */
	public void setTabLocked(AbstractPanel panel, boolean lock) {
        for (int i = 0; i < this.getTabCount(); i++) {
        	Component tabCom = this.getTabComponentAt(i);
        	if (tabCom != null && tabCom instanceof TabbedPanelTab && tabCom.isVisible()) {
        		TabbedPanelTab jp = (TabbedPanelTab) tabCom;
        		if (panel.equals(jp.getAbstractPanel())) {
            		jp.setLocked(!lock);
        		}
        	}
        }
	}

    @Override
    public void setIconAt(int index, Icon icon) {
    	Component tabCom = this.getTabComponentAt(index);
    	if (tabCom != null && tabCom instanceof JPanel) {
    		Component c = ((JPanel)tabCom).getComponent(0);
			if (c != null && c instanceof JLabel) {
				((JLabel)c).setIcon(icon);
			}
    	}
    }

    /**
     * Set the title of the tab when hiding/showing tab names.
     */
    @Override
    public void setTitleAt(int index, String title) {
    	Component tabCom = this.getTabComponentAt(index);
    	if (tabCom != null && tabCom instanceof JPanel) {
    		Component c = ((JPanel)tabCom).getComponent(0);
			if (c != null && c instanceof JLabel) {
				((JLabel)c).setText(title);
			}
    	}
      else {
        super.setTitleAt(index, title);
      }
    }

	public List<Component> getTabList() {
		return Collections.unmodifiableList(this.fullTabList);
	}

	public List<Component> getSortedTabList() {
		List<Component> copy = new ArrayList<Component>(this.fullTabList);
		Collections.sort(copy, new Comparator<Component>(){
			@Override
			public int compare(Component o1, Component o2) {
				return o1.getName().compareTo(o2.getName());
			}});
		return copy;
	}

	public void removeTab(AbstractPanel panel) {
		this.remove(panel);
		this.fullTabList.remove(panel);
		if (this.removedTabList.remove(panel)) {
			handleHiddenTabListTab();
		}
	}

	@Override
	public void removeAll() {
		super.removeAll();

		removedTabList.clear();
		removedTabList.addAll(fullTabList);

		handleHiddenTabListTab();
	}

  /**
   * Sets whether or not the tab names should be shown.
   *
   * @param showTabNames {@code true} if the tab names should be shown, {@code false} otherwise.
   * @since 2.4.0
   */
  public void setShowTabNames(boolean showTabNames) {
        for (int i = 0; i < getTabCount(); i++) {
            String title = showTabNames ? getComponentAt(i).getName() : "";
            setTitleAt(i, title);
        }
    }

    /**
     * {@inheritDoc}
     *

     * Overridden to call the method {@code AbstractPanel#tabSelected()} on the currently selected {@code AbstractPanel}, if
     * any.
     *
     * @see AbstractPanel#tabSelected()
     */
    @Override
    protected void fireStateChanged() {
        super.fireStateChanged();

        Component comp = getSelectedComponent();
        if (comp instanceof AbstractPanel) {
            ((AbstractPanel) comp).tabSelected();
        }
    }

    /**
     * Returns true if the tab is 'active' - ie is being used for anything.
     * This method always returns false so must be overriden to be changed
     *
     * @return {@code true} if the tab is active, {@code false} otherwise
     */
    public boolean isActive() {
    	return false;
    }

    /**
     * Gets all the {@code AbstractPanel}s.
     *
     * @return a {@code List} containing all the panels
     * @since 2.5.0
     * @see #getVisiblePanels()
     */
    public List<AbstractPanel> getPanels() {
        List<AbstractPanel> panels = new ArrayList<>();
        for (Component component : fullTabList) {
            if (component instanceof AbstractPanel) {
                panels.add((AbstractPanel) component);
            }
        }
        return panels;
    }

    /**
     * Gets all the {@code AbstractPanel}s that are currently visible.
     *
     * @return a {@code List} containing all the visible panels
     * @since 2.5.0
     * @see #getPanels()
     */
    public List<AbstractPanel> getVisiblePanels() {
        List<AbstractPanel> panels = getPanels();
        for (Iterator<AbstractPanel> it = panels.iterator(); it.hasNext();) {
            if (removedTabList.contains(it.next())) {
                it.remove();
            }
        }
        return panels;
    }

    /**
     * Sets the given {@code panels} as visible, while hiding the remaining panels.
     *

     * Any panel that cannot be hidden (per {@link AbstractPanel#isHideable()} and {@link AbstractPanel#isPinned()}) will still
     * be shown, even if the panel was not in the given {@code panels}, moreover {@code panels} that are not currently added to
     * this tabbed panel are ignored.
     *
     * @param panels the panels that should be visible
     * @since 2.5.0
     * @see #getVisiblePanels()
     */
    public void setVisiblePanels(List<AbstractPanel> panels) {
        removeAll();

        for (Component component : fullTabList) {
            if (panels.contains(component)) {
                setVisible(component, true);
            } else if (component instanceof AbstractPanel) {
                AbstractPanel ap = (AbstractPanel) component;
                if (!canHidePanel(ap)) {
                    setVisible(component, true);
                }
            }
        }

        if (getSelectedComponent() == null && getTabCount() > 0) {
            setSelectedIndex(0);
        }
    }

    /**
     * Sets whether or not the panels should be visible.
     *

     * {@link AbstractPanel#isHideable() Non-hideable} and {@link AbstractPanel#isPinned() pinned} panels are not affected by
     * this call, when set to not be visible.
     *
     * @param visible {@code true} if all panels should be visible, {@code false} otherwise.
     * @since 2.5.0
     * @see #getVisiblePanels()
     */
    public void setPanelsVisible(boolean visible) {
        for (Component component : fullTabList) {
            if (component instanceof AbstractPanel) {
                AbstractPanel ap = (AbstractPanel) component;
                boolean canChangeVisibility = true;
                if (!visible) {
                    canChangeVisibility = canHidePanel(ap);
                }

                if (canChangeVisibility) {
                    setVisible(component, visible);
                }
            }
        }
    }

    /**
     * Tells whether or not the given panel can be hidden.
     *

     * A panel can be hidden if it is {@link AbstractPanel#isHideable() hideable} and it's not {@link AbstractPanel#isPinned()
     * pinned}.
     *
     * @param panel the panel to be checked
     * @return {@code true} if the panel can be hidden, {@code false} otherwise
     */
    private static boolean canHidePanel(AbstractPanel panel) {
        return panel.isHideable() && !panel.isPinned();
    }

}


text:
require 'test_helper'

class Messages::SearchesControllerTest < ActionController::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
<?php

declare(strict_types=1);

namespace MovingImage\Client\VMPro\Collection;

use Doctrine\Common\Collections\ArrayCollection;
use JMS\Serializer\Annotation as JMS;
use MovingImage\Meta\Interfaces\ChannelInterface;

class ChannelCollection
{
    /**
     * @var int
     * @JMS\Type("integer")
     * @JMS\SerializedName("totalCount")
     */
    private $totalCount;

    /**
     * @var ArrayCollection<ChannelInterface>
     * @JMS\Type("ArrayCollection<MovingImage\Client\VMPro\Entity\Channel>")
     */
    private $channels;

    /**
     * @param ArrayCollection<ChannelInterface> $channels
     */
    public function __construct(int $totalCount, ArrayCollection $channels)
    {
        $this->totalCount = $totalCount;
        $this->channels = $channels;
    }

    public function getTotalCount(): int
    {
        return $this->totalCount;
    }

    /**
     * @return ArrayCollection<ChannelInterface>
     */
    public function getChannels(): ArrayCollection
    {
        return $this->channels;
    }

    public function setTotalCount(int $totalCount): ChannelCollection
    {
        $this->totalCount = $totalCount;

        return $this;
    }

    /**
     * @param ArrayCollection<ChannelInterface> $channels
     */
    public function setChannels(ArrayCollection $channels): ChannelCollection
    {
        $this->channels = $channels;

        return $this;
    }
}


text:
#include <string.h>
#include <stdlib.h>
// nice public domain implementations at http://en.wikibooks.org/wiki/C_Programming/Strings

// from http://clc-wiki.net/wiki/strncpy, public domain
char* strncpy(char* restrict dest, const char* restrict src, size_t n) {
	char *ret = dest;
	do {
		if (!n--) {
			return ret;
		}
	} while (*dest++ = *src++);
	while (n--) {
		*dest++ = 0;
	}
	return ret;
}

size_t strlen(const char * str) {
    const char *s;
    for (s = str; *s; ++s);
    return(s - str);
}

void* memset (void* dest, int value, size_t len) {
	unsigned char *ptr = (unsigned char*)dest;
	while (len-- > 0) {
		*ptr++ = value;
	}
	return dest;
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings
void *memchr(const void *s, int c, size_t n) {
	const unsigned char *src = s;
	unsigned char uc = c;
	while (n-- != 0) {
		if (*src == uc) {
			return (void *) src;
		}
		src++;
	}
	return NULL;
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings
size_t strcspn(const char *s1, const char *s2) {
	const char *sc1;
	for (sc1 = s1; *sc1 != '\0'; sc1++)
		if (strchr(s2, *sc1) != NULL)
			return (sc1 - s1);
	return sc1 - s1;            /* terminating nulls match */
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings
char *strpbrk(const char *s1, const char *s2) {
	const char *sc1;
	for (sc1 = s1; *sc1 != '\0'; sc1++)
		if (strchr(s2, *sc1) != NULL)
			return (char *)sc1;
	return NULL;                /* terminating nulls match */
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings
size_t strspn(const char *s1, const char *s2) {
	const char *sc1;
	for (sc1 = s1; *sc1 != '\0'; sc1++)
		if (strchr(s2, *sc1) == NULL)
			return (sc1 - s1);
	return sc1 - s1;            /* terminating nulls don't match */
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings
char *strstr(const char *haystack, const char *needle) {
	size_t needlelen;
	/* Check for the null needle case.  */
	if (*needle == '\0')
		return (char *) haystack;
	needlelen = strlen(needle);
	for (; (haystack = strchr(haystack, *needle)) != NULL; haystack++)
		if (strncmp(haystack, needle, needlelen) == 0)
			return (char *) haystack;
	return NULL;
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings
char *strtok_r(char *s, const char *delimiters, char **lasts) {
	char *sbegin, *send;
	sbegin = s ? s : *lasts;
	sbegin += strspn(sbegin, delimiters);
	if (*sbegin == '\0') {
		*lasts = "";
		return NULL;
	}
	send = sbegin + strcspn(sbegin, delimiters);
	if (*send != '\0')
		*send++ = '\0';
	*lasts = send;
	return sbegin;
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings
char *strtok(char *restrict s1, const char *restrict delimiters) {
	static char *ssave = "";
	return strtok_r(s1, delimiters, &ssave);
}

int strcmp (const char * s1, const char * s2) {
    for(; *s1 == *s2; ++s1, ++s2)
        if(*s1 == 0)
            return 0;
    return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
}

void *memmove(void *s1, const void *s2, size_t n) {
	char* tmp = (char*)malloc(n);
	memcpy(tmp, s2, n);
	memcpy(s1, tmp, n);
	free(tmp);
	return s1;
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings#The_strcat_function
char *strchr(const char *s, int c) {
	/* Scan s for the character.  When this loop is finished,
	s will either point to the end of the string or the
	character we were looking for.  */
	while (*s != '\0' && *s != (char)c)
		s++;
	return ( (*s == c) ? (char *) s : NULL );
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings#The_strncmp_function
int strncmp(const char *s1, const char *s2, size_t n) {
	unsigned char uc1, uc2;
	/* Nothing to compare?  Return zero.  */
	if (n == 0)
		return 0;
	/* Loop, comparing bytes.  */
	while (n-- > 0 && *s1 == *s2) {
	/* If we've run out of bytes or hit a null, return zero
	since we already know *s1 == *s2.  */
		if (n == 0 || *s1 == '\0')
			return 0;
		s1++;
		s2++;
	}
	uc1 = (*(unsigned char *) s1);
	uc2 = (*(unsigned char *) s2);
	return ((uc1 < uc2) ? -1 : (uc1 > uc2));
 }

char *(strrchr)(const char *s, int c) {
     const char *last = NULL;
     /* If the character we're looking for is the terminating null,
        we just need to look for that character as there's only one
        of them in the string.  */
     if (c == '\0')
         return strchr(s, c);
     /* Loop through, finding the last match before hitting NULL.  */
     while ((s = strchr(s, c)) != NULL) {
         last = s;
         s++;
     }
     return (char *) last;
 }

// from http://www.danielvik.com/2010/02/fast-memcpy-in-c.html
// by Daniel Vik
void* memcpy(void* dest, const void* src, size_t count) {
	char* dst8 = (char*)dest;
	char* src8 = (char*)src;

	while (count--) {
		*dst8++ = *src8++;
	}
	return dest;
}

// this is public domain
int memcmp(const void *s1, const void *s2, size_t n) {
	const unsigned char *us1 = (const unsigned char *) s1;
	const unsigned char *us2 = (const unsigned char *) s2;
	while (n-- != 0) {
		if (*us1 != *us2) {
			return (*us1 < *us2) ? -1 : +1;
		}
		us1++;
		us2++;
	}
	return 0;
}

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings#The_strcat_function
char *strcat(char *restrict s1, const char *restrict s2) {
	char *s = s1;
	/* Move s so that it points to the end of s1.  */
	while (*s != '\0')
		s++;
	/* Copy the contents of s2 into the space at the end of s1.  */
	strcpy(s, s2);
	return s1;
 }

// public domain implementation from http://en.wikibooks.org/wiki/C_Programming/Strings#The_strncat_function
char *strncat(char *restrict s1, const char *restrict s2, size_t n) {
	char *s = s1;
	/* Loop over the data in s1.  */
	while (*s != '\0')
		s++;
	/* s now points to s1's trailing null character, now copy
	up to n bytes from s1 into s stopping if a null character
	is encountered in s2.
	It is not safe to use strncpy here since it copies EXACTLY n
	characters, NULL padding if necessary.  */
	while (n != 0 && (*s = *s2++) != '\0') {
		n--;
		s++;
	}
	*s = '\0'; // CME: fixed problem here; read memory and was comparing
	return s1;
}


text:
import React from 'react'
import {mount} from 'enzyme'
import {expect} from 'chai'

import App from '../../components/App.react'

describe('App', () => {
    it('should render', () => {
        let location = {
            pathname: '/'
        }

        let app = mount(
            <App
                children={null}
                location={location} />
        )
        expect(app).to.exist
    })
})


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 ~ Copyright (c) 2010-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ Licensed under the Apache License, Version 2.0 (the "License");
 ~ you may not use this file except in compliance with the License.
 ~ You may obtain a copy of the License at
 ~
 ~      http://www.apache.org/licenses/LICENSE-2.0
 ~
 ~ Unless required by applicable law or agreed to in writing, software
 ~ distributed under the License is distributed on an "AS IS" BASIS,
 ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ~ See the License for the specific language governing permissions and
 ~ limitations under the License.
-->

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

    <parent>
        <groupId>org.wso2.carbon.mobile.appmgt</groupId>
        <artifactId>carbon-mobile-appmgt</artifactId>
        <version>2.0.0-SNAPSHOT</version>
	<relativePath>../../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>org.wso2.carbon.appmgt.rest.api.publisher.feature</artifactId>
    <packaging>pom</packaging>
    <name>WSO2 Carbon - APP Manager - Publisher ReST API Feature</name>
    <url>http://wso2.org</url>
    <description>This feature contains the artifacts for the Publisher ReST API</description>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon.mobile.appmgt</groupId>
            <artifactId>org.wso2.carbon.appmgt.rest.api.publisher</artifactId>
            <type>war</type>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.wso2.carbon.mobile.appmgt</groupId>
                                    <artifactId>org.wso2.carbon.appmgt.rest.api.publisher</artifactId>
                                    <overWrite>true</overWrite>
                                    <type>war</type>
                                    <outputDirectory>${basedir}/src/main/resources/</outputDirectory>
                                    <destFileName>api#appm#publisher#v1.1.war</destFileName>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.wso2.maven</groupId>
                <artifactId>carbon-p2-plugin</artifactId>
                <executions>
                    <execution>
                        <id>p2-feature-generation</id>
                        <phase>package</phase>
                        <goals>
                            <goal>p2-feature-gen</goal>
                        </goals>
                        <configuration>
                            <id>org.wso2.carbon.appmgt.rest.api.publisher</id>
                            <propertiesFile>../etc/feature.properties</propertiesFile>
                            <adviceFile>
                                <properties>
                                    <propertyDef>org.wso2.carbon.p2.category.type:server
                                    </propertyDef>
                                    <propertyDef>org.eclipse.equinox.p2.type.group:false
                                    </propertyDef>
                                </properties>
                            </adviceFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>delete-copied-war-files</id>
                        <phase>package</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <delete file="src/main/resources/api#appm#publisher#v1.1.war" />
                            </tasks>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

</project>


text:
const { assemble } = require('@articulate/funky')
const { expect } = require('chai')
const http = require('http')
const { is, pipe, pipeP, prop, tap } = require('ramda')
const { Readable } = require('stream')
const request = require('supertest')

const { bufferBody, json, mount, routes } = require('..')

describe('bufferBody', () => {
  const app =
    routes({
      '/bufferme': pipeP(
        bufferBody,
        prop('body'),
        assemble({
          isReadable: is(Readable),
          isString: is(String)
        }),
        json
      ),

      '/lambda': pipe(
        prop('body'),
        assemble({
          isReadable: is(Readable),
          isString: is(String)
        }),
        json
      )
    })

  const cry =
    tap(console.error)

  describe('with { lambda: false } (default)', () => {
    const server = http.createServer(mount({ app, cry }))
    const agent = request.agent(server)

    it('buffers the body', () =>
      agent.post('/bufferme')
        .type('text/plain')
        .send('body')
        .expect(200, {
          isReadable: false,
          isString: true
        })
    )

    it('does not buffer when content-length is zero', () =>
      agent.post('/bufferme')
        .type('text/plain')
        .send('')
        .expect(200, {
          isReadable: true,
          isString: false
        })
    )
  })

  describe('with { lambda: true }', () => {
    const handler = mount({ app, cry, lambda: true })

    it('the body is already buffered by AWS', () =>
      handler({
        httpMethod: 'POST',
        path: '/lambda',
        headers: {
          'content-type': 'text/plain'
        },
        body: 'body'
      }).then(res =>
        expect(res).to.include({
          body: '{"isReadable":false,"isString":true}',
          statusCode: 200
        })
      )
    )
  })
})


text:
package com.clean;

import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by tonghui on 2015/9/12.
 */
public class DownloadImages implements Runnable {

    private List<String> images = new ArrayList<String>();

    public DownloadImages(List<String>images) {
        this.images = images;
    }

    public void run() {

        for (String image : images) {
                Utils.downloadImage(image);
        }
    }
}


text:
@interface LLCreateCommandTableViewController ()
- (void)setupToolbar;
- (LLOptionPrototype *)optionPrototypeAtIndexPath:(NSIndexPath *)indexPath;
- (LLOptionPrototype *)optionPrototypeAtIndex:(int)index;
- (LLOptionValuePrototype *)optionValuePrototypeAtIndexPath:(NSIndexPath *)indexPath;
- (void)updateTableViewAndReloadOptionValueAtIndexPath:(NSIndexPath *)indexPath withValue:(id)value;
@end

@implementation LLCreateCommandTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = self.commandPrototype.desc;
    [self setupToolbar];

    [self.tableView registerClass:[LLOptionValuePrototypeCell class] forCellReuseIdentifier:IDENTIFIER_OPTION_VALUE_PROTOTYPE_CELL];
    [self.tableView registerNib:[UINib nibWithNibName:NIB_PREFILL_OPTION_VALUE_PROTOTYPE_CELL bundle:nil] forCellReuseIdentifier:IDENTIFIER_PREFILL_OPTION_VALUE_PROTOTYPE_CELL];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setToolbarHidden:YES animated:YES];
}

- (void)dealloc {
    self.likeReceiptHelper = nil;
    self.commandPrototype = nil;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [self.commandPrototype.options count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    LLOptionPrototype *optionPrototype = [self.commandPrototype.options objectAtIndex:section];
    return [optionPrototype.possibleValues count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [[self.commandPrototype.options objectAtIndex:section] displayName];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LLOptionPrototype *option = [self optionPrototypeAtIndexPath:indexPath];
    LLOptionValuePrototype *optionValuePrototype = [self optionValuePrototypeAtIndexPath:indexPath];

    // Right now LLPrefillOptionValuePrototypeCell only supports string option value types
    if ([optionValuePrototype.key isEqualToString:OPTION_VALUE_PREFILL] && [LLUtils isStringOptionValueType:option.valueType]) {
        LLOptionPrototype *optionPrototype = [self optionPrototypeAtIndexPath:indexPath];

        LLPrefillOptionValuePrototypeCell *cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER_PREFILL_OPTION_VALUE_PROTOTYPE_CELL forIndexPath:indexPath];
        ((LLPrefillOptionValuePrototypeCell *) cell).delegate = self;
        [cell updateViewWithOptionValuePrototype:optionValuePrototype andValueType:optionPrototype.valueType atIndexPath:indexPath];
        return cell;
    } else {
        LLOptionValuePrototypeCell *cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER_OPTION_VALUE_PROTOTYPE_CELL forIndexPath:indexPath];
        [cell updateViewWithOptionValuePrototype:optionValuePrototype atIndexPath:indexPath];
        return cell;
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

#pragma mark - Table view delegate

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LLOptionPrototype *option = [self optionPrototypeAtIndexPath:indexPath];
    LLOptionValuePrototype *optionValuePrototype = [self optionValuePrototypeAtIndexPath:indexPath];

    if ([optionValuePrototype.key isEqualToString:OPTION_VALUE_PREFILL] && [LLUtils isStringOptionValueType:option.valueType]) {
        // Don't select prefill cells, since the UITextField is on top
        return nil;
    }
    return indexPath;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self updateTableViewAndReloadOptionValueAtIndexPath:indexPath withValue:nil];
}

#pragma mark - Prefill option value prototype cell delegate

- (void)onTextFieldDidEndEditing:(id)cell {
    LLPrefillOptionValuePrototypeCell *prefillCell = cell;
    NSIndexPath *indexPath = prefillCell.indexPath;
    NSString *value = prefillCell.textField.text;

    // Only update the option value prototype if text was set
    if ([value length] != 0) {
        [self updateTableViewAndReloadOptionValueAtIndexPath:indexPath withValue:value];
    }
}

#pragma mark - Like receipt helper delegate

- (void)onFinishedLiking {
    self.likeReceiptHelper = nil;
    [self showCheckmarkHUDWithLabelText:@"Added"];
}

- (void)onFailedLiking {
    self.likeReceiptHelper = nil;
    [self showTextHUDWithLabelText:@"Error. Try later"];
}

#pragma mark - Command Delegate

- (void)onFinishedCommand:(LLCommand *)command {
    [self showExecutedCommandHUD];
}

- (void)onStoppedCommand:(LLCommand *)command withErrorTitle:(NSString *)title andErrorDesc:(NSString *)desc {
    [self showErrorHUDWithTitle:title andDesc:desc];
}

#pragma mark - Instance methods

- (void)setupToolbar {
    UIBarButtonItem *flexibleSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *executeBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(executeCommand)];
    UIBarButtonItem *likeBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(likeCommand)];

    [self.navigationController setToolbarHidden:NO animated:YES];
    self.toolbarItems = [NSArray arrayWithObjects:flexibleSpaceBarButtonItem, likeBarButtonItem, flexibleSpaceBarButtonItem, executeBarButtonItem, flexibleSpaceBarButtonItem, nil];
}

- (void)executeCommand {
    [[LLCommandManager sharedInstance] executeFromCommandPrototype:self.commandPrototype withViewController:self andDelegate:self];
}

- (void)likeCommand {
    self.likeReceiptHelper = [[LLLikeCommandHelper alloc] init];
    [self.likeReceiptHelper likeCommandPrototype:self.commandPrototype withDelegate:self];
}

- (LLOptionPrototype *)optionPrototypeAtIndexPath:(NSIndexPath *)indexPath {
    return [self optionPrototypeAtIndex:indexPath.section];
}

- (LLOptionPrototype *)optionPrototypeAtIndex:(int)index {
    return [self.commandPrototype.options objectAtIndex:index];
}

- (LLOptionValuePrototype *)optionValuePrototypeAtIndexPath:(NSIndexPath *)indexPath {
    LLOptionPrototype *optionPrototype = [self optionPrototypeAtIndexPath:indexPath];
    LLOptionValuePrototype *optionValuePrototype = [[optionPrototype.possibleValues allValues] objectAtIndex:indexPath.row];
    return optionValuePrototype;
}

// @TODO is it a good name?
- (void)updateTableViewAndReloadOptionValueAtIndexPath:(NSIndexPath *)indexPath withValue:(id)value {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    LLOptionPrototype *option = [self optionPrototypeAtIndexPath:indexPath];
    LLOptionValuePrototype *optionValue = [self optionValuePrototypeAtIndexPath:indexPath];

    // Deselect all other option values if this option value will be selected and not an array option
    if (!optionValue.selected && option.dataType != DATA_ARRAY) {
        for (LLOptionValuePrototype *optionValue in option.possibleValues.allValues) {
            optionValue.selected = NO;
        }
    }

    // Toggle selected value
    optionValue.selected = !optionValue.selected;
    optionValue.value = value;

    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
}

@end


text:
namespace ui {

namespace {

// Saves gfx::Canvas state upon construction and automatically restores it when
// it goes out of scope.
class ScopedCanvasState {
 public:
  explicit ScopedCanvasState(gfx::Canvas* canvas) : canvas_(canvas) {
    canvas_->Save();
  }
  ~ScopedCanvasState() {
    canvas_->Restore();
  }

 private:
  gfx::Canvas* canvas_;
  DISALLOW_COPY_AND_ASSIGN(ScopedCanvasState);
};

bool ExceededDragThreshold(const gfx::Point& press_point,
                           const gfx::Point& event_point) {
  // TODO(beng): implement
  return true;
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// View, public:

View::View()
    : parent_owned_(true),
      visible_(true),
      enabled_(true),
      id_(-1),
      group_(-1),
      parent_(NULL),
      focusable_(false),
      next_focusable_view_(NULL),
      prev_focusable_view_(NULL),
      context_menu_controller_(NULL),
      drag_controller_(NULL) {
}

View::~View() {
  if (parent_)
    parent_->RemoveChildView(this, false);

  for (Views::const_iterator i(children_begin()); i != children_.end(); ++i) {
    (*i)->parent_ = NULL;
    if ((*i)->parent_owned())
      delete *i;
  }
}

// Size and disposition --------------------------------------------------------

gfx::Rect View::GetVisibleBounds() const {
  // TODO(beng):
  return bounds();
}

gfx::Rect View::GetContentsBounds() const {
  gfx::Rect rect(gfx::Point(), size());
  if (border_.get())
    rect.Inset(border_->insets());
  return rect;
}

void View::SetBounds(const gfx::Rect& bounds) {
  gfx::Rect old_bounds = bounds_;
  bounds_ = bounds;
  // TODO(beng): investigate usage of needs_layout_ in old View code.
  if (old_bounds != bounds_) {
    OnBoundsChanged();
    Layout();
  }
}

void View::SetOrigin(const gfx::Point& origin) {
  SetBounds(gfx::Rect(origin, size()));
}

void View::SetSize(const gfx::Size& size) {
  SetBounds(gfx::Rect(origin(), size));
}

void View::SetBorder(Border* border) {
  border_.reset(border);
}

void View::OnBoundsChanged() {
}

gfx::Size View::GetPreferredSize() const {
  return gfx::Size();
}

gfx::Size View::GetMinimumSize() const {
  return GetPreferredSize();
}

void View::SetLayoutManager(LayoutManager* layout_manager) {
  layout_manager_.reset(layout_manager);
}

void View::Layout() {
  // The layout manager handles all child layout if present.
  if (layout_manager_.get()) {
    layout_manager_->Layout(this);
  } else {
    std::for_each(children_begin(), children_end(),
                  std::mem_fun(&View::Layout));
  }
  // TODO(beng): needs_layout_? SchedulePaint()?
}

void View::SetVisible(bool visible) {
  if (visible != visible_) {
    visible_ = visible;
    // InvaldateRect() checks for view visibility before proceeding, so we need
    // to ask the parent to invalidate our bounds.
    if (parent_)
      parent_->InvalidateRect(bounds_);
  }
}

void View::SetEnabled(bool enabled) {
  if (enabled != enabled_) {
    enabled_ = enabled;
    Invalidate();
  }
}

// Attributes ------------------------------------------------------------------

View* View::GetViewByID(int id) {
  if (id_ == id)
    return this;
  for (Views::const_iterator i(children_begin()); i != children_end(); ++i) {
    View* view = (*i)->GetViewByID(id);
    if (view)
      return view;
  }
  return NULL;
}

void View::GetViewsInGroup(int group, Views* vec) {
  if (group_ == group)
    vec->push_back(const_cast<View*>(this));
  for (Views::const_iterator i(children_begin()); i != children_end(); ++i)
    (*i)->GetViewsInGroup(group, vec);
}

View* View::GetSelectedViewForGroup(int group_id) {
  // TODO(beng): implementme
  return NULL;
}

// Coordinate conversion -------------------------------------------------------

// static
void View::ConvertPointToView(const View& source,
                              const View& target,
                              gfx::Point* point) {
  const View* inner = NULL;
  const View* outer = NULL;
  if (source.Contains(target)) {
    inner = ⌖
    outer = &source;
  } else if (target.Contains(source)) {
    inner = &source;
    outer = ⌖
  }  // Note that we cannot do a plain "else" here since |source| and |target|
     // may be in different hierarchies with no relation.
  if (!inner)
    return;

  gfx::Point offset;
  for (const View* v = inner; v != outer; v = v->parent())
    offset.Offset(v->x(), v->y());
  // When target is contained by source, we need to subtract the offset.
  // When source is contained by target, we need to add the offset.
  int multiplier = (inner == &target) ? -1 : 1;
  point->Offset(multiplier * offset.x(), multiplier * offset.y());
}

// static
void View::ConvertPointToScreen(const View& source, gfx::Point* point) {
  const Widget* widget = source.GetWidget();
  if (widget) {
    ConvertPointToWidget(source, point);
    gfx::Point client_origin(widget->GetClientAreaScreenBounds().origin());
    point->Offset(client_origin.x(), client_origin.y());
  }
}

// static
void View::ConvertPointToWidget(const View& source, gfx::Point* point) {
  for (const View* v = &source; v; v = v->parent())
    point->Offset(v->x(), v->y());
}

// Tree operations -------------------------------------------------------------

const Widget* View::GetWidget() const {
  return parent() ? parent()->GetWidget() : NULL;
}

void View::AddChildView(View* view) {
  AddChildViewAt(view, children_size());
}

void View::AddChildViewAt(View* view, size_t index) {
  CHECK_NE(this, view) << "A view cannot be its own child.";

  // Remove the child from its current parent if any.
  if (view->parent())
    view->parent()->RemoveChildView(view, false);

  // TODO(beng): Move focus initialization to FocusManager.
  InitFocusSiblings(view, index);

  children_.insert(children_.begin() + index, view);
  view->parent_ = this;

  // Notify the hierarchy.
  NotifyHierarchyChanged(view, true);

  // TODO(beng): Notify other objects like tooltip, layout manager, etc.
  //             Figure out RegisterChildrenForVisibleBoundsNotification.
}

void View::RemoveChildView(View* view, bool delete_child) {
  Views::const_iterator i(std::find(children_begin(), children_end(), view));
  DCHECK(i != children_end());
  view->parent_ = NULL;
  children_.erase(i);
  NotifyHierarchyChanged(view, false);
  // TODO(beng): Notify other objects like tooltip, layout manager, etc.
  if (delete_child)
    delete view;
}

void View::RemoveAllChildViews(bool delete_children) {
  while (!children_.empty()) {
    RemoveChildView(children_.front(), delete_children);
    // TODO(beng): view deletion is actually more complicated in the old view.cc
    //             figure out why. (it uses a ScopedVector to accumulate a list
    //             of views to delete).
  }
}

bool View::Contains(const View& child) const {
  for (const View* v = &child; v; v = v->parent()) {
    if (v == this)
      return true;
  }
  return false;
}

// Painting --------------------------------------------------------------------

void View::Invalidate() {
  InvalidateRect(gfx::Rect(gfx::Point(), size()));
}

void View::InvalidateRect(const gfx::Rect& invalid_rect) {
  if (visible_ && parent_) {
    gfx::Rect r(invalid_rect);
    r.Offset(bounds_.origin());
    parent_->InvalidateRect(r);
  }
}

// Input -----------------------------------------------------------------------

bool View::HitTest(const gfx::Point& point) const {
  // TODO(beng): Hit test mask support.
  return gfx::Rect(gfx::Point(), size()).Contains(point);
}

// Accelerators ----------------------------------------------------------------

void View::AddAccelerator(const Accelerator& accelerator) {
}

void View::RemoveAccelerator(const Accelerator& accelerator) {
}

void View::RemoveAllAccelerators() {
}

// Focus -----------------------------------------------------------------------

FocusManager* View::GetFocusManager() {
  return const_cast<FocusManager*>(static_cast<const View*>(this)->
      GetFocusManager());
}

const FocusManager* View::GetFocusManager() const {
  const Widget* widget = GetWidget();
  return widget ? widget->GetFocusManager() : NULL;
}

FocusTraversable* View::GetFocusTraversable() {
  return NULL;
}

View* View::GetNextFocusableView() {
  return NULL;
}

View* View::GetPreviousFocusableView() {
  return NULL;
}

bool View::IsFocusable() const {
  return focusable_ && enabled_ && visible_;
}

bool View::HasFocus() const {
  const FocusManager* focus_manager = GetFocusManager();
  return focus_manager ? (focus_manager->focused_view() == this) : false;
}

void View::RequestFocus() {
  FocusManager* focus_manager = GetFocusManager();
  if (focus_manager && (focus_manager->focused_view() != this))
    focus_manager->SetFocusedView(this);
}

// Resources -------------------------------------------------------------------

ThemeProvider* View::GetThemeProvider() {
  Widget* widget = GetWidget();
  return widget ? widget->GetThemeProvider() : NULL;
}

////////////////////////////////////////////////////////////////////////////////
// View, protected:

// Tree operations -------------------------------------------------------------

void View::OnViewAdded(const View& parent, const View& child) {
}

void View::OnViewRemoved(const View& parent, const View& child) {
}

void View::OnViewAddedToWidget() {
}

void View::OnViewRemovedFromWidget() {
}

// Painting --------------------------------------------------------------------

void View::PaintChildren(gfx::Canvas* canvas) {
  std::for_each(children_begin(), children_end(),
                std::bind2nd(std::mem_fun(&View::Paint), canvas));
}

void View::OnPaint(gfx::Canvas* canvas) {
  // TODO(beng): investigate moving these function calls to Paint().
  OnPaintBackground(canvas);
  OnPaintFocusBorder(canvas);
  OnPaintBorder(canvas);
}

void View::OnPaintBackground(gfx::Canvas* canvas) {
}

void View::OnPaintBorder(gfx::Canvas* canvas) {
  if (border_.get())
    border_->Paint(this, canvas);
}

void View::OnPaintFocusBorder(gfx::Canvas* canvas) {
}

// Input -----------------------------------------------------------------------

View* View::GetEventHandlerForPoint(const gfx::Point& point) {
  for (Views::const_reverse_iterator i(children_rbegin()); i != children_rend();
       ++i) {
    View* child = *i;
    if (child->visible()) {
      gfx::Point point_in_child_coords(point);
      View::ConvertPointToView(*this, *child, &point_in_child_coords);
      if (child->HitTest(point_in_child_coords))
        return child->GetEventHandlerForPoint(point_in_child_coords);
    }
  }
  return this;
}

gfx::NativeCursor View::GetCursorForPoint(const gfx::Point& point) const {
  return NULL;
}

bool View::OnKeyPressed(const KeyEvent& event) {
  return true;
}

bool View::OnKeyReleased(const KeyEvent& event) {
  return true;
}

bool View::OnMouseWheel(const MouseWheelEvent& event) {
  return true;
}

bool View::OnMousePressed(const MouseEvent& event) {
  return true;
}

bool View::OnMouseDragged(const MouseEvent& event) {
  return true;
}

void View::OnMouseReleased(const MouseEvent& event) {
}

void View::OnMouseCaptureLost() {
}

void View::OnMouseMoved(const MouseEvent& event) {
}

void View::OnMouseEntered(const MouseEvent& event) {
}

void View::OnMouseExited(const MouseEvent& event) {
}

// Accelerators ----------------------------------------------------------------

bool View::OnAcceleratorPressed(const Accelerator& accelerator) {
  return false;
}

// Focus -----------------------------------------------------------------------

bool View::SkipDefaultKeyEventProcessing(const KeyEvent& event) const {
  return false;
}

bool View::IsGroupFocusTraversable() const {
  return true;
}

bool View::IsFocusableInRootView() const {
  // TODO(beng): kill this, replace with direct check in focus manager.
  return IsFocusable();
}

bool View::IsAccessibilityFocusableInRootView() const {
  // TODO(beng): kill this, replace with direct check in focus manager.
  return false;
}

FocusTraversable* View::GetPaneFocusTraversable() {
  // TODO(beng): figure out what to do about this.
  return NULL;
}

void View::OnFocus(const FocusEvent& event) {
}

void View::OnBlur(const FocusEvent& event) {
}

////////////////////////////////////////////////////////////////////////////////
// View, private:

void View::DragInfo::Reset() {
  possible_drag = false;
  press_point = gfx::Point();
}

void View::DragInfo::PossibleDrag(const gfx::Point& point) {
  possible_drag = true;
  press_point = point;
}

// Tree operations -------------------------------------------------------------

void View::NotifyHierarchyChanged(View* child, bool is_add) {
  // Notify the hierarchy up.
  for (View* v = parent(); v; v = v->parent())
    CallViewNotification(v, *child, is_add, false);

  // Notify the hierarchy down.
  bool has_widget = GetWidget() != NULL;
  if (!is_add) {
    // Because |child| has already been removed from |parent|'s child list, we
    // need to notify its hierarchy manually.
    child->NotifyHierarchyChangedDown(*child, is_add, has_widget);
  }
  NotifyHierarchyChangedDown(*child, is_add, has_widget);
}

void View::NotifyHierarchyChangedDown(const View& child,
                                      bool is_add,
                                      bool has_widget) {
  CallViewNotification(this, child, is_add, has_widget);
  for (Views::const_iterator i(children_begin()); i != children_end(); ++i)
    (*i)->NotifyHierarchyChangedDown(child, is_add, has_widget);
}

void View::CallViewNotification(View* target,
                                const View& child,
                                bool is_add,
                                bool has_widget) {
  if (is_add) {
    target->OnViewAdded(*this, child);
    if (has_widget)
      target->OnViewAddedToWidget();
  } else {
    target->OnViewRemoved(*this, child);
    if (has_widget)
      target->OnViewRemovedFromWidget();
  }
}

// Painting --------------------------------------------------------------------

void View::Paint(gfx::Canvas* canvas) {
  // Invisible views are not painted.
  if (!visible_)
    return;

  ScopedCanvasState canvas_state(canvas);
  if (canvas->ClipRectInt(x(), y(), width(), height())) {
    canvas->TranslateInt(x(), y());
    // TODO(beng): RTL
    ScopedCanvasState canvas_state(canvas);
    OnPaint(canvas);
    PaintChildren(canvas);
  }
}

// Input -----------------------------------------------------------------------

bool View::MousePressed(const MouseEvent& event, DragInfo* drag_info) {
  bool handled = OnMousePressed(event);
  // TODO(beng): deal with view deletion, see ProcessMousePressed() in old code.
  if (!enabled_)
    return handled;

  if (!event.IsOnlyLeftMouseButton() || !HitTest(event.location()) ||
      (GetDragOperations(event.location()) == DragDropTypes::DRAG_NONE))
    return handled || (event.IsRightMouseButton() && context_menu_controller_);

  drag_info->PossibleDrag(event.location());
  return true;
}

bool View::MouseDragged(const MouseEvent& event, DragInfo* drag_info) {
  if (drag_info->possible_drag &&
      ExceededDragThreshold(drag_info->press_point, event.location())) {
    if (!drag_controller_ ||
        drag_controller_->CanStartDrag(this, drag_info->press_point,
                                       event.location()))
      StartShellDrag(event, drag_info->press_point);
  } else if (OnMouseDragged(event)) {
    return true;
  }
  // TODO(beng): Handle view deletion from OnMouseDragged().
  return context_menu_controller_ || drag_info->possible_drag;
}

void View::MouseReleased(const MouseEvent& event) {
  OnMouseReleased(event);
  // TODO(beng): Handle view deletion from OnMouseReleased().
  if (context_menu_controller_ && event.IsOnlyRightMouseButton()) {
    gfx::Point location(event.location());
    if (HitTest(location)) {
      ConvertPointToScreen(*this, &location);
      context_menu_controller_->ShowContextMenu(this, location, true);
    }
  }
}

// Focus -----------------------------------------------------------------------

// TODO(beng): Move to FocusManager.
void View::InitFocusSiblings(View* view, size_t index) {
  if (children_empty()) {
    view->next_focusable_view_ = NULL;
    view->prev_focusable_view_ = NULL;
    return;
  }

  if (index != children_size()) {
    View* prev = children_[index]->GetPreviousFocusableView();
    view->prev_focusable_view_ = prev;
    view->next_focusable_view_ = children_[index];
    if (prev)
      prev->next_focusable_view_ = view;
    children_[index]->prev_focusable_view_ = view;
    return;
  }

  // We are inserting at the end, but the end of the child list may not be
  // the last focusable element. Let's try to find an element with no next
  // focusable element to link to.
  for (Views::const_iterator i(children_begin()); i != children_end(); ++i) {
    if (!(*i)->next_focusable_view_) {
      (*i)->next_focusable_view_ = view;
      view->next_focusable_view_ = NULL;
      view->prev_focusable_view_ = *i;
      return;
    }
  }

  // Hum... there is a cycle in the focus list. Let's just insert ourself
  // after the last child.
  View* prev = children_[index - 1];
  view->prev_focusable_view_ = prev;
  view->next_focusable_view_ = prev->next_focusable_view_;
  prev->next_focusable_view_->prev_focusable_view_ = view;
  prev->next_focusable_view_ = view;
}

// Drag & Drop -----------------------------------------------------------------

int View::GetDragOperations(const gfx::Point& point) {
  return drag_controller_ ?
      drag_controller_->GetDragOperations(this, point) :
      DragDropTypes::DRAG_NONE;
}

void View::WriteDragData(const gfx::Point& point, OSExchangeData* data) {
  drag_controller_->WriteDragData(this, point, data);
}

void View::StartShellDrag(const MouseEvent& event,
                          const gfx::Point& press_point) {
  // TODO(beng): system stuff.
}

}  // namespace ui


text:
function f(x) {
  // This function compiles into code that only throws a redeclaration
  // error. It contains no stack check and has no function body.
  const x = 0;
  return x;
}

function g() {
  f(0);
}

var exception = null;
var called = false;
var Debug = debug.Debug;
Debug.setBreakOnException();

function listener(event, exec_state, event_data, data) {
  if (event != Debug.DebugEvent.Exception) return;
  try {
    called = true;
    Debug.setBreakPoint(f, 1);
  } catch (e) {
    exception = e;
  }
}

Debug.setListener(listener);

assertThrows(g);
assertNull(exception);
assertTrue(called);


text:
package controllers.preview

import org.specs2.mutable._
import utils.WithJsBrowser
import utils.pageobjects.PageObjects
import utils.pageobjects.preview.PreviewPage

/**
 * Created by valtechuk on 16/10/2015.
 */
class PreviewSpec extends Specification {
  section("preview")
  "Preview page" should {
    "be presented with back button removed" in new WithJsBrowser with PageObjects {
      val page =  PreviewPage(context)
      page goToThePage()
      val source = page.source
      print( source )

      source must not contain("backButton")
    }
  }
  section("preview")
}


text:
function createPropertiesAssignment(count) {
  let result = "";
  for (let i = 0; i < count; i++) {
    result += "this.p"+i+" = undefined;";
  }
  return result;
}

function testSubclassProtoProperties(count) {
  const MyClass = eval(`(class MyClass {
    constructor() {
      ${createPropertiesAssignment(count)}
    }
  });`);

  class BaseClass {};
  class SubClass extends BaseClass {
    constructor() {
        super()
    }
  };

  const boundMyClass = MyClass.bind();
  %HeapObjectVerify(boundMyClass);

  SubClass.__proto__ = boundMyClass;
  var instance = new SubClass();

  %HeapObjectVerify(instance);
  // Create some more instances to complete in-object slack tracking.
  let results = [];
  for (let i = 0; i < 4000; i++) {
    results.push(new SubClass());
  }
  var instance = new SubClass();
  %HeapObjectVerify(instance);
}

for (let count = 0; count < 10; count++) {
  testSubclassProtoProperties(count);
}


text:
'use strict';

// Built-in modules
var fs = require('fs');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

// External modules
var async = require('async');
var extend = require('node.extend');
var Readable = require('stream').Readable || require('readable-stream').Readable;

// Internal modules
var encoder = require('./util/encoding');
var globber = require('./util/glob');
var validator = require('./util/validate');

// Utility
var slicer = Array.prototype.slice;

function arraysMatch(arr1, arr2) {
  if (arr1 && arr2 && arr1.length === arr2.length) {
    var matches = arr1.filter(function(e, i) {
      return e === arr2[i];
    });
    return matches.length === arr1.length;
  }
  return arr1 === arr2;
}

// A big frickin' mess... but aimed at performance by not reading the file more times than necessary
function processFile(filePath, callback, options) {
  /*jshint validthis:true */
  var processor = this;
  processor.emit('processing.start', {
    file: filePath
  });

  encoder.detectBom(filePath, function(err, bomName) {
    var status = 'good';

    if (err) {
      status = 'error';
      processor.emit('processing.error', {
        file: filePath,
        message: 'Skipping file with errors during encoding detection: ' + err
      });
      return callback(null, status);
    }
    else {
      var needsFixing = false;
      var lastByteSequenceWasCR = false;
      var bytesPerBom = encoder.getBytesPerBom(bomName);
      var bytesPerControlChar = encoder.getBytesPerControlChar(bomName);

      var transformBuffer = [];
      var tempBuffer = null;

      // Fast-forward past the BOM if present
      var onFirstReadable = function() {
        var bomBuffer = this.read(bytesPerBom);
        if (bomBuffer == null || bomBuffer.length !== bytesPerBom) {
          status = 'error';
          processor.emit('processing.error', {
            file: filePath,
            message: 'Skipping file with errors during read: Unable to read past the expected BOM'
          });
          return callback(null, status);
        }
      };
      var onReadable = function() {
        var data = this.read(),
            i = 0,
            len = data ? data.length : 0,
            cursor = i,
            buffer,
            isByteSequenceLF;
        for ( ; i < len; i += bytesPerControlChar) {
          buffer = slicer.call(data, i, i + bytesPerControlChar);

          // If we read less bytes than the minimum number necessary to register
          // as a complete character in this encoding, put them back on the front
          // of the read queue for the next read and then bail out.
          if (buffer.length < bytesPerControlChar) {
            if (!tempBuffer || !arraysMatch(buffer, tempBuffer)) {
              tempBuffer = buffer;
              // Save these rogue bytes to inspect on the next time around
              this.unshift(data.slice(i, i + buffer.length));
              // Break out of the loop
              break;
            }
            else {
              // This will prevent an infinite loop if the number of bytes in the file
              // is erroneous/irregular, e.g. a total of 7 bytes in a UTF-16 file.
              status = 'error';

              // Send a signal to cause early termination (i.e. trigger the 'end' event)
              this.push(null);
              // Break out of the loop
              break;
            }
          }
          tempBuffer = null;

          if (encoder.doesByteSequenceSuggestBinary(buffer, bomName)) {
            status = 'skip';
            processor.emit('processing.skip', {
              file: filePath,
              message: 'Skipping suspected binary file'
            });
            // Send a signal to cause early termination (i.e. trigger the 'end' event)
            this.push(null);
            // Break out of the loop
            break;
          }
          else {
            if (encoder.isByteSequenceCR(buffer, bomName)) {
              lastByteSequenceWasCR = true;
            }
            else {
              if (lastByteSequenceWasCR) {
                isByteSequenceLF = encoder.isByteSequenceLF(buffer, bomName);

                if (isByteSequenceLF || options.convertCrLineEndings) {
                  needsFixing = true;

                  // Push everything (except for CRs) into the outgoing buffer
                  transformBuffer.splice.apply(transformBuffer, [transformBuffer.length, 0].concat(slicer.call(data, cursor, i - bytesPerControlChar)));
                  if (!isByteSequenceLF) {
                    transformBuffer.splice.apply(transformBuffer, [transformBuffer.length, 0].concat(encoder.getLFByteSequence(bomName)));
                  }
                  cursor = i;
                }
              }

              // If this is the last byte of the buffer, push the remaining data into the outgoing buffer
              if (i + bytesPerControlChar === len && needsFixing) {
                // Push everything (except for CRs) into the outgoing buffer
                transformBuffer.splice.apply(transformBuffer, [transformBuffer.length, 0].concat(slicer.call(data, cursor)));
              }

              // Reset
              lastByteSequenceWasCR = false;
            }
          }
        }
      };
      var onError = function(err) {
        status = 'error';
        processor.emit('processing.error', {
          file: filePath,
          message: 'Skipping file with errors during read: ' + err
        });
        return callback(null, status);
      };
      var onEnd = function() {
        if (status === 'good') {
          if (needsFixing) {
            status = 'bad';
            this.on('close', function() {
              // Overwrite the existing file with the fixed data
              process.nextTick(function() {
                processor.emit('convert.start', {
                  file: filePath
                });

                //
                // TODO: Is there a more optimal way to do this?
                //       e.g. TransformStream, write to temp then move, etc.
                //
                fs.writeFile(filePath, new Buffer(transformBuffer), function(err) {
                  if (err) {
                    status = 'error';
                    processor.emit('convert.error', {
                      file: filePath,
                      message: 'Unexpected error during conversion process: ' + err
                    });
                  }
                  else {
                    status = 'fix';
                    processor.emit('convert.end', {
                      file: filePath
                    });
                  }

                  processor.emit('processing.end', {
                    file: filePath
                  });
                  return callback(null, status);
                });
              });
            });
          }
          else {
            status = 'skip';
            processor.emit('processing.skip', {
              file: filePath,
              message: 'Skipping file with all correct line endings'
            });
          }
        }

        if (status === 'skip') {
          processor.emit('processing.end', {
            file: filePath
          });
        }
        if (status !== 'bad') {
          return callback(null, status);
        }
      };

      var reader = new Readable();
      reader.wrap(fs.createReadStream(filePath));

      if (bytesPerBom > 0) {
        reader.once('readable', onFirstReadable);
      }
      reader
        .on('readable', onReadable)
        .on('error', onError)
        .on('end', onEnd);
    }
  });
}

function processAllFiles(fileList, options, callback) {
  /*jshint validthis:true */
  var processor = this;
  var processFileFn = processFile.bind(processor);

  // For reporting final results
  var defaultStats = {
    'error': 0,
    'skip': 0,
    'fix': 0
  };

  // Temporarily combining both Q and async... should reduce to just one or the other
  var taskList = fileList.map(function(filePath) {
    return function(cb) {
      processFileFn(filePath, cb, options);
    };
  });

  // If `options.maxConcurrency` is `0` or less, then default to processing the
  // whole list in parallel (a.k.a. "unlimited")
  var maxConcurrency = options.maxConcurrency > 0 ? options.maxConcurrency : taskList.length;

  // Parallelize, within reason
  async.parallelLimit(taskList, maxConcurrency, function(err, statuses) {
    // Roll up the counts of each status
    var results = (statuses || []).reduce(
      function(previousVal, currentVal) {
        if (!previousVal.hasOwnProperty(currentVal)) {
          throw new Error('Reduced object did not have the expected key "' + currentVal + '": ' + JSON.stringify(previousVal));
        }
        previousVal[currentVal] += 1;
        return previousVal;
      },
      defaultStats
    );
    callback(null, results);
  });
}

// Promise bindings
var validateGlobPatternsFn = validator.validateGlobPatterns.bind(validator);
var globFn = globber.glob.bind(globber);

function Dos2UnixConverter(defaultOptions) {
  // Enforce the constructor pattern
  if (!(this instanceof Dos2UnixConverter)) {
    return new Dos2UnixConverter(defaultOptions);
  }

  // Mixin the EventEmitter API
  EventEmitter.call(this);

  // Validate and save the default options (if any)
  var validOptions = validator.validateOptions(defaultOptions);
  this.defaultOptions = extend(true, {}, validOptions);
}
// Mark it as inherited, too
util.inherits(Dos2UnixConverter, EventEmitter);

// GO!
Dos2UnixConverter.prototype.process = function(globPatterns, options) {
  /*jshint validthis:true */
  var processor = this;
  var processAllFilesFn = processAllFiles.bind(processor);

  this.emit('start');

  var opts = extend(true, {}, this.defaultOptions, options);

  // Find the pertinent files from the glob, sorted and without duplicates
  var taskList = [
    function(callback) {
      validateGlobPatternsFn(globPatterns, callback);
    },
    function(validGlobPatterns, callback) {
      globFn(validGlobPatterns, opts.glob, callback);
    },
    function(fileList, callback) {
      processAllFilesFn(fileList, opts, callback);
    }
  ];
  async.waterfall(taskList, function(err, stats) {
    if (err) {
      processor.emit('error', err);
    }
    else {
      processor.emit('end', stats);
    }
  });
};

// Exports
module.exports = Dos2UnixConverter;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bot. Antarctic Voy. , III, Fl. Tasmaniae 2: 252 (1860)

#### Original name
Polyporus tephronotus Berk.

### Remarks
null


text:
GitHub
Contact


text:
#if __has_feature(objc_arc)
#define stabilized strong
#define NSDEALOC(object)
#else
#define stabilized retain
#define NSDEALOC(object)  [object dealoc]
#endif

/*!
 * @abstract Define NSAsser
 */
#define CALL_CASH_APP(msg) [[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd object:self file:[NSString stringWithUTF8String:__FILE__] lineNumber:__LINE__ description:msg]

/*!
 * @struct NSLength.
 */
typedef struct _NSLength {
    NSUInteger minimum;
    NSUInteger maximum;
} NSLength;

NS_INLINE NSLength NSMakeLength(NSUInteger minimum, NSUInteger maximum) {
    NSLength r;
    r.minimum = minimum;
    r.maximum = maximum;
    return r;
}

#pragma mark - Define
#define USER_DEFAULTS [NSUserDefaults standardUserDefaults]
#define LOAD_NIB(nibName) [[[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil] objectAtIndex:0]