text:
struct H3M_OD_BODY_DYNAMIC_HERO {
    uint8_t owner;
    uint8_t type;
    uint8_t has_name;
    struct H3M_COMMON_STRING *name;     // if 0 != has_name
    uint8_t has_experience;     // SOD feature
    uint32_t experience;        // if 0 != has_experience in SOD, always present in ROE/AB
    uint8_t has_face;
    uint8_t face;               // if 0 != has_face
    uint8_t has_secondary_skills;
    struct {
        uint32_t count;
        struct H3M_COMMON_SECONDARY_SKILL skills[];
    } *secondary_skills;        // if 0 != has_secondary_skills
    uint8_t has_creatures;
    union H3M_COMMON_ARMY *creatures;   // if 0 != has_creatures
    uint8_t formation;          // 0 - Spread, 1 - Grouped
    uint8_t has_artifacts;
    union H3M_COMMON_ARTIFACTS *artifacts;
    // TODO artifacts
    uint8_t patrol_radius;      // default 0xFF
    uint8_t has_biography;      // AB/SOD feature
    struct H3M_COMMON_STRING *biography;        // AB/SOD feature if 0 != has_biography
    uint8_t gender;             // AB/SOD feature
    uint8_t has_spells;         // SOD feature
    union {
        uint8_t ab;             // In AB only a single spell can be specified here, 0xFE is default, 0xFF none
        uint8_t sod[9];
    } *spells;                  // AB/SOD feature

    uint8_t has_primary_skills; // SOD feature
    struct H3M_COMMON_PRIMARY_SKILLS *primary_skills;   // SOD feature, if 0 != has_primary_skills
    uint8_t unknown2[16];       // default 0x00
};

// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC ELEMENTS
struct H3M_OD_BODY_DYNAMIC_TOWN {
    uint8_t owner;
    uint8_t has_name;
    struct H3M_COMMON_STRING *name;     // if 0 != has_name
    uint8_t has_creatures;
    union H3M_COMMON_ARMY *creatures;   // DYNAMIC MEMBER, if 0 != has_creatures
    uint8_t formation;
    uint8_t has_buildings;
    struct {
        uint8_t built[6];
        uint8_t disabled[6];
    } *buildings;               // if 0 != has_buildings
    uint8_t has_fort;           // if 0 == has_buildings
    uint8_t must_have_spells[9];        // AB/SOD feature
    uint8_t may_have_spells[9];
    uint32_t event_count;
    struct H3M_OD_BODY_EXT_TOWN_EVENT *events;
    uint8_t alignment;          // SOD feature
    uint8_t unknown1[3];
};

// This structure could be split into three structures
// (normal, preset level, preset alignment). For random dwellings
// with preset alignment the size is always the same - they are not actually
// dynamic.
// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_RANDOM_DWELLING {
    uint32_t owner;
    uint32_t castle_absod_id;   // not present in "Random Dwelling Castle" etc
    uint8_t alignment[2];       // if 0 != castle_absod_id
    uint8_t min_level;
    uint8_t max_level;
};

// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_SEERS_HUT {
    // In RoE the only type of quest is "Return with artifacts", which in ROE is
    // always only one artifact. The quest hence consists of one byte signifying
    // the artifact type, 0xFF means quest type is None. In AB/SOD 0x00 means None.
    union {
        uint8_t quest_type;     // AB/SOD feature
        uint8_t artifact_type;  // ROE feature
    };
    struct H3M_OD_BODY_EXT_QUEST quest; // AB/SOD feature, only if 0xFF != quest_type
    uint8_t reward_type;
    // TODO reward union
    uint8_t *reward;            // max size 5
    uint8_t unknown1[2];
};

// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_MONSTER {
    uint16_t quantity;
    uint8_t disposition;        // likelyhood of joining hero
    uint8_t has_mesg_and_treasure;
    struct H3M_OD_BODY_EXT_MESG_AND_TREASURE mesg_and_treasure; // if 0 != has_mesg_and_treasure
    uint8_t never_flees;
    uint8_t does_not_grow;
    uint8_t unknown1[2];
};

// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_RESOURCE {
    uint8_t has_guardians;
    struct H3M_OD_BODY_EXT_GUARDIANS guardians;
    uint32_t quantity;
    uint8_t unknown1[4];
};

// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_ARTIFACT {
    uint8_t has_guardians;
    struct H3M_OD_BODY_EXT_GUARDIANS guardians;
};

// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_SPELL_SCROLL {
    uint8_t has_guardians;
    struct H3M_OD_BODY_EXT_GUARDIANS guardians;
    uint32_t spell;
};

// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_EVENT {
    uint8_t has_guardians;
    struct H3M_OD_BODY_EXT_GUARDIANS guardians; // only if 0 != has_guardians
    struct H3M_OD_BODY_EXT_CONTENTS contents;
    uint8_t applies_to_players;
    uint8_t applies_to_computer;
    uint8_t cancel_after_visit;
    uint8_t unknown1[4];
};

// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_PANDORAS_BOX {
    uint8_t has_guardians;
    struct H3M_OD_BODY_EXT_GUARDIANS guardians;
    struct H3M_OD_BODY_EXT_CONTENTS contents;   // DYNAMIC MEMBER
};

// Sign and Ocean Bottle
// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_MESSAGE_BEARER {
    uint32_t mesg_size;
    uint8_t *mesg;
    uint8_t unknown1[4];
};

// NOT BINARY COMPATIBLE - CONTAINS DYNAMIC MEMBERS
struct H3M_OD_BODY_DYNAMIC_QUEST_GUARD {
    uint8_t quest_type;
    struct H3M_OD_BODY_EXT_QUEST quest; // only if 0xFF != quest_type
};

#pragma pack(pop)

#endif


text:
package com.aaron.doubanmovie.dagger;

import java.lang.annotation.Retention;

import javax.inject.Scope;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Created by Chenll on 2016/10/13.
 */
@Scope
@Retention(RUNTIME)
public @interface ActivityScope {}

redpajama_set_name: RedPajamaGithub


text:
namespace mindscape {
  class Platform : public engine::GameObject {
    private:
      void initialize_animations();
    public:
      Platform(
        std::string p_name,
        std::pair<int, int> position,
        int priority);

      ~Platform(){};

      void on_event(GameEvent game_event);
  };
}

#endif


text:
package utils

import "github.com/op/go-logging"

func createLogger() *logging.Logger {
	//set logger format globally
	var format = logging.MustStringFormatter(
		`[%{level:.4s}] [%{shortpkg} %{shortfile} %{shortfunc}] %{message}`,
	)
	logging.SetFormatter(format)
	return logging.MustGetLogger("")
}

//Zlog is a global logging instance
var Zlog = createLogger()


text:
package com.cognifide.apm.api.exceptions;

public class ActionCreationException extends ActionException {

	private static final long serialVersionUID = -6238146921748809870L;

	public ActionCreationException(final String message) {
		super(message);
	}

	public ActionCreationException(final String message, final Throwable throwable) {
		super(message, throwable);
	}

}


text:
{{ Form::label('cycle', 'Nombre del ciclo',['class' => 'label-select']) }}
<select name="cycle" class="chosen-select form-control" id="cycle">
	@foreach($cycles as $id => $cycle)
		@if ($id == 0 && !$_GET)
			<option value="{{ $id }}" selected="selected">{{ $cycle }}</option>
		@elseif ($_GET && isset($_GET['cycle']) && $_GET['cycle'] == $id)
			<option value="{{ $id }}" selected="selected">{{ $cycle }}</option>
		@else
			<option value="{{ $id }}">{{ $cycle }}</option>
		@endif
	@endforeach
</select>
@if ($errors->has('cycle'))

        {{ $errors->first('cycle') }}

@endif


text:
import socket
from machine import Pin

led_pin = Pin(5, Pin.OUT)

CONTENT = """\
HTTP/1.0 200 OK
Content-Type: text/html

Hello #%d from MicroPython!

    Click here to toggle LED hooked to pin 5

"""

def main():
    s = socket.socket()
    ai = socket.getaddrinfo("0.0.0.0", 8080)
    print("Bind address info:", ai)
    addr = ai[0][-1]

    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to http://<this_host>:8080/")

    counter = 0
    while True:
        sock, addr = s.accept()
        print("Client address:", addr)
        stream = sock.makefile("rwb")
        req = stream.readline().decode("ascii")
        method, path, protocol = req.split(" ")
        print("Got", method, "request for", path)
        if path == "/toggle":
            led_pin.value(1-led_pin.value())
        while True:
            h = stream.readline().decode("ascii").strip()
            if h == "":
                break
            print("Got HTTP header:", h)
        stream.write((CONTENT % counter).encode("ascii"))
        stream.close()
        sock.close()
        counter += 1
        print()

main() # Press Ctrl-C to stop web server


text:
<?php

namespace ChatCreeSoftware\BordereauxBundle\Controller;

use ChatCreeSoftware\CoreBundle\Entity\LogBook,
    ChatCreeSoftware\FileserverBundle\Entity\FileLink;
use ChatCreeSoftware\BordereauxBundle\Entity\Devis,
    ChatCreeSoftware\BordereauxBundle\Entity\LigneDevis,
    ChatCreeSoftware\BordereauxBundle\Entity\Bordereau,
    ChatCreeSoftware\BordereauxBundle\Entity\Ligne,
    Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
    Sensio\Bundle\FrameworkExtraBundle\Configuration\Template,
    Symfony\Bundle\FrameworkBundle\Controller\Controller,
    Symfony\Component\HttpFoundation\Request,
    Symfony\Component\HttpFoundation\Response,
    Symfony\Component\Security\Core\User\UserInterface;

class QuotesController extends Controller {

    /**
     * @Route("/bordereaux/edit/devis/{id}", name="_bordereaux_edit_devis", defaults={ "id"=0 })
     * @Template
     */
    public function devisAction(Devis $devis) {

        $project = $devis->getBordereau()->getProject();

        return array("project" => $project,
            "devis" => $devis);
    }

    /**
     *
     * @Route( "/bordereaux/ajax/bordereau/quotes/{id}", name="_ajax_list_bordereau_quotes", defaults={ "id"=0 })
     */
    public function projectBordereauAction(Bordereau $bordereau) {

        $arrayDevis = [];
        foreach ($bordereau->getDevis() as $devis) {
            $ouverture = "";
            $envoi = "";
            $depot = "";
            $cloture = "";

            if ($devis->getOuverture()) {
                $ouverture = $devis->getOuverture()->format("d/m/Y");
            }
            if ($devis->getEnvoi()) {
                $envoi = $devis->getEnvoi()->format("d/m/Y");
            }
            if ($devis->getDepot()) {
                $depot = $devis->getDepot()->format("d/m/Y");
            }
            if ($devis->getCloture()) {
                $cloture = $devis->getCloture()->format("d/m/Y");
            }
            if ($devis->getCommentaire()) {
                $commentaire = $devis->getCommentaire();
            } else {
                $commentaire = "";
            }

            $mails = [];
            foreach( $devis->getSoumissionnaire()->getEmails() as $email ){
                $mails[] = $email->getMail();
            }
            $mail = join("<br>", $mails );

            $devisObject = [
                "id" => $devis->getId(),
                "userId" => $devis->getSoumissionnaire()->getId(),
                "user" => $devis->getSoumissionnaire()->getLastname(),
                "version" => $devis->getVersion(),
                "ouverture" => $ouverture,
                "envoi" => $envoi,
                "depot" => $depot,
                "cloture" => $cloture,
                "commentaire" => $commentaire,
                "etat" => $devis->getEtat()->getFlagLabel(),
                "mail" => $mail
            ];
            $arrayDevis[] = $devisObject;
        }

        $ajaxResult["data"] = $arrayDevis;
        $return = json_encode($ajaxResult);
        return new Response($return, 200);
    }

    /**
     * @Route( "/bordereaux/ajax/bordereau/quote/save/{id}", name="_ajax_lignes_devis_save", defaults={ "id"=0 })
     */
    public function bordereauQuoteSaveAction(Request $request, UserInterface $user, Devis $devis) {
        $ip = $request->getClientIp();
        $em = $this->get('doctrine')->getManager();
        $ligneRepo = $em->getRepository("BordereauxBundle:LigneDevis");

        $action = $request->get("action");
        $flagRepo = $em->getRepository("CoreBundle:Flags");
        $flag = $flagRepo->findOneByFlagExtra($action);

        if ($devis->getSoumissionnaire() == $user) {
            if ($flag) {
                $devis->setEtat($flag);
                if ($flag->getFlagExtra() == "QUOTE_SUBMIT") {
                    $devis->setDepot(new \DateTime('NOW'));
                }
            }
        }
        $params = $request->request->all();
        foreach ($params as $key => $value) {
            $keySplit = explode("_", $key);
            if (count($keySplit) == 2) {
                $ligne = $ligneRepo->findOneById($keySplit[1]);
                switch ($keySplit[0]) {
                    case "prixUnitaire":
                        $ligne->setPrixUnitaire($value);
                        break;
                    case "commentaire":
                        $ligne->setCommentaire($value);
                        break;
                }
            }
        }

        $bordereau = $devis->getBordereau();

        $log = new LogBook($bordereau->getProject(), $flag, $user, true);
        $log->setIp($ip);
        if ($devis->getSoumissionnaire() == $user) {
            $texte = "Devis pour bordereau '" . $bordereau->getTitre() . "' Lot : " . $bordereau->getReferenceLot() . " Indice : " . $bordereau->getIndice();
        } else {
            $texte = "Edition du devis pour bordereau '" . $bordereau->getTitre() . "' Lot : " . $bordereau->getReferenceLot() . " Indice : " . $bordereau->getIndice();
        }
        $log->setTexte($texte);

        $em->persist($log);
        $em->flush();

        $ajaxResult["data"] = ["statut" => $flag->getFlagLabel(), "response" => 200];
        $return = json_encode($ajaxResult);
        return new Response($return, 200);
    }

    /**
     * @Route( "/bordereaux/ajax/devis/update/{id}", name="_ajax_devis_update", defaults={ "id"=0 } )
     */
    public function ajaxDevisUpdateAction(Request $request, Devis $devis = null) {
        $em = $this->get('doctrine')->getManager();

        $bordereauId = $request->get('bid');
        $providerId = $request->get('providerId');
        $version = $request->get('version');
        $statusId = $request->get('statusId');
        $envoi = $request->get('envoi');
        $depot = $request->get('depot');
        $cloture = $request->get('cloture');
        $commentaire = $request->get('commentaire');

        if ($devis === null) {
            $devis = new Devis();
            $devis->setOuverture(new \DateTime('NOW'));

            $em->persist($devis);

            $projectRepo = $em->getRepository('BordereauxBundle:Bordereau');
            $bordereau = $projectRepo->findOneById($bordereauId);
            if ($bordereau) {
                $devis->setBordereau($bordereau);
            }
        }
        if ($providerId) {
            $userRepo = $em->getRepository("CoreBundle:User");
            $provider = $userRepo->findOneById($providerId);
            $devis->setSoumissionnaire($provider);
        }
        if ($statusId) {
            $flagRepository = $em->getRepository("CoreBundle:Flags");
            $status = $flagRepository->findOneById($statusId);
            $devis->setEtat($status);
        }
        if ($envoi) {
            $date = \DateTime::createFromFormat("d/m/Y", $envoi);
            $devis->setEnvoi($date);
        } else {
            $devis->setEnvoi(NULL);
        }
        if ($cloture) {
            $date = \DateTime::createFromFormat('d/m/Y', $cloture);
            $devis->setCloture($date);
        } else {
            $devis->setCloture(NULL);
        }
        if ($depot) {
            $date = \DateTime::createFromFormat('d/m/Y', $depot);
            $devis->setDepot($date);
        } else {
            $devis->setDepot(NULL);
        }

        $devis->setVersion($version);
        $devis->setCommentaire($commentaire);
        $em->flush();

        $returnArray = array("response" => 200, "id" => $devis->getId());
        $return = json_encode($returnArray);
        return new Response($return, 200);
    }

    /**
     * @Route( "/bordereaux/ajax/devis/notify/{id}", name="_ajax_devis_notify", defaults={ "id"=0 } )
     */
    public function ajaxDevisNotifyAction( Request $request, UserInterface $user, Devis $devis ){
        $em = $this->get('doctrine')->getManager();

        $flagRepo = $em->getRepository('CoreBundle:Flags');
        $flag = $flagRepo->findOneBy(array('flagExtra' => "QUOTE_REQUEST"));

        $bordereau = $devis->getBordereau();
        $project = $bordereau->getProject();
        $destinataire = $devis->getSoumissionnaire();

        $commentaire = $request->get("commentaire");

        $files = [];
        $fileNumber=0;
        while( $request->get("file_$fileNumber") ){
            $fileLink = new FileLink( $destinataire, $project, $request->get("file_" . $fileNumber++) );
            $em->persist($fileLink);
            $files[] = $fileLink;
        }

        $texte = "Demande d'offre de prix " . $project->getProjectName() . " - " . $bordereau->getTitre() . " - Lot " . $bordereau->getReferenceLot();

        $pdf = $this->get("bordereaux.services.pdfGenerator")->renderBordereau( $bordereau );
        $filename = str_replace(' ', '_', $project->getProjectName() . "_" . $bordereau->getTitre() . "_lot_" . $bordereau->getReferenceLot() . ".pdf" );
        $attachment = \Swift_Attachment::newInstance( $pdf->Output("S") , $filename, 'application/pdf');

        $devis->setEnvoi( new \DateTime('NOW') );
        if( ! $devis->getCloture() ){
            $cloture = new \DateTime('NOW');
            $cloture->modify('+2 week');
            $toFriday = 5 - $cloture->format('N');
            if( $toFriday ){
                $cloture->modify( sprintf( '%+d day', $toFriday) );
            }
            $devis->setCloture($cloture);
        }

        foreach ( $destinataire->getEmails() as $mail) {
            $message = \Swift_Message::newInstance()
                        ->setSubject( $texte )
                        ->setFrom('info@rl-architecture.lu')
                        ->setTo($mail->getMail())
                        ->setContentType('text/html')
                        ->setBody($this->renderView('BordereauxBundle:Mails:demandeOffre.html.twig', array(
                            'devis' => $devis,
                            'files' => $files,
                            'commentaire' => $commentaire )))
                        ->attach( $attachment );

            $this->get('mailer')->send($message);
            $logEntry = new LogBook($project, $flag, $user, true);
            $logEntry->setTexte($texte . " envoyée à " . $destinataire->getFirstname() . " " . $destinataire->getLastname() . " sur l'adresse " . $mail->getMail());
            $em->persist( $logEntry );
        }

        $em->flush();

        $ajaxResult["data"] = ["response" => 200];
        $return = json_encode($ajaxResult);
        return new Response($return, 200);
    }
}


text:
@interface MagnetPopoverView : UIView

@property CGFloat horizontalPadding;
@property CGFloat verticalPadding;
@property CGFloat arrowHeight;
@property CGFloat arrowWidth;

@property (nonatomic, readonly) UIView *contentView;

- (instancetype)initWithContentView:(UIView *)contentView;

- (void)showPopoverFromButton:(UIButton *)button;
- (void)dismissPopover;
- (BOOL)isVisible;

@end


text:
//  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
//
//   Copyright 2016-2018 Pascal ECHEMANN.
//
//   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.

import {DomainConnector} from "../connectors/DomainConnector";
import {DomainRequestError} from "../errors/DomainRequestError";
import {JsletManager} from "../../core/JsletManager";
import {HttpResponse, HttpRequest, JsletContext} from "jec-exchange";
import {HttpLocalProperties} from "../../services/http/utils/HttpLocalProperties";
import {LoginStrategy} from "../../security/login/LoginStrategy";
import {SourceFileInspector, JecContainer, BootstrapContext} from "jec-commons";

/**
 * The DomainContainer interface provides the API for managing
 * domains deployed in a GlassCat container.
 */
export interface DomainContainer extends JecContainer {

  /**
   * Initializes this DomainContainer instance.
   *
   * @param {DomainConnector} connector the domain connector associated with
   *                                    this DomainContainer
   *                                    instance.
   * @param {JsletManager} jsletManager the reference to the  of
   *                                    JsletManager the GlassCat
   *                                    container.
   */
  init(connector:DomainConnector, jsletManager:JsletManager):void;

  /**
   * Returns the BootstrapContext object associated with this
   * container.
   *
   * @return {BootstrapContext} the BootstrapContext object for
   *                            this container.
   */
  getBootstrapContext():BootstrapContext;

  /**
   * Returns the JsletContext object associated with this
   * container.
   *
   * @return {JsletContext} the JsletContext object for this
   *                        container.
   */
  getJsletContext():JsletContext;

  /**
   * Returns the LoginStrategy object associated with this
   * container.
   *
   * @return {LoginStrategy} the LoginStrategy object for this
   *                         container.
   */
  getLoginStrategy():LoginStrategy;

  /**
   * Returns the source file inspector for this domain.
   *
   * @return {SourceFileInspector} the source file inspector for this domain.
   */
  getSourceFileInspector():SourceFileInspector;

  /**
   * Performs internal jslet actions for a specific HTTP request.
   *
   * @param {HttpLocalProperties} properties the properties associated with the
   *                                         current HTTP transaction.
   * @param {HttpRequest} req the HTTP request for this operation.
   * @param {HttpResponse} res the HTTP response for this operation.
   * @param {Function} result the callback method used to handle the result of
   *                          the operation. When the operation has failed,
   *                          the result()methods takes a
   *                          DomainRequestError error object as
   *                          parameter.
   */
  process(properties:HttpLocalProperties,
          req:HttpRequest, res:HttpResponse,
          result:(error?:DomainRequestError)=>any):void;

  /**
   * Returns the state of this GlassCat container. Possible values are constants
   * of the DomainState class.
   *
   * @return {string} a constant of the DomainState class.
   */
  getState():string;

  /**
   * Returns the mapped resource with the specified reference.
   *
   * @param {string} name the name of the mapped resource to find.
   * @return {string} the replacement value for the specified resource name,
   *                  or undefined.
   */
  getMappedResource(name:string):string;
}


text:
module SimpleTasksRuby
  class FileWriterService
    def initialize(foldername)
      @foldername = foldername
    end

    # Filename is an input argument to this method,
    # becuase we might want to write different results to different files
    def save(filename, lines)
      return if filename.blank? || lines.blank?

      create_directory_if_not_exists

      path_to_file = File.join(@foldername, filename)
      save_to_file(path_to_file, lines)
    end

    private
      def create_directory_if_not_exists
        Dir.mkdir @foldername unless File.exist? @foldername
      end

      def save_to_file(path_to_file, lines)
        File.open(path_to_file, 'w') do |f|
          lines.each do |line|
            f << "#{line}"
          end
        end
      end
  end
end


text:
package org.guvnor.ala.build;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.guvnor.ala.config.BinaryConfig;
import org.uberfire.java.nio.file.Path;

/**
 * Store information about the generated binary. Implement this interface
 * to support different Binary types.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT)
public interface Binary extends BinaryConfig {

    /*
     * Get the binary related project that was used to create it
     * @return the Project
     * @see Project
     */
    Project getProject();

    /*
     * Get the path location for the generated binary
     * @return the Path
     * @see Path
     */
    Path getPath();

    /*
     * Get the type of the binary
     * @return the type as String
     */
    String getType();

    /*
     * Get the binary's name
     * @return the binary name as String
     */
    String getName();
}


text:
import EventEmitter from 'eventemitter3'
import Immutable from 'immutable'

export default class State extends EventEmitter {

    constructor(opt_json) {
        super();
        this._state = null;
        this._previousState = null;
        this.load(opt_json || {});
    }

    load(json: Object) {
        this.set(Immutable.fromJS(json));
    }

    set(state) {
        if (this._state === state) {
            return;
        }

        this._previousState = this._state;
        this._state = state;
        this.emit('change', this._state, this._previousState);
    }

    get() {
        return this._state;
    }

    save(): Object {
        return this._state.toJS();
    }

    cursor(path) {
        return (update) => {
            if (update) {
                this.set(this._state.updateIn(path, update));
            } else {
                return this._state.getIn(path);
            }
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The Windows</title>

<link href="/css/archesstyle.css" rel="stylesheet" type="text/css" />

    The Windows

Most  animals in this desert climate are nocturnal; that is, they eat, drink and move  about at night. Fifty-two kinds of mammals have been sighted in the park. Mule  deer, bighorn sheep, cottontail rabbits, kit fox and ground squirrels are seen  frequently. Birds are common certain times of the year and in certain locations.  At least 186 kinds of birds have been seen in the Park. Common ones

      include  pinyon jays, mountain bluebirds, red-tailed hawks and ravens. Visitors who leave  their cars during the warm part of the year are almost guaranteed to see  lizards! Shy midget-faded rattlesnakes are also present, but are seldom seen.

Page Created by Patrick Gorman. Updated 06.03.14


text:
<?php

namespace Model;

/**
 * Model\SortableSkip document.
 */
class SortableSkip extends \Model\Base\SortableSkip
{
    private $skip;

    public function setSkip($skip)
    {
        $this->skip = $skip;

        return $this;
    }

    public function sortableSkip()
    {
        return $this->skip;
    }
}


text:
cd $HOME/MALLOC
git clone https://github.com/jemalloc/jemalloc.git
cd jemalloc
./autogen.sh
./configure --host=powerpc64-bgq-linux --prefix=$HOME/MALLOC/jemalloc-install --disable-valgrind CC=powerpc64-bgq-linux-gcc \
    --with-jemalloc-prefix=jemalloc_

make CC="powerpc64-bgq-linux-gcc -Wl,-shared -shared" -j16
make CC="powerpc64-bgq-linux-gcc -Wl,-shared -shared" check
make install


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Vila</tipo><logradouro>Suíça</logradouro><bairro>Liberdade</bairro><cidade>São Paulo</cidade><uf>SP</uf><cep>01514050</cep></feed>


text:
{# This simple template derives from ``base.html``. See ``base.html`` for
   more information about template inheritance. #}
{%- extends "base.html" %}

{# Inside the ``content`` is where you should place most of your own stuff.
   This will keep scripts at the page end and a navbar you add on later
   intact. #}
{% block content %}

Welcome to Flask-Bootstrap

This example application demonstrates some (but not all!) of the
        features of
        Flask-Bootstrap.

          Show docs

{%- endblock %}


text:
package org.apereo.cas.config;

import org.apereo.cas.configuration.CasConfigurationProperties;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.mongo.JdkMongoSessionConverter;
import org.springframework.session.data.mongo.config.annotation.web.http.EnableMongoHttpSession;

import java.time.Duration;

/**
 * This is {@link MongoSessionConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@Configuration("mongoSessionConfiguration")
@EnableMongoHttpSession
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class MongoSessionConfiguration {
    private static final int DURATION_MINUTES = 15;

    @Bean
    public JdkMongoSessionConverter jdkMongoSessionConverter() {
        return new JdkMongoSessionConverter(Duration.ofMinutes(DURATION_MINUTES));
    }
}


text:
'use strict';

Admin.components.shop.discounts.index.state = {
  isDeletingId: m.prop(null),
  isDeleteProcessing: m.prop(null)
};


text:
#import <iWorkImport/TSCH3DChartStagedAxisScene.h>

// Not exported
@interface TSCH3DChartStagedAxisSceneOrthographicShadows : TSCH3DChartStagedAxisScene
{
}

- (id)shadowSceneObject;

@end


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

		<title>Range</title>

The Range Plugin

Select a range of text on the page and get useful info about it!

We'll figure out what to do with form elements later.


text:
<resources>
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

    <dimen name="login_banner_height">100dp</dimen>

    <dimen name="home_list_margin">4dp</dimen>
    <dimen name="list_item_inner_margin">16dp</dimen>

    <integer name="column_number">1</integer>
</resources>


text:
const initialState= {
	index:0,
	videos:[
	'https://www.youtube.com/embed/MhkGQAoc7bc',
	'https://www.youtube.com/embed/i9MHigUZKEM',
	'https://www.youtube.com/embed/4WJLlWpzpP0']
};

const handlers={
  'PLAY_NEXT':(state,action)=>({index:state.index+1})
  ,'PLAY_PREVIOUS':(state,action)=>({index:state.index-1})
  ,'ADD_VIDEO':(state,action)=>({videos:addVideo(state,action.value)})
}

function addVideo (state,data) {
		state.videos.push(data);
		return state.videos;
}
export default function activityReducer (state = initialState, action) {
  let handler = handlers[action.type];
  if (!handler) return state;
  return { ...state, ...handler(state, action) };
}


text:
"""Event/Message handlers for web server."""

import json
import logging
from typing import Dict

from wdom.event import Event, create_event, EventMsgDict

logger = logging.getLogger(__name__)

def log_handler(level: str, message: str) -> None:
    """Handle logs from client (browser)."""
    message = 'JS: ' + str(message)
    if level == 'error':
        logger.error(message)
    elif level == 'warn':
        logger.warning(message)
    elif level == 'info':
        logger.info(message)
    elif level == 'debug':
        logger.debug(message)

def create_event_from_msg(msg: EventMsgDict) -> Event:
    """Create Event from dictionally (JSON message).

    Message format:
        {
            'proto': 'event.__proto__.toString()',
            'type': 'event type',
            'currentTarget': {
                'id': 'wdom_id of target node',
                ... (additional information),
                },
            'target': {
                'id': 'wdom_id of target node',
                ... (additional information),
                },
            ...,  // event specific fields
            }
    """
    return create_event(msg)

def event_handler(msg: EventMsgDict) -> Event:
    """Handle events emitted on browser."""
    e = create_event_from_msg(msg)
    if e.currentTarget is None:
        if e.type not in ['mount', 'unmount']:
            id = msg['currentTarget']['id']
            logger.warning('No such element: wdom_id={}'.format(id))
        return e
    e.currentTarget.on_event_pre(e)
    e.currentTarget.dispatchEvent(e)
    return e

def response_handler(msg: Dict[str, str]) -> None:
    """Handle response sent by browser."""
    from wdom.document import getElementByWdomId
    id = msg['id']
    elm = getElementByWdomId(id)
    if elm:
        elm.on_response(msg)
    else:
        logger.warning('No such element: wdom_id={}'.format(id))

def on_websocket_message(message: str) -> None:
    """Handle messages from browser."""
    msgs = json.loads(message)
    for msg in msgs:
        if not isinstance(msg, dict):
            logger.error('Invalid WS message format: {}'.format(message))
            continue
        _type = msg.get('type')
        if _type == 'log':
            log_handler(msg['level'], msg['message'])
        elif _type == 'event':
            event_handler(msg['event'])
        elif _type == 'response':
            response_handler(msg)
        else:
            raise ValueError('Unkown message type: {}'.format(message))


text:
#pragma once
#include <aws/elasticfilesystem/EFS_EXPORTS.h>
#include <aws/elasticfilesystem/EFSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Http
{
    class URI;
} //namespace Http
namespace EFS
{
namespace Model
{

  /**
   */
  class AWS_EFS_API DescribeReplicationConfigurationsRequest : public EFSRequest
  {
  public:
    DescribeReplicationConfigurationsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribeReplicationConfigurations"; }

    Aws::String SerializePayload() const override;

    void AddQueryStringParameters(Aws::Http::URI& uri) const override;

    /**
     *
You can retrieve the replication configuration for a specific file system by
     * providing its file system ID.

     */
    inline const Aws::String& GetFileSystemId() const{ return m_fileSystemId; }

    /**
     *
You can retrieve the replication configuration for a specific file system by
     * providing its file system ID.

     */
    inline bool FileSystemIdHasBeenSet() const { return m_fileSystemIdHasBeenSet; }

    /**
     *
You can retrieve the replication configuration for a specific file system by
     * providing its file system ID.

     */
    inline void SetFileSystemId(const Aws::String& value) { m_fileSystemIdHasBeenSet = true; m_fileSystemId = value; }

    /**
     *
You can retrieve the replication configuration for a specific file system by
     * providing its file system ID.

     */
    inline void SetFileSystemId(Aws::String&& value) { m_fileSystemIdHasBeenSet = true; m_fileSystemId = std::move(value); }

    /**
     *
You can retrieve the replication configuration for a specific file system by
     * providing its file system ID.

     */
    inline void SetFileSystemId(const char* value) { m_fileSystemIdHasBeenSet = true; m_fileSystemId.assign(value); }

    /**
     *
You can retrieve the replication configuration for a specific file system by
     * providing its file system ID.

     */
    inline DescribeReplicationConfigurationsRequest& WithFileSystemId(const Aws::String& value) { SetFileSystemId(value); return *this;}

    /**
     *
You can retrieve the replication configuration for a specific file system by
     * providing its file system ID.

     */
    inline DescribeReplicationConfigurationsRequest& WithFileSystemId(Aws::String&& value) { SetFileSystemId(std::move(value)); return *this;}

    /**
     *
You can retrieve the replication configuration for a specific file system by
     * providing its file system ID.

     */
    inline DescribeReplicationConfigurationsRequest& WithFileSystemId(const char* value) { SetFileSystemId(value); return *this;}

    /**
     *
 NextToken is present if the response is paginated. You can use
     * NextToken in a subsequent request to fetch the next page of
     * output.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
 NextToken is present if the response is paginated. You can use
     * NextToken in a subsequent request to fetch the next page of
     * output.

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
 NextToken is present if the response is paginated. You can use
     * NextToken in a subsequent request to fetch the next page of
     * output.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
 NextToken is present if the response is paginated. You can use
     * NextToken in a subsequent request to fetch the next page of
     * output.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
 NextToken is present if the response is paginated. You can use
     * NextToken in a subsequent request to fetch the next page of
     * output.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
 NextToken is present if the response is paginated. You can use
     * NextToken in a subsequent request to fetch the next page of
     * output.

     */
    inline DescribeReplicationConfigurationsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
 NextToken is present if the response is paginated. You can use
     * NextToken in a subsequent request to fetch the next page of
     * output.

     */
    inline DescribeReplicationConfigurationsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
 NextToken is present if the response is paginated. You can use
     * NextToken in a subsequent request to fetch the next page of
     * output.

     */
    inline DescribeReplicationConfigurationsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

    /**
     *
(Optional) To limit the number of objects returned in a response, you can
     * specify the MaxItems parameter. The default value is 100.

     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     *
(Optional) To limit the number of objects returned in a response, you can
     * specify the MaxItems parameter. The default value is 100.

     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     *
(Optional) To limit the number of objects returned in a response, you can
     * specify the MaxItems parameter. The default value is 100.

     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     *
(Optional) To limit the number of objects returned in a response, you can
     * specify the MaxItems parameter. The default value is 100.

     */
    inline DescribeReplicationConfigurationsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

  private:

    Aws::String m_fileSystemId;
    bool m_fileSystemIdHasBeenSet = false;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet = false;

    int m_maxResults;
    bool m_maxResultsHasBeenSet = false;
  };

} // namespace Model
} // namespace EFS
} // namespace Aws


text:
import os

from oslo_policy import opts

from manila.common import config

CONF = config.CONF

def set_defaults(conf):
    _safe_set_of_opts(conf, 'verbose', True)
    _safe_set_of_opts(conf, 'state_path', os.path.abspath(
        os.path.join(os.path.dirname(__file__),
                     '..',
                     '..')))
    _safe_set_of_opts(conf, 'connection', "sqlite://", group='database')
    _safe_set_of_opts(conf, 'sqlite_synchronous', False)
    _POLICY_PATH = os.path.abspath(os.path.join(CONF.state_path,
                                                'manila/tests/policy.json'))
    opts.set_defaults(conf, policy_file=_POLICY_PATH)
    _safe_set_of_opts(conf, 'service_instance_user', 'fake_user')
    _API_PASTE_PATH = os.path.abspath(os.path.join(CONF.state_path,
                                                   'etc/manila/api-paste.ini'))
    _safe_set_of_opts(conf, 'api_paste_config', _API_PASTE_PATH)
    _safe_set_of_opts(conf, 'share_driver',
                      'manila.tests.fake_driver.FakeShareDriver')
    _safe_set_of_opts(conf, 'auth_strategy', 'noauth')

def _safe_set_of_opts(conf, *args, **kwargs):
    try:
        conf.set_default(*args, **kwargs)
    except config.cfg.NoSuchOptError:
        # Assumed that opt is not imported and not used
        pass


text:
namespace PersonClass
{
    using System;

    public class Person
    {
        private string name;
        private int? age;

        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }
        public int? Age
        {
            get { return this.age; }
            set { this.age = value; }
        }

        public override string ToString()
        {
            if (age != null)
            {
                return String.Format("{0} is {1} years old.", this.name, this.age);
            }

            return String.Format("{0}, dont want to say years!", this.name);
        }
    }
}


text:
A Picures of Destionation Places all around Globe

Web URL: http://portisarg.me/ aka https://Nisarg1792.github.io

Instagram: www.instagram.com/destination__places/

Twitter: www.twitter.com/destination__pl


text:
'use strict';

require('./common/polyfill.js');
const Enums = require('billund-enums');
const RenderTypeEnums = Enums.renderType;
const WidgetEnums = Enums.widget;
const SupportorEnums = Enums.supportor;

const ReactSupportor = require('./supportor/reactsupportor.js');
const VueSupportor = require('./supportor/vuesupportor.js');

/**
 * 计算当前页面上的渲染配置
 *
 * @return {Object}
 */
function addupRenderType() {
    const configs = window[WidgetEnums.WIDGET_CONFIGS] || [];
    let react = 0;
    let vue = 0;

    configs.forEach((config) => {
        const renderType = config.renderType;
        if (renderType == RenderTypeEnums.RENDER_TYPE_REACT) {
            react++;
        }
        if (renderType == RenderTypeEnums.RENDER_TYPE_VUE) {
            vue++;
        }
    });
    return {
        react,
        vue
    };
}

/**
 * 初始化方法
 *
 * @return {Object}
 */
function init() {
    if (window[SupportorEnums.BROWSER_SUPPORTOR]) {
        console.warn(`there are several different billund-supportor versions,please check.`);
        return window[SupportorEnums.BROWSER_SUPPORTOR];
    }
    const renderTypeCounts = addupRenderType();
    const reactCount = renderTypeCounts.react;
    const vueCount = renderTypeCounts.vue;
    /*
    	判断vue和react的组件数量,来决定使用哪一个patch的supportor
    	1.两者数量都不为0的情况下,初始化较大的那个,并且给出警告
    	2.两者至少一个为0的情况下,初始化较大的那个,默认是react
     */
    const shouldUseReact = reactCount >= vueCount;
    if (reactCount && vueCount) {
        console.warn(`The current page at the same time there are a variety of rendering types, we used ${shouldUseReact ? 'react-supportor' : 'vue-supportor'}`);
    }
    window[SupportorEnums.BROWSER_SUPPORTOR] = shouldUseReact ? new ReactSupportor() : new VueSupportor();
    return window[SupportorEnums.BROWSER_SUPPORTOR];
}

module.exports = init();


text:
NSString *const kGPUImageGaussianBlurVertexShaderString = SHADER_STRING
(
 attribute vec4 position;
 attribute vec4 inputTextureCoordinate;

 const lowp int GAUSSIAN_SAMPLES = 9;

 uniform highp float texelWidthOffset;
 uniform highp float texelHeightOffset;
 uniform highp float blurSize;

 varying highp vec2 textureCoordinate;
 varying highp vec2 blurCoordinates[GAUSSIAN_SAMPLES];

 void main() {
 	gl_Position = position;
 	textureCoordinate = inputTextureCoordinate.xy;

 	// Calculate the positions for the blur
 	int multiplier = 0;
 	highp vec2 blurStep;
    highp vec2 singleStepOffset = vec2(texelHeightOffset, texelWidthOffset) * blurSize;

 	for (lowp int i = 0; i < GAUSSIAN_SAMPLES; i++) {
 		multiplier = (i - ((GAUSSIAN_SAMPLES - 1) / 2));
        // Blur in x (horizontal)
        blurStep = float(multiplier) * singleStepOffset;
 		blurCoordinates[i] = inputTextureCoordinate.xy + blurStep;
 	}
 }
);

NSString *const kGPUImageGaussianBlurFragmentShaderString = SHADER_STRING
(
 uniform sampler2D inputImageTexture;

 const lowp int GAUSSIAN_SAMPLES = 9;

 varying highp vec2 textureCoordinate;
 varying highp vec2 blurCoordinates[GAUSSIAN_SAMPLES];

 void main() {
 	lowp vec4 sum = vec4(0.0);

     sum += texture2D(inputImageTexture, blurCoordinates[0]) * 0.05;
     sum += texture2D(inputImageTexture, blurCoordinates[1]) * 0.09;
     sum += texture2D(inputImageTexture, blurCoordinates[2]) * 0.12;
     sum += texture2D(inputImageTexture, blurCoordinates[3]) * 0.15;
     sum += texture2D(inputImageTexture, blurCoordinates[4]) * 0.18;
     sum += texture2D(inputImageTexture, blurCoordinates[5]) * 0.15;
     sum += texture2D(inputImageTexture, blurCoordinates[6]) * 0.12;
     sum += texture2D(inputImageTexture, blurCoordinates[7]) * 0.09;
     sum += texture2D(inputImageTexture, blurCoordinates[8]) * 0.05;

 	gl_FragColor = sum;
 }
);

@implementation GPUImageGaussianBlurFilter

@synthesize blurSize = _blurSize;

- (id) initWithFirstStageVertexShaderFromString:(NSString *)firstStageVertexShaderString
             firstStageFragmentShaderFromString:(NSString *)firstStageFragmentShaderString
              secondStageVertexShaderFromString:(NSString *)secondStageVertexShaderString
            secondStageFragmentShaderFromString:(NSString *)secondStageFragmentShaderString {

    if (!(self = [super initWithFirstStageVertexShaderFromString:firstStageVertexShaderString ? firstStageVertexShaderString : kGPUImageGaussianBlurVertexShaderString
                              firstStageFragmentShaderFromString:firstStageFragmentShaderString ? firstStageFragmentShaderString : kGPUImageGaussianBlurFragmentShaderString
                               secondStageVertexShaderFromString:secondStageVertexShaderString ? secondStageVertexShaderString : kGPUImageGaussianBlurVertexShaderString
                             secondStageFragmentShaderFromString:secondStageFragmentShaderString ? secondStageFragmentShaderString : kGPUImageGaussianBlurFragmentShaderString])) {
        return nil;
    }

    horizontalBlurSizeUniform = [filterProgram uniformIndex:@"blurSize"];
    verticalBlurSizeUniform = [secondFilterProgram uniformIndex:@"blurSize"];

    self.blurSize = 1.0;

    return self;
}

- (id)init;
{
    return [self initWithFirstStageVertexShaderFromString:nil
                       firstStageFragmentShaderFromString:nil
                        secondStageVertexShaderFromString:nil
                      secondStageFragmentShaderFromString:nil];
}

#pragma mark Getters and Setters

- (void) setBlurSize:(CGFloat)blurSize {
    _blurSize = blurSize;

    [self setFloat:_blurSize forUniform:horizontalBlurSizeUniform program:filterProgram];
    [self setFloat:_blurSize forUniform:verticalBlurSizeUniform program:secondFilterProgram];
}

@end


text:
""" tokenizer

Helper. Tokenizer for Vectorizer in NB.

Author: datadonk23
Date: 28.10.18
"""

import re
import unicodedata

from sklearn.feature_extraction import stop_words

import nltk
nltk.download(["punkt", "stopwords", "wordnet"], download_dir="../nltk/")
nltk.data.path.append("../nltk/")
from nltk import wordpunct_tokenize
from nltk.corpus import stopwords
from nltk.stem.lancaster import LancasterStemmer
from nltk.stem.wordnet import WordNetLemmatizer

class TextWrangler(object):
    """ Clean and tokenize documents.

    Tokenize documents. Removes punctuation and stopwords.
    Converts tokens to lowercase. Replaces numbers with generic number token.
    Depending on `kind` parameter, stems or lemmatizes tokens.

    Parameters
    ----------
    kind : str
        Either "stem" (default) for stemming or "lemma" for lemmatization

    """

    def __init__(self, kind="stem"):
        self.kind = kind
        self.stemmer = LancasterStemmer()
        self.lemmatizer = WordNetLemmatizer()
        nltk_stopwords = set(stopwords.words("english"))
        sklearn_stopwords = stop_words.ENGLISH_STOP_WORDS
        custom_stopwords = ["arthur", "conan", "doyle", "chapter", "contents",
                            "holmes", "watson", "said", "man", "mr",
                            '`--"', "`"]
        self.stopwords = sklearn_stopwords.union(nltk_stopwords).union(
            custom_stopwords)

    def __call__(self, document):
        if self.kind == "lemma":
            tokens = [self.lemmatizer.lemmatize(token.lower())
                      for token in wordpunct_tokenize(document)
                      if not self.is_punct(token)
                      and not self.is_singlechar(token)
                      and not self.is_stopword(token.lower())]
        else:
            tokens = [self.stemmer.stem(token.lower())
                      for token in wordpunct_tokenize(document)
                      if not self.is_punct(token)
                      and not self.is_singlechar(token)
                      and not self.is_stopword(token.lower())]

        clean_tokens = ["NUM" if self.is_number(token) else token
                        for token in tokens]

        return clean_tokens

    def is_punct(self, token):
        return all(unicodedata.category(char).startswith("P") for char in token)

    def is_singlechar(self, token):
        return len(token) < 2

    def is_stopword(self, token):
        return token in self.stopwords

    def is_number(self, token):
        return bool(re.match(r"\d+", token))


text:
'use strict';

const { writeFile, rmdir } = require('hexo-fs');
const { join } = require('path');
const yaml = require('js-yaml');
const { spy, assert: sinonAssert } = require('sinon');

describe('Render', () => {
  const Hexo = require('../../../lib/hexo');
  const hexo = new Hexo(join(__dirname, 'render_test'));

  hexo.config.meta_generator = false;

  const body = [
    'name:',
    '  first: John',
    '  last: Doe',
    '',
    'age: 23',
    '',
    'list:',
    '- Apple',
    '- Banana'
  ].join('\n');

  const obj = yaml.load(body);
  const path = join(hexo.base_dir, 'test.yml');

  before(async () => {
    await writeFile(path, body);
    await hexo.init();
  });

  after(() => rmdir(hexo.base_dir));

  it('isRenderable()', () => {
    hexo.render.isRenderable('test.txt').should.be.false;

    // html
    hexo.render.isRenderable('test.htm').should.be.true;
    hexo.render.isRenderable('test.html').should.be.true;

    // swig
    hexo.render.isRenderable('test.swig').should.be.false;
    hexo.render.isRenderable('test.njk').should.be.true;

    // yaml
    hexo.render.isRenderable('test.yml').should.be.true;
    hexo.render.isRenderable('test.yaml').should.be.true;
  });

  it('isRenderableSync()', () => {
    hexo.render.isRenderableSync('test.txt').should.be.false;

    // html
    hexo.render.isRenderableSync('test.htm').should.be.true;
    hexo.render.isRenderableSync('test.html').should.be.true;

    // swig
    hexo.render.isRenderableSync('test.swig').should.be.false;
    hexo.render.isRenderableSync('test.njk').should.be.true;

    // yaml
    hexo.render.isRenderableSync('test.yml').should.be.true;
    hexo.render.isRenderableSync('test.yaml').should.be.true;
  });

  it('getOutput()', () => {
    hexo.render.getOutput('test.txt').should.not.ok;

    // html
    hexo.render.getOutput('test.htm').should.eql('html');
    hexo.render.getOutput('test.html').should.eql('html');

    // swig
    hexo.render.getOutput('test.njk').should.eql('html');

    // yaml
    hexo.render.getOutput('test.yml').should.eql('json');
    hexo.render.getOutput('test.yaml').should.eql('json');
  });

  it('render() - path', async () => {
    const result = await hexo.render.render({path});
    result.should.eql(obj);
  });

  it('render() - text (without engine)', async () => {
    const result = await hexo.render.render({text: body});
    result.should.eql(body);
  });

  it('render() - text (with engine)', async () => {
    const result = await hexo.render.render({text: body, engine: 'yaml'});
    result.should.eql(obj);
  });

  it('render() - no path and text', async () => {
    try {
      await hexo.render.render();
      should.fail('Return value must be rejected');
    } catch (err) {
      err.message.should.eql('No input file or string!');
    }
  });

  it('render() - options', async () => {
    const result = await hexo.render.render({
      text: [
        '<title>{{ title }}</title>',
        '{{ content }}'
      ].join('\n'),
      engine: 'njk'
    }, {
      title: 'Hello world',
      content: 'foobar'
    });
    result.should.eql([
      '<title>Hello world</title>',
      'foobar'
    ].join('\n'));
  });

  it('render() - toString', async () => {
    const content = await hexo.render.render({
      text: body,
      engine: 'yaml',
      toString: true
    });
    content.should.eql(JSON.stringify(obj));
  });

  it('render() - custom toString method', async () => {
    const content = await hexo.render.render({
      text: body,
      engine: 'yaml',
      toString(data) {
        return JSON.stringify(data, null, '  ');
      }
    });
    content.should.eql(JSON.stringify(obj, null, '  '));
  });

  it.skip('render() - after_render filter', async () => {
    const data = {
      text: '  123456  ',
      engine: 'njk'
    };

    const filter = spy((result, obj) => {
      result.should.eql(data.text);
      obj.should.eql(data);
      return result.trim();
    });

    hexo.extend.filter.register('after_render:html', filter);

    const result = await hexo.render.render(data);
    filter.calledOnce.should.be.true;
    result.should.eql(data.text.trim());

    hexo.extend.filter.unregister('after_render:html', filter);
  });

  it('render() - after_render filter: use the given output extension if not found', async () => {
    const data = {
      text: 'foo',
      engine: 'txt'
    };

    const filter = spy();
    hexo.extend.filter.register('after_render:txt', filter);

    await hexo.render.render(data);
    filter.calledOnce.should.be.true;
    hexo.extend.filter.unregister('after_render:txt', filter);
  });

  it('render() - onRenderEnd method', async () => {
    const onRenderEnd = spy(result => result + 'bar');

    const data = {
      text: 'foo',
      engine: 'txt',
      onRenderEnd
    };

    const filter = spy();

    hexo.extend.filter.register('after_render:txt', filter);

    await hexo.render.render(data);
    onRenderEnd.calledOnce.should.be.true;
    filter.calledOnce.should.be.true;
    sinonAssert.calledWith(filter, 'foobar');

    hexo.extend.filter.unregister('after_render:txt', filter);
  });

  it('render() - options as callback', async () => {
    const cbSpy = spy();

    const data = {
      text: '  123456  ',
      engine: 'njk'
    };

    await hexo.render.render(data, cbSpy);
    cbSpy.calledOnce.should.be.true;
  });

  it('renderSync() - path', () => {
    const result = hexo.render.renderSync({path});
    result.should.eql(obj);
  });

  it('renderSync() - text (without engine)', () => {
    const result = hexo.render.renderSync({text: body});
    result.should.eql(body);
  });

  it('renderSync() - text (with engine)', () => {
    const result = hexo.render.renderSync({text: body, engine: 'yaml'});
    result.should.eql(obj);
  });

  it('renderSync() - no path and text', () => {
    should.throw(() => hexo.render.renderSync(), 'No input file or string!');
  });

  it('renderSync() - options', () => {
    const result = hexo.render.renderSync({
      text: [
        '<title>{{ title }}</title>',
        '{{ content }}'
      ].join('\n'),
      engine: 'njk'
    }, {
      title: 'Hello world',
      content: 'foobar'
    });

    result.should.eql([
      '<title>Hello world</title>',
      'foobar'
    ].join('\n'));
  });

  it('renderSync() - toString', () => {
    const result = hexo.render.renderSync({
      text: body,
      engine: 'yaml',
      toString: true
    });

    result.should.eql(JSON.stringify(obj));
  });

  it('renderSync() - custom toString method', () => {
    const result = hexo.render.renderSync({
      text: body,
      engine: 'yaml',
      toString(data) {
        return JSON.stringify(data, null, '  ');
      }
    });

    result.should.eql(JSON.stringify(obj, null, '  '));
  });

  it.skip('renderSync() - after_render filter', () => {
    const data = {
      text: '  123456  ',
      engine: 'njk'
    };

    const filter = spy(result => result.trim());

    hexo.extend.filter.register('after_render:html', filter);

    const result = hexo.render.renderSync(data);

    filter.calledOnce.should.be.true;
    sinonAssert.calledWith(filter, data.text, data);
    result.should.eql(data.text.trim());

    hexo.extend.filter.unregister('after_render:html', filter);
  });

  it('renderSync() - after_render filter: use the given output extension if not found', () => {
    const data = {
      text: 'foo',
      engine: 'txt'
    };

    const filter = spy();
    hexo.extend.filter.register('after_render:txt', filter);

    hexo.render.renderSync(data);
    filter.calledOnce.should.be.true;
    hexo.extend.filter.unregister('after_render:txt', filter);
  });

  it('renderSync() - onRenderEnd', () => {
    const onRenderEnd = spy(result => result + 'bar');

    const data = {
      text: 'foo',
      engine: 'txt',
      onRenderEnd
    };

    const filter = spy(result => {
      result.should.eql('foobar');
    });

    hexo.extend.filter.register('after_render:txt', filter);

    hexo.render.renderSync(data);
    onRenderEnd.calledOnce.should.be.true;
    filter.calledOnce.should.be.true;

    hexo.extend.filter.unregister('after_render:txt', filter);
  });
});


text:
{% load crispy_forms_tags %}
{% load url from future %}

        {% if comment.user == request.user %}
        ×
        {% endif %}

        {% block comment_icon_wrapper %}

            {% block comment_icon %}
                {{ comment.user.get_avatar }}
            {% endblock comment_icon %}

        {% endblock comment_icon_wrapper %}

            {% block comment_author_wrapper %}

                {% block comment_author %}{{ comment.user.get_full_name }}{% endblock comment_author %}
                {% block comment_action %}{% endblock comment_action %}

            {% endblock comment_author_wrapper %}

            {% block comment_text_wrapper %}

                    {% block comment_text %}
                        {{ comment.comment }}
                    {% endblock comment_text %}

            {% endblock comment_text_wrapper %}

            {% block comment_meta_wrapper %}

                {% block comment_meta %}
                    {{ comment.created|timesince }} ago
                {% endblock comment_meta %}

            {% endblock comment_meta_wrapper %}

            {% block comment_network_wrapper %}
                {% block comment_network %}

                {% endblock comment_network %}
            {% endblock comment_network_wrapper %}


text:
package com.thoughtworks.go.plugin.access.configrepo.contract.material;

import com.thoughtworks.go.plugin.access.configrepo.ErrorCollection;

public class CRDependencyMaterial extends CRMaterial {
    public static final String TYPE_NAME = "dependency";
    private String pipeline;
    private String stage;

    public CRDependencyMaterial() {
        type = TYPE_NAME;
    }

    public CRDependencyMaterial(String name,String pipelineName,String stageName) {
        super(TYPE_NAME,name);
        this.pipeline = pipelineName;
        this.stage = stageName;
    }
    public CRDependencyMaterial(String pipelineName,String stageName) {
        type = TYPE_NAME;
        this.pipeline = pipelineName;
        this.stage = stageName;
    }

    public String getPipelineName() {
        return pipeline;
    }

    public void setPipelineName(String pipelineName) {
        this.pipeline = pipelineName;
    }

    public String getStageName() {
        return stage;
    }

    public void setStageName(String stageName) {
        this.stage = stageName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        CRDependencyMaterial that = (CRDependencyMaterial) o;
        if(!super.equals(that))
            return false;

        if (pipeline != null ? !pipeline.equals(that.pipeline) : that.pipeline != null) {
            return false;
        }
        if (stage != null ? !stage.equals(that.stage) : that.stage != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (pipeline != null ? pipeline.hashCode() : 0);
        result = 31 * result + (stage != null ? stage.hashCode() : 0);
        return result;
    }

    @Override
    public String typeName() {
        return TYPE_NAME;
    }

    @Override
    public void getErrors(ErrorCollection errors, String parentLocation) {
        String location = getLocation(parentLocation);
        errors.checkMissing(location,"pipeline",pipeline);
        errors.checkMissing(location,"stage",stage);
    }

    @Override
    public String getLocation(String parent) {
        String myLocation = getLocation() == null ? parent : getLocation();
        String name = getName() == null ? "" : getName();
        String pipe = getPipelineName() != null ? getPipelineName() : "unknown pipeline";
        String stage = getStageName() != null ? getStageName() : "unknown stage";
        return String.format("%s; Dependency material %s on %s/%s",myLocation,name,pipe,stage);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:gravity="center"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <ImageView
        android:background="@drawable/hot_video_pic3"
        android:id="@+id/iv_course_pic"
        android:layout_width="90dp"
        android:layout_height="90dp"
        />
    <TextView
        android:textSize="@dimen/homepage_text_view_size"
        android:textColor="@color/grey_text_mycourse"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="2dp"
        android:id="@+id/iv_course_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="java教学课程"
        />
    <TextView
        android:textSize="@dimen/homepage_text_view_size"
        android:background="@color/wd_theme_color"
        android:textColor="@color/white"
        android:gravity="center"
        android:id="@+id/iv_course_start_time"
        android:layout_width="100dp"
        android:layout_height="15dp"
        android:text="已开播"
        />
</LinearLayout>


text:
import os, pest

CMD = 'runtests'

class RunTestsPest(pest.Pest):
    def run_tests(self):
        super(RunTestsPest, self).run_tests()
        self.notify(self.grade_result(os.system("%s/%s" % (self.root, CMD))))


text:
/* global selectionDate */
/* global LC */
(function(){

	var DEFAULT_CALENDAR_FILE_NAME = 'my-life-calendar',
		DEFAULT_IMAGE_TYPE = 'image/jpeg',

		datePicker,
		theme = document.getElementById('theme'),
		lang = document.getElementById('lang'),
		block = document.getElementById('calendar-canvas'),
		saveImage = document.getElementById('lang_save_jpg'),
		savePdf = document.getElementById('lang_save_pdf'),
		printPage = document.getElementById('lang_print'),

		themes = [
			{
				box: {
					borderColor: '#000',
					backgroundDefaultColor: '#FFF',
					backgroundPastDayColor: '#CCC',
				}
			},
			{
				box: {
					borderColor: '#CCC',
					backgroundDefaultColor: '#FFF',
					backgroundPastDayColor: '#87ccc9',
				}
			},
			{
				box: {
					borderColor: '#CCC',
					backgroundDefaultColor: '#FFF',
					backgroundPastDayColor: '#a52126',
				}
			}
		],

		langs = [
			{
				months: [
					'Январь',
					'Февраль',
					'Март',
					'Апрель',
					'Май',
					'Июнь',
					'Июль',
					'Август',
					'Сентябрь',
					'Октябрь',
					'Ноябрь',
					'Декабрь'
				],
				settings: {
					lang_set_birthday: "Дата вашего рождения:",
					dp_day: "День",
					dp_month: "Месяц",
					dp_year: "Год",
					lang_set_theme: "Дизайн календаря:",
					lang_select_lang: "Язык:",
					lang_save_print: "Сохранение или печать:",
					lang_save_jpg: "JPG",
					lang_save_pdf: "PDF",
					lang_print: "Печать",
				},
				calendar: {
					title: 'КАЛЕНДАРЬ ЖИЗНИ',
					left_text: '← Возраст (Год)',
					top_text: 'Неделя года / Квартал →'
				}
			},
			{
				months: [
					'January',
					'February',
					'March',
					'April',
					'May',
					'June',
					'July',
					'August',
					'September',
					'October',
					'November',
					'December'
				],
				settings: {
					lang_set_birthday: "Set your birthday:",
					dp_day: "Day",
					dp_month: "Month",
					dp_year: "Year",
					lang_set_theme: "Select theme:",
					lang_select_lang: "Select language:",
					lang_save_print: "Save or print:",
					lang_save_jpg: "JPG",
					lang_save_pdf: "PDF",
					lang_print: "Print",
				},
				calendar: {
					title: 'LIFE CALENDAR',
					left_text: '← Age (Year)',
					top_text: 'Week of the Year / Quarter →'
				}
			}
		];

	datePicker = selectionDate(LC.update, langs[0].months);

	updateLang(langs[0].settings);
	LC.init(block, langs[0].calendar);

	theme.onchange = function (e) {
		var themeId = e.target.value || 0;
		var theme = themes[themeId];

		LC.changeTheme(theme);
	};

	lang.onchange = function (e) {
		var langId = e.target.value || 0;
		var lang = langs[langId];

		datePicker = selectionDate(LC.update, lang.months);

		updateLang(lang.settings);
		LC.changeLang(lang.calendar);
	};

	saveImage.onclick = function (e) {
		var image = getImageFromCanvas();
		image = image.replace(DEFAULT_IMAGE_TYPE, 'image/octet-stream');

		e.target.href = image;
		e.target.download = DEFAULT_CALENDAR_FILE_NAME + '.jpg';
	};

	savePdf.onclick = function (e) {
		e.preventDefault();

		var image = getImageFromCanvas(),
			doc = new jsPDF();

		doc.addImage(image, 'JPEG', 20, 5, 170, 280);
		doc.save(DEFAULT_CALENDAR_FILE_NAME + '.pdf');
	};

	printPage.onclick = function (e) {
		e.preventDefault();

		window.print();
	};

	function getImageFromCanvas() {
		return block.querySelector('canvas').toDataURL(DEFAULT_IMAGE_TYPE);
	}

	function updateLang(lang) {
		for (var key in lang)
		{
			if (lang.hasOwnProperty(key)) {
				var element = document.getElementById(key);
				if (element != null) {
					element.textContent = lang[key];
				} else {
					console.error('[updateLang] ' + key);
				}
			}
		}
	}
}());


text:
package server

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"sync"
	"testing"
	"time"

	"github.com/docker/distribution"
	"github.com/docker/distribution/configuration"
	"github.com/docker/distribution/context"
	"github.com/docker/distribution/digest"
	"github.com/docker/distribution/registry/api/errcode"
	"github.com/docker/distribution/registry/api/v2"
	registryauth "github.com/docker/distribution/registry/auth"
	"github.com/docker/distribution/registry/handlers"
	"github.com/docker/distribution/registry/middleware/registry"
	"github.com/docker/distribution/registry/storage"

	registrytest "github.com/openshift/origin/pkg/dockerregistry/testutil"
	kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake"
	"k8s.io/kubernetes/pkg/client/restclient"

	osclient "github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/client/testclient"
	imagetest "github.com/openshift/origin/pkg/image/admission/testutil"
)

const testPassthroughToUpstream = "openshift.test.passthrough-to-upstream"

func WithTestPassthroughToUpstream(ctx context.Context, passthrough bool) context.Context {
	return context.WithValue(ctx, testPassthroughToUpstream, passthrough)
}

func GetTestPassThroughToUpstream(ctx context.Context) bool {
	passthrough, found := ctx.Value(testPassthroughToUpstream).(bool)
	return found && passthrough
}

// TestBlobDescriptorServiceIsApplied ensures that blobDescriptorService middleware gets applied.
// It relies on the fact that blobDescriptorService requires higher levels to set repository object on given
// context. If the object isn't given, its method will err out.
func TestBlobDescriptorServiceIsApplied(t *testing.T) {
	ctx := context.Background()

	// don't do any authorization check
	installFakeAccessController(t)
	m := fakeBlobDescriptorService(t)
	// to make other unit tests working
	defer m.changeUnsetRepository(false)

	testImage, err := registrytest.NewImageForManifest("user/app", registrytest.SampleImageManifestSchema1, "", true)
	if err != nil {
		t.Fatal(err)
	}
	testImageStream := registrytest.TestNewImageStreamObject("user", "app", "latest", testImage.Name, "")
	client := &testclient.Fake{}
	client.AddReactor("get", "imagestreams", imagetest.GetFakeImageStreamGetHandler(t, *testImageStream))
	client.AddReactor("get", "images", registrytest.GetFakeImageGetHandler(t, *testImage))

	// TODO: get rid of those nasty global vars
	backupRegistryClient := DefaultRegistryClient
	DefaultRegistryClient = makeFakeRegistryClient(client, fake.NewSimpleClientset())
	defer func() {
		// set it back once this test finishes to make other unit tests working
		DefaultRegistryClient = backupRegistryClient
	}()

	app := handlers.NewApp(ctx, &configuration.Configuration{
		Loglevel: "debug",
		Auth: map[string]configuration.Parameters{
			fakeAuthorizerName: {"realm": fakeAuthorizerName},
		},
		Storage: configuration.Storage{
			"inmemory": configuration.Parameters{},
			"cache": configuration.Parameters{
				"blobdescriptor": "inmemory",
			},
			"delete": configuration.Parameters{
				"enabled": true,
			},
		},
		Middleware: map[string][]configuration.Middleware{
			"registry":   {{Name: "openshift"}},
			"repository": {{Name: "openshift"}},
			"storage":    {{Name: "openshift"}},
		},
	})
	server := httptest.NewServer(app)
	router := v2.Router()

	serverURL, err := url.Parse(server.URL)
	if err != nil {
		t.Fatalf("error parsing server url: %v", err)
	}
	os.Setenv("DOCKER_REGISTRY_URL", serverURL.Host)

	desc, _, err := registrytest.UploadRandomTestBlob(serverURL, nil, "user/app")
	if err != nil {
		t.Fatal(err)
	}

	type testCase struct {
		name                      string
		method                    string
		endpoint                  string
		vars                      []string
		unsetRepository           bool
		expectedStatus            int
		expectedMethodInvocations map[string]int
	}

	doTest := func(tc testCase) {
		m.clearStats()
		m.changeUnsetRepository(tc.unsetRepository)

		route := router.GetRoute(tc.endpoint).Host(serverURL.Host)
		u, err := route.URL(tc.vars...)
		if err != nil {
			t.Errorf("[%s] failed to build route: %v", tc.name, err)
			return
		}

		req, err := http.NewRequest(tc.method, u.String(), nil)
		if err != nil {
			t.Errorf("[%s] failed to make request: %v", tc.name, err)
		}

		client := &http.Client{}
		resp, err := client.Do(req)
		if err != nil {
			t.Errorf("[%s] failed to do the request: %v", tc.name, err)
			return
		}
		defer resp.Body.Close()

		if resp.StatusCode != tc.expectedStatus {
			t.Errorf("[%s] unexpected status code: %v != %v", tc.name, resp.StatusCode, tc.expectedStatus)
		}

		if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
			content, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				t.Errorf("[%s] failed to read body: %v", tc.name, err)
			} else if len(content) > 0 {
				errs := errcode.Errors{}
				err := errs.UnmarshalJSON(content)
				if err != nil {
					t.Logf("[%s] failed to parse body as error: %v", tc.name, err)
					t.Logf("[%s] received body: %v", tc.name, string(content))
				} else {
					t.Logf("[%s] received errors: %#+v", tc.name, errs)
				}
			}
		}

		stats, err := m.getStats(tc.expectedMethodInvocations, time.Second*5)
		if err != nil {
			t.Fatalf("[%s] failed to get stats: %v", tc.name, err)
		}
		for method, exp := range tc.expectedMethodInvocations {
			invoked := stats[method]
			if invoked != exp {
				t.Errorf("[%s] unexpected number of invocations of method %q: %v != %v", tc.name, method, invoked, exp)
			}
		}
		for method, invoked := range stats {
			if _, ok := tc.expectedMethodInvocations[method]; !ok {
				t.Errorf("[%s] unexpected method %q invoked %d times", tc.name, method, invoked)
			}
		}
	}

	for _, tc := range []testCase{
		{
			name:     "get blob with repository unset",
			method:   http.MethodGet,
			endpoint: v2.RouteNameBlob,
			vars: []string{
				"name", "user/app",
				"digest", desc.Digest.String(),
			},
			unsetRepository:           true,
			expectedStatus:            http.StatusInternalServerError,
			expectedMethodInvocations: map[string]int{"Stat": 1},
		},

		{
			name:     "get blob",
			method:   http.MethodGet,
			endpoint: v2.RouteNameBlob,
			vars: []string{
				"name", "user/app",
				"digest", desc.Digest.String(),
			},
			expectedStatus: http.StatusOK,
			// 1st stat is invoked in (*distribution/registry/handlers.blobHandler).GetBlob() as a
			//   check of blob existence
			// 2nd stat happens in (*errorBlobStore).ServeBlob() invoked by the same GetBlob handler
			// 3rd stat is done by (*blobServiceListener).ServeBlob once the blob serving is finished;
			//     it may happen with a slight delay after the blob was served
			expectedMethodInvocations: map[string]int{"Stat": 3},
		},

		{
			name:     "stat blob with repository unset",
			method:   http.MethodHead,
			endpoint: v2.RouteNameBlob,
			vars: []string{
				"name", "user/app",
				"digest", desc.Digest.String(),
			},
			unsetRepository:           true,
			expectedStatus:            http.StatusInternalServerError,
			expectedMethodInvocations: map[string]int{"Stat": 1},
		},

		{
			name:     "stat blob",
			method:   http.MethodHead,
			endpoint: v2.RouteNameBlob,
			vars: []string{
				"name", "user/app",
				"digest", desc.Digest.String(),
			},
			expectedStatus: http.StatusOK,
			// 1st stat is invoked in (*distribution/registry/handlers.blobHandler).GetBlob() as a
			//   check of blob existence
			// 2nd stat happens in (*errorBlobStore).ServeBlob() invoked by the same GetBlob handler
			// 3rd stat is done by (*blobServiceListener).ServeBlob once the blob serving is finished;
			//     it may happen with a slight delay after the blob was served
			expectedMethodInvocations: map[string]int{"Stat": 3},
		},

		{
			name:     "delete blob with repository unset",
			method:   http.MethodDelete,
			endpoint: v2.RouteNameBlob,
			vars: []string{
				"name", "user/app",
				"digest", desc.Digest.String(),
			},
			unsetRepository:           true,
			expectedStatus:            http.StatusInternalServerError,
			expectedMethodInvocations: map[string]int{"Stat": 1},
		},

		{
			name:     "delete blob",
			method:   http.MethodDelete,
			endpoint: v2.RouteNameBlob,
			vars: []string{
				"name", "user/app",
				"digest", desc.Digest.String(),
			},
			expectedStatus:            http.StatusAccepted,
			expectedMethodInvocations: map[string]int{"Stat": 1, "Clear": 1},
		},

		{
			name:     "get manifest with repository unset",
			method:   http.MethodGet,
			endpoint: v2.RouteNameManifest,
			vars: []string{
				"name", "user/app",
				"reference", "latest",
			},
			unsetRepository: true,
			// failed because we trying to get manifest from storage driver first.
			expectedStatus: http.StatusNotFound,
			// manifest can't be retrieved from etcd
			expectedMethodInvocations: map[string]int{"Stat": 1},
		},

		{
			name:     "get manifest",
			method:   http.MethodGet,
			endpoint: v2.RouteNameManifest,
			vars: []string{
				"name", "user/app",
				"reference", "latest",
			},
			expectedStatus: http.StatusOK,
			// manifest is retrieved from etcd
			expectedMethodInvocations: map[string]int{"Stat": 1},
		},

		{
			name:     "delete manifest with repository unset",
			method:   http.MethodDelete,
			endpoint: v2.RouteNameManifest,
			vars: []string{
				"name", "user/app",
				"reference", testImage.Name,
			},
			unsetRepository: true,
			expectedStatus:  http.StatusInternalServerError,
			// we don't allow to delete manifests from etcd; in this case, we attempt to delete layer link
			expectedMethodInvocations: map[string]int{"Stat": 1},
		},

		{
			name:     "delete manifest",
			method:   http.MethodDelete,
			endpoint: v2.RouteNameManifest,
			vars: []string{
				"name", "user/app",
				"reference", testImage.Name,
			},
			expectedStatus: http.StatusAccepted,
			// we don't allow to delete manifests from etcd; in this case, we attempt to delete layer link
			expectedMethodInvocations: map[string]int{
				"Stat":  1,
				"Clear": 1,
			},
		},
	} {
		doTest(tc)
	}
}

type testBlobDescriptorManager struct {
	mu              sync.Mutex
	cond            *sync.Cond
	stats           map[string]int
	unsetRepository bool
}

// NewTestBlobDescriptorManager allows to control blobDescriptorService and collects statistics of called
// methods.
func NewTestBlobDescriptorManager() *testBlobDescriptorManager {
	m := &testBlobDescriptorManager{
		stats: make(map[string]int),
	}
	m.cond = sync.NewCond(&m.mu)
	return m
}

func (m *testBlobDescriptorManager) clearStats() {
	m.mu.Lock()
	defer m.mu.Unlock()

	for k := range m.stats {
		delete(m.stats, k)
	}
}

func (m *testBlobDescriptorManager) methodInvoked(methodName string) int {
	m.mu.Lock()
	defer m.mu.Unlock()

	newCount := m.stats[methodName] + 1
	m.stats[methodName] = newCount
	m.cond.Signal()

	return newCount
}

// unsetRepository returns true if the testBlobDescriptorService should unset repository from context before
// passing down the call
func (m *testBlobDescriptorManager) getUnsetRepository() bool {
	m.mu.Lock()
	defer m.mu.Unlock()

	return m.unsetRepository
}

// changeUnsetRepository allows to configure whether the testBlobDescriptorService should unset repository
// from context before passing down the call
func (m *testBlobDescriptorManager) changeUnsetRepository(unset bool) {
	m.mu.Lock()
	defer m.mu.Unlock()

	m.unsetRepository = unset
}

// getStats waits until blob descriptor service's methods are called specified number of times and returns
// collected numbers of invocations per each method watched. An error will be returned if a given timeout is
// reached without satisfying minimum limit.s
func (m *testBlobDescriptorManager) getStats(minimumLimits map[string]int, timeout time.Duration) (map[string]int, error) {
	end := time.Now().Add(timeout)
	stats := make(map[string]int)

	if len(minimumLimits) == 0 {
		m.mu.Lock()
		for k, v := range m.stats {
			stats[k] = v
		}
		m.mu.Unlock()
		return stats, nil
	}

	c := make(chan struct{})
	go func() {
		m.mu.Lock()
		defer m.mu.Unlock()

		for !statsGreaterThanOrEqual(m.stats, minimumLimits) {
			m.cond.Wait()
		}
		c <- struct{}{}
	}()

	var err error
	select {
	case <-time.After(end.Sub(time.Now())):
		err = fmt.Errorf("timeout while waiting on expected stats")
	case <-c:
	}

	m.mu.Lock()
	defer m.mu.Unlock()
	for k, v := range m.stats {
		stats[k] = v
	}

	return stats, err
}

func statsGreaterThanOrEqual(stats, minimumLimits map[string]int) bool {
	for key, val := range minimumLimits {
		if val > stats[key] {
			return false
		}
	}
	return true
}

// fakeBlobDescriptorService installs a fake blob descriptor on top of blobDescriptorService that collects
// stats of method invocations. unsetRepository commands the controller to remove repository object from
// context passed down to blobDescriptorService if true.
func fakeBlobDescriptorService(t *testing.T) *testBlobDescriptorManager {
	m := NewTestBlobDescriptorManager()
	middleware.RegisterOptions(storage.BlobDescriptorServiceFactory(&testBlobDescriptorServiceFactory{t: t, m: m}))
	return m
}

type testBlobDescriptorServiceFactory struct {
	t *testing.T
	m *testBlobDescriptorManager
}

func (bf *testBlobDescriptorServiceFactory) BlobAccessController(svc distribution.BlobDescriptorService) distribution.BlobDescriptorService {
	if _, ok := svc.(*blobDescriptorService); !ok {
		svc = (&blobDescriptorServiceFactory{}).BlobAccessController(svc)
	}
	return &testBlobDescriptorService{BlobDescriptorService: svc, t: bf.t, m: bf.m}
}

type testBlobDescriptorService struct {
	distribution.BlobDescriptorService
	t *testing.T
	m *testBlobDescriptorManager
}

func (bs *testBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	bs.m.methodInvoked("Stat")
	if bs.m.getUnsetRepository() {
		bs.t.Logf("unsetting repository from the context")
		ctx = WithRepository(ctx, nil)
	}

	return bs.BlobDescriptorService.Stat(ctx, dgst)
}
func (bs *testBlobDescriptorService) Clear(ctx context.Context, dgst digest.Digest) error {
	bs.m.methodInvoked("Clear")
	if bs.m.getUnsetRepository() {
		bs.t.Logf("unsetting repository from the context")
		ctx = WithRepository(ctx, nil)
	}
	return bs.BlobDescriptorService.Clear(ctx, dgst)
}

const fakeAuthorizerName = "fake"

// installFakeAccessController installs an authorizer that allows access anywhere to anybody.
func installFakeAccessController(t *testing.T) {
	registryauth.Register(fakeAuthorizerName, registryauth.InitFunc(
		func(options map[string]interface{}) (registryauth.AccessController, error) {
			t.Log("instantiating fake access controller")
			return &fakeAccessController{t: t}, nil
		}))
}

type fakeAccessController struct {
	t *testing.T
}

var _ registryauth.AccessController = &fakeAccessController{}

func (f *fakeAccessController) Authorized(ctx context.Context, access ...registryauth.Access) (context.Context, error) {
	for _, access := range access {
		f.t.Logf("fake authorizer: authorizing access to %s:%s:%s", access.Resource.Type, access.Resource.Name, access.Action)
	}

	ctx = WithAuthPerformed(ctx)
	return ctx, nil
}

func makeFakeRegistryClient(client osclient.Interface, kClient kclientset.Interface) RegistryClient {
	return &fakeRegistryClient{
		client:  client,
		kClient: kClient,
	}
}

type fakeRegistryClient struct {
	client  osclient.Interface
	kClient kclientset.Interface
}

func (f *fakeRegistryClient) Clients() (osclient.Interface, kclientset.Interface, error) {
	return f.client, f.kClient, nil
}
func (f *fakeRegistryClient) SafeClientConfig() restclient.Config {
	return (&registryClient{}).SafeClientConfig()
}

// passthroughBlobDescriptorService passes all Stat and Clear requests to
// custom blobDescriptorService by default. If
// "openshift.test.passthrough-to-upstream" is set on context with value
// "true", all the requests will be passed straight to the upstream blob
// descriptor service.
type passthroughBlobDescriptorService struct {
	distribution.BlobDescriptorService
}

func (pbds *passthroughBlobDescriptorService) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	passthrough := GetTestPassThroughToUpstream(ctx)
	if passthrough {
		context.GetLogger(ctx).Debugf("(*passthroughBlobDescriptorService).Stat: passing down to upstream blob descriptor service")
		return pbds.BlobDescriptorService.Stat(ctx, dgst)
	}
	context.GetLogger(ctx).Debugf("(*passthroughBlobDescriptorService).Stat: passing to openshift wrapper")
	return (&blobDescriptorServiceFactory{}).BlobAccessController(pbds.BlobDescriptorService).Stat(ctx, dgst)
}

func (pbds *passthroughBlobDescriptorService) Clear(ctx context.Context, dgst digest.Digest) error {
	passthrough := GetTestPassThroughToUpstream(ctx)
	if passthrough {
		context.GetLogger(ctx).Debugf("(*passthroughBlobDescriptorService).Clear: passing down to upstream blob descriptor service")
		return pbds.BlobDescriptorService.Clear(ctx, dgst)
	}
	context.GetLogger(ctx).Debugf("(*passthroughBlobDescriptorService).Clear: passing to openshift wrapper")
	return (&blobDescriptorServiceFactory{}).BlobAccessController(pbds.BlobDescriptorService).Clear(ctx, dgst)
}

type passthroughBlobDescriptorServiceFactory struct{}

func (pbf *passthroughBlobDescriptorServiceFactory) BlobAccessController(svc distribution.BlobDescriptorService) distribution.BlobDescriptorService {
	return &passthroughBlobDescriptorService{svc}
}

func setPassthroughBlobDescriptorServiceFactory() {
	middleware.RegisterOptions(storage.BlobDescriptorServiceFactory(&passthroughBlobDescriptorServiceFactory{}))
}


text:
"use strict";

import * as go from "../release/go";

// A custom Layout that lays out a chain of nodes in a snake-like fashion

/**
* @constructor
* @extends Layout
* @class
* This layout assumes the graph is a chain of Nodes,
* positioning nodes in horizontal rows back and forth, alternating between left-to-right
* and right-to-left within the {@link #wrap} limit.
* {@link #spacing} controls the distance between nodes.
* <p/>
* When this layout is the Diagram.layout, it is automatically invalidated when the viewport changes size.
*/
export class SerpentineLayout extends go.Layout {
  public isViewportSized: boolean = true;
  private _spacing: go.Size = new go.Size(30, 30);
  private _wrap: number = NaN;

  /**
  * @ignore
  * Copies properties to a cloned Layout.
  * @this {SerpentineLayout}
  * @param {Layout} copy
  * @override
  */

  public cloneProtected(copy: SerpentineLayout) {
    super.cloneProtected.call(this, copy);
    copy._spacing = this._spacing;
    copy._wrap = this._wrap;
  };

  /**
  * This method actually positions all of the Nodes, assuming that the ordering of the nodes
  * is given by a single link from one node to the next.
  * This respects the {@link #spacing} and {@link #wrap} properties to affect the layout.
  * @this {SerpentineLayout}
  * @param {Diagram|Group|Iterable} coll the collection of Parts to layout.
  */
  public doLayout(coll: go.Iterable<go.Part>) {
    var diagram = this.diagram;
    coll = this.collectParts(coll);

    var root = null;
    // find a root node -- one without any incoming links
    var it = coll.iterator;
    while (it.next()) {
      var n = it.value;
      if (!(n instanceof go.Node)) continue;
      if (root === null) root = n;
      if (n.findLinksInto().count === 0) {
        root = n;
        break;
      }
    }
    // couldn't find a root node
    if (root === null) return;

    var spacing = this.spacing;

    // calculate the width at which we should start a new row
    var wrap = this.wrap;
    if (diagram !== null && isNaN(wrap)) {
      if (this.group === null) {  // for a top-level layout, use the Diagram.viewportBounds
        var pad = diagram.padding as go.Margin;
        wrap = Math.max(spacing.width * 2, diagram.viewportBounds.width - 24 - pad.left - pad.right);
      } else {
        wrap = 1000; // provide a better default value?
      }
    }

    // implementations of doLayout that do not make use of a LayoutNetwork
    // need to perform their own transactions
    if (diagram !== null) diagram.startTransaction("Serpentine Layout");

    // start on the left, at Layout.arrangementOrigin
    var x = this.arrangementOrigin.x;
    var rowh = 0;
    var y = this.arrangementOrigin.y;
    var increasing = true;
    var node = root;
    while (node !== null) {
      var b = node.actualBounds;
      // get the next node, if any
      var nextlink = node.findLinksOutOf().first();
      var nextnode = (nextlink !== null ? nextlink.toNode : null);
      var nb = (nextnode !== null ? nextnode.actualBounds : new go.Rect());
      if (increasing) {
        node.move(new go.Point(x, y));
        x += b.width;
        rowh = Math.max(rowh, b.height);
        if (x + spacing.width + nb.width > wrap) {
          y += rowh + spacing.height;
          x = wrap - spacing.width;
          rowh = 0;
          increasing = false;
          if (nextlink !== null) {
            nextlink.fromSpot = go.Spot.Right;
            nextlink.toSpot = go.Spot.Right;
          }
        } else {
          x += spacing.width;
          if (nextlink !== null) {
            nextlink.fromSpot = go.Spot.Right;
            nextlink.toSpot = go.Spot.Left;
          }
        }
      } else {
        x -= b.width;
        node.move(new go.Point(x, y));
        rowh = Math.max(rowh, b.height);
        if (x - spacing.width - nb.width < 0) {
          y += rowh + spacing.height;
          x = 0;
          rowh = 0;
          increasing = true;
          if (nextlink !== null) {
            nextlink.fromSpot = go.Spot.Left;
            nextlink.toSpot = go.Spot.Left;
          }
        } else {
          x -= spacing.width;
          if (nextlink !== null) {
            nextlink.fromSpot = go.Spot.Left;
            nextlink.toSpot = go.Spot.Right;
          }
        }
      }
      node = nextnode;
    }

    if (diagram !== null) diagram.commitTransaction("Serpentine Layout");
  };

  // Public properties

  /**
  * Gets or sets the {@link Size} whose width specifies the horizontal space between nodes
  * and whose height specifies the minimum vertical space between nodes.
  * The default value is 30x30.
  * @name SerpentineLayout#spacing
  * @function.
  * @return {Size}
  */
  get spacing(): go.Size { return this._spacing }
  set spacing(val: go.Size) {
    if (!(val instanceof go.Size)) throw new Error("new value for SerpentineLayout.spacing must be a Size, not: " + val);
    if (!this._spacing.equals(val)) {
      this._spacing = val;
      this.invalidateLayout();
    }
  }

  /**
  * Gets or sets the total width of the layout.
  * The default value is NaN, which for {@link Diagram#layout}s means that it uses
  * the {@link Diagram#viewportBounds}.
  * @name SerpentineLayout#wrap
  * @function.
  * @return {number}
  */
  get wrap(): number { return this._wrap }
  set wrap(val: number) {
    if (this._wrap !== val) {
      this._wrap = val;
      this.invalidateLayout();
    }
  }

}


text:
export {
  Query as QueryAnnotation,
  ViewQuery as ViewQueryAnnotation,
  Attribute as AttributeAnnotation,
} from '../annotations_impl/di';


text:
using System;

namespace MindTouch.Collections {

    /// <summary>
    /// A specialized queue that uses a two-phase dequeue to retrieve items
    /// </summary>
    /// <remarks>
    /// Items dequeued are invisible to other users of the queue, but are not permanently removed until the dequeue is either committed,
    /// or rolled back, the latter action making the item availabe for dequeuing again
    /// </remarks>
    /// <seealso cref="TransactionalQueue{T}"/>
    /// <typeparam name="T">Type of entries in the queue</typeparam>
    public interface ITransactionalQueue<T> : IDisposable {

        //--- Properties ---

        /// <summary>
        /// The default timeout used for a dequeued item before the item is considered abandoned and automatically rolled back
        /// </summary>
        TimeSpan DefaultCommitTimeout { get; set; }

        /// <summary>
        /// The current count of items available for <see cref="Dequeue()"/>
        /// </summary>
        /// <remarks>
        /// Count only reflects items available for dequeue, not items pending commit or rollback
        /// </remarks>
        int Count { get; }

        //--- Methods ---

        /// <summary>
        /// Clear out the queue and drop all items.
        /// </summary>
        void Clear();

        /// <summary>
        /// Put an item into the queue
        /// </summary>
        /// <param name="item">An instance of type T</param>
        void Enqueue(T item);

        /// <summary>
        /// Get the next available item from the queue. Must call <see cref="CommitDequeue"/> to fully take possession or the item. Uses <see cref="DefaultCommitTimeout"/>.
        /// </summary>
        /// <remarks>
        /// Phase 1 of the two-phase dequeue. <see cref="CommitDequeue"/> within <see cref="DefaultCommitTimeout"/> completes the dequeue, while waiting for the timeout to
        /// expire or calling <see cref="RollbackDequeue"/> aborts the dequeue.
        /// </remarks>
        /// <returns>
        /// An instance of <see cref="ITransactionalQueueEntry{T}"/> wrapping the dequeued value and item id for use
        /// with <see cref="CommitDequeue"/> or <see cref="RollbackDequeue"/>. <see langword="null"/> if the queue is empty.
        /// </returns>
        ITransactionalQueueEntry<T> Dequeue();

        /// <summary>
        /// Get the next available item from the queue. Must call <see cref="CommitDequeue"/> to fully take possession or the item.
        /// </summary>
        /// <remarks>
        /// Phase 1 of the two-phase dequeue. <see cref="CommitDequeue"/> within <b>commitTimeout</b> completes the dequeue, while waiting for the timeout to
        /// expire or calling <see cref="RollbackDequeue"/> aborts the dequeue.
        /// </remarks>
        /// <param name="commitTimeout">Time before an uncommitted dequeue is considered abandoned and automatically rolled back</param>
        /// <returns>
        /// An instance of <see cref="ITransactionalQueueEntry{T}"/> wrapping the dequeued value and item id for use
        /// with <see cref="CommitDequeue"/> or <see cref="RollbackDequeue"/>. <see langword="null"/> if the queue is empty.
        /// </returns>
        ITransactionalQueueEntry<T> Dequeue(TimeSpan commitTimeout);

        /// <summary>
        /// Completes the two-phase <see cref="Dequeue()"/>.
        /// </summary>
        /// <param name="id"><see cref="ITransactionalQueueEntry{T}.Id"/> identifier of the dequeued item</param>
        /// <returns><see langword="true"/> if the commit succeeded, <see langword="false"/> if the item was already dequeued or has been rolled back</returns>
        bool CommitDequeue(long id);

        /// <summary>
        /// Undo <see cref="Dequeue()"/> and return item back to the queue.
        /// </summary>
        /// <param name="id"><see cref="ITransactionalQueueEntry{T}.Id"/> identifier of the dequeued item</param>
        void RollbackDequeue(long id);
    }

    /// <summary>
    /// A entry returned from <see cref="ITransactionalQueue{T}.Dequeue()"/> containing both the dequeued value and an entry Id to be
    /// used with <see cref="ITransactionalQueue{T}.CommitDequeue"/> or <see cref="ITransactionalQueue{T}.RollbackDequeue"/>.
    /// </summary>
    /// <typeparam name="T">Type of entries in the originating <see cref="ITransactionalQueue{T}"/></typeparam>
    public interface ITransactionalQueueEntry<T> {

        //--- Properties ---

        /// <summary>
        /// The dequeued value
        /// </summary>
        T Value { get; }

        /// <summary>
        /// The entry Id for use with <see cref="ITransactionalQueue{T}.CommitDequeue"/> or <see cref="ITransactionalQueue{T}.RollbackDequeue"/>.
        /// </summary>
        long Id { get; }

        /// <summary>
        /// The time at which this entry will be considered abananded and automatically rolled back.
        /// </summary>
        DateTime Expiration { get; }
    }
}