text:
<?php

namespace Phalcon\Mvc\Model;

/**
 * Phalcon\Mvc\Model\Message
 *
 * Encapsulates validation info generated before save/delete records fails
 *
 * <code>
 * use Phalcon\Mvc\Model\Message as Message;
 *
 * class Robots extends \Phalcon\Mvc\Model
 * {
 *     public function beforeSave()
 *     {
 *         if ($this->name === "Peter") {
 *             $text  = "A robot cannot be named Peter";
 *             $field = "name";
 *             $type  = "InvalidValue";
 *
 *             $message = new Message($text, $field, $type);
 *
 *             $this->appendMessage($message);
 *         }
 *     }
 * }
 * </code>
 */
class Message implements \Phalcon\Mvc\Model\MessageInterface
{

    protected $_type;

    protected $_message;

    protected $_field;

    protected $_model;

    protected $_code;

    /**
     * Phalcon\Mvc\Model\Message constructor
     *
     * @param string $message
     * @param string|array $field
     * @param string $type
     * @param \Phalcon\Mvc\ModelInterface $model
     * @param int|null $code
     */
    public function __construct($message, $field = null, $type = null, $model = null, $code = null) {}

    /**
     * Sets message type
     *
     * @param string $type
     * @return Message
     */
    public function setType($type) {}

    /**
     * Returns message type
     *
     * @return string
     */
    public function getType() {}

    /**
     * Sets verbose message
     *
     * @param string $message
     * @return Message
     */
    public function setMessage($message) {}

    /**
     * Returns verbose message
     *
     * @return string
     */
    public function getMessage() {}

    /**
     * Sets field name related to message
     *
     * @param mixed $field
     * @return Message
     */
    public function setField($field) {}

    /**
     * Returns field name related to message
     */
    public function getField() {}

    /**
     * Set the model who generates the message
     *
     * @param \Phalcon\Mvc\ModelInterface $model
     * @return Message
     */
    public function setModel(\Phalcon\Mvc\ModelInterface $model) {}

    /**
     * Sets code for the message
     *
     * @param int $code
     * @return Message
     */
    public function setCode($code) {}

    /**
     * Returns the model that produced the message
     *
     * @return \Phalcon\Mvc\ModelInterface
     */
    public function getModel() {}

    /**
     * Returns the message code
     *
     * @return int
     */
    public function getCode() {}

    /**
     * Magic __toString method returns verbose message
     *
     * @return string
     */
    public function __toString() {}

    /**
     * Magic __set_state helps to re-build messages variable exporting
     *
     * @param array $message
     * @return Message
     */
    public static function __set_state(array $message) {}

}


text:
/*
http://zobayer.blogspot.com/2010/…/getch-getche-in-gccg.html
AUTHOR: zobayer
INSTRUCTION:
just make this file a header like "conio.h"
and use the getch() and getche() functions.
*/
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
/* reads from keypress, doesn't echo */
int getch(void)
{
	struct termios oldattr, newattr;
	int ch;
	tcgetattr( STDIN_FILENO, &oldattr );
	newattr = oldattr;
	newattr.c_lflag &= ~( ICANON | ECHO );
	tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
	ch = getchar();
	tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
	return ch;
}
/* reads from keypress, and echoes */
int getche(void)
{
	struct termios oldattr, newattr;
	int ch;
	tcgetattr( STDIN_FILENO, &oldattr );
	newattr = oldattr;
	newattr.c_lflag &= ~( ICANON );
	tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
	ch = getchar();
	tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
	return ch;
}

redpajama_set_name: RedPajamaGithub


text:
package com.example.administrator.qiongyou.adapter;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.example.administrator.qiongyou.R;
import com.example.administrator.qiongyou.adapter.viewholder.CarouselViewHolder;
import com.example.administrator.qiongyou.adapter.viewholder.HotCityViewHolder;
import com.example.administrator.qiongyou.adapter.viewholder.HotDestinationViewHolder;
import com.example.administrator.qiongyou.adapter.viewholder.RecommendViewHolder;
import com.example.administrator.qiongyou.adapter.viewholder.RvHotTopicViewHolder;
import com.example.administrator.qiongyou.adapter.viewholder.RvPromoViewHolder;
import com.example.administrator.qiongyou.adapter.viewholder.RvSubcateAdapter;
import com.example.administrator.qiongyou.bean.HomeBean;
import com.example.administrator.qiongyou.bean.Recommend;

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

/**
 * Created by Administrator on 2017/3/3.
 */

public class RvHomePageAdapter extends RecyclerView.Adapter {

    private static final String TAG = RvHomePageAdapter.class.getCanonicalName();
    private final List<HomeBean.DataBean.HotDestinationBean> hotDestination;
    private List<HomeBean.DataBean.HotTopicBean> hotTopic;
    private List<HomeBean.DataBean.HeadSlideBean.SlideDataBean> slideData;
    private List<HomeBean.DataBean.BarBean> barBeanList;
    private List<HomeBean.DataBean.SubCateBean> subCate;
    private List<HomeBean.DataBean.HotCityBean> hotCity;
    private List<HomeBean.DataBean.PromoBean> promo;
    private HomeBean.DataBean dataBean;
    private Context context;
    private boolean isFirst = true;
    private int widthPixels;
    private List<Recommend.DataBean> dataBeen = new ArrayList<>();

    public RvHomePageAdapter(HomeBean.DataBean dataBean) {
        this.dataBean = dataBean;
        slideData = dataBean.getHead_slide().getSlide_data();
        barBeanList = dataBean.getBar();
        subCate = dataBean.getSub_cate();
        hotCity = dataBean.getHot_city();
        hotTopic = dataBean.getHot_topic();
        promo = dataBean.getPromo();
        hotDestination = dataBean.getHot_destination();
        dataBeen.add(null);
    }

    public void setDataBeenAndRefresh(List<Recommend.DataBean> dataBeen) {
        this.dataBeen = dataBeen;
        this.notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return 0;
        } else if (position == 1) {
            return 1;
        } else if (position == 2) {
            return 2;
        } else if (position == 3) {
            return 3;
        } else if (position == 4) {
            return 4;
        } else {
            return 5;
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        this.context = parent.getContext();
        widthPixels = context.getResources().getDisplayMetrics().widthPixels;
        View view;
        RecyclerView.ViewHolder viewHolder = null;
        LayoutInflater inflater = LayoutInflater.from(context);
        if (viewType == 0) {
            view = inflater.inflate(R.layout.rv_homepage_carousel_item, parent, false);
            viewHolder = new CarouselViewHolder(view);
        } else if (viewType == 1) {
            view = inflater.inflate(R.layout.rv_homepage_hotcity_item, parent, false);
            viewHolder = new HotCityViewHolder(view);
        } else if (viewType == 2) {
            view = inflater.inflate(R.layout.rv_homepage_promo_item, parent, false);
            viewHolder = new RvPromoViewHolder(view);
        } else if (viewType == 3) {
            view = inflater.inflate(R.layout.rv_homepage_hot_topic, parent, false);
            viewHolder = new RvHotTopicViewHolder(view);
        } else if (viewType == 4) {
            view = inflater.inflate(R.layout.rv_homepage_hot_destination, parent, false);
            viewHolder = new HotDestinationViewHolder(view);
        } else if (viewType == 5) {
            view = inflater.inflate(R.layout.rv_homepage_recommend_item, parent, false);
            viewHolder = new RecommendViewHolder(view);
        }

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if (holder instanceof CarouselViewHolder) {
            if (isFirst) {
                initCarousel(((CarouselViewHolder) holder));//轮播图
                initBar((CarouselViewHolder) holder);//bar,轮播图下方圆形小图标
                initSubCate((CarouselViewHolder) holder);//小图标下方亚类
                isFirst = false;
            }
        } else if (holder instanceof HotCityViewHolder) {
            HotCityViewHolder cityViewHolder = (HotCityViewHolder) holder;
            initCity(cityViewHolder);
        } else if (holder instanceof RvPromoViewHolder) {
            RvPromoViewHolder promoViewHolder = (RvPromoViewHolder) holder;
            initPromo(promoViewHolder);
        } else if (holder instanceof RvHotTopicViewHolder) {
            RvHotTopicViewHolder topicViewHolder = (RvHotTopicViewHolder) holder;
            initHotTopic(topicViewHolder);
        } else if (holder instanceof HotDestinationViewHolder) {
            HotDestinationViewHolder destinationViewHolder = (HotDestinationViewHolder) holder;
            initHotDestination(destinationViewHolder);
        } else if (holder instanceof RecommendViewHolder) {
            RecommendViewHolder recommendViewHolder = (RecommendViewHolder) holder;
            initRecommend(recommendViewHolder, position - 5);
        }
    }

    private void initRecommend(RecommendViewHolder holder, int position) {
        /*RecyclerView recyclerView = recommendViewHolder.recyclerView;
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        RecommendAdapter recommendAdapter = new RecommendAdapter(dataBeen);
        recyclerView.setAdapter(recommendAdapter);*/
        if (position == 0) {
            holder.tvHead.setVisibility(View.VISIBLE);
        } else {
            holder.tvHead.setVisibility(View.GONE);
        }
        Recommend.DataBean dataBean = dataBeen.get(position);
        if (dataBean != null) {
            ViewGroup.LayoutParams layoutParams = holder.imgTitle.getLayoutParams();
            layoutParams.width = widthPixels;
            layoutParams.height = (int) (widthPixels / 2.2f);
            holder.imgTitle.setLayoutParams(layoutParams);

            String pic = dataBean.getPic();
            Glide.with(context).load(pic).centerCrop()
                    .into(holder.imgTitle);
            String title = dataBean.getTitle();
            String price = dataBean.getPrice().replaceAll("<em>", "").replaceAll("</em>", "");
            holder.tvTitle.setText(title);
            holder.tvPrice.setText(price);
        }
    }

    private void initHotDestination(HotDestinationViewHolder destinationViewHolder) {
        RecyclerView recyclerView = destinationViewHolder.recyclerView;
        recyclerView.setLayoutManager(new GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false));
        RvHotDestinationAdapter rvHotDestinationAdapter = new RvHotDestinationAdapter(hotDestination);
        recyclerView.setAdapter(rvHotDestinationAdapter);
    }

    private void initHotTopic(RvHotTopicViewHolder topicViewHolder) {
        RecyclerView recyclerView = topicViewHolder.recyclerView;
        LinearLayoutManager manager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(manager);
        RvHotTopicAdapter rvHotTopicAdapter = new RvHotTopicAdapter(hotTopic);
        recyclerView.setAdapter(rvHotTopicAdapter);
    }

    private void initPromo(RvPromoViewHolder promoViewHolder) {
        ImageView leftTop = promoViewHolder.leftTop;
        ImageView rightTop = promoViewHolder.rightTop;
        ImageView leftBottom = promoViewHolder.leftBottom;
        ImageView rightBottom = promoViewHolder.rightBottom;
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) leftTop.getLayoutParams();
        layoutParams.width = (int) ((float) widthPixels / 4);
        layoutParams.height = layoutParams.width * 2;
        leftTop.setLayoutParams(layoutParams);

        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) rightTop.getLayoutParams();
        layoutParams1.width = widthPixels - layoutParams.width;
        layoutParams1.height = layoutParams1.width / 4;
        rightTop.setLayoutParams(layoutParams1);

        LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) leftBottom.getLayoutParams();
        layoutParams2.width = layoutParams1.width / 2;
        layoutParams2.height = layoutParams.height - layoutParams1.height;
        leftBottom.setLayoutParams(layoutParams2);

        rightBottom.setLayoutParams(layoutParams2);

        Glide.with(context).load(promo.get(0).getImg()).centerCrop()
                .into(leftTop);
        Glide.with(context).load(promo.get(1).getImg()).centerCrop()
                .into(rightTop);
        Glide.with(context).load(promo.get(2).getImg()).centerCrop()
                .into(leftBottom);
        Glide.with(context).load(promo.get(3).getImg()).centerCrop()
                .into(rightBottom);
    }

    private void initCity(HotCityViewHolder cityViewHolder) {
        RecyclerView recyclerView = cityViewHolder.recyclerView;
        LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(manager);
        HotCityAdapter hotCityAdapter = new HotCityAdapter(hotCity);
        recyclerView.setAdapter(hotCityAdapter);
    }

    private void initSubCate(CarouselViewHolder holder) {
        RecyclerView recyclerView = holder.recyclerView;
        GridLayoutManager manager = new GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        RvSubcateAdapter rvSubcateAdapter = new RvSubcateAdapter(subCate);
        recyclerView.setAdapter(rvSubcateAdapter);

    }

    private void initBar(CarouselViewHolder holder) {
        ViewPager vpBar = holder.vpBar;
        final LinearLayout llBarPoints = holder.llBarPoints;
        List<RecyclerView> recyclerViewList = new ArrayList<>();
        int size = barBeanList.size();

        for (int i = 0; i <= size / 8; i++) {
            int leftIndex = i * 8;
            int rightIndex = 8 * (i + 1);
            if (rightIndex >= size) {
                rightIndex = size;
            }
            GridLayoutManager gridLayoutManager =
                    new GridLayoutManager(context, 4, GridLayoutManager.VERTICAL, false);
            RecyclerView rvBar = new RecyclerView(context);
            //Log.i("AAA", "initBar: left--" + leftIndex + "--right--" + rightIndex);
            List<HomeBean.DataBean.BarBean> barBeen = barBeanList.subList(leftIndex, rightIndex);
            rvBar.setLayoutManager(gridLayoutManager);
            rvBar.setNestedScrollingEnabled(false);
            RvBarAdapter rvBarAdapter = new RvBarAdapter(barBeen);
            rvBar.setAdapter(rvBarAdapter);
            recyclerViewList.add(rvBar);
            llBarPoints.addView(getImagePoints());
        }
        setUpWithViewPager(llBarPoints, 0);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) vpBar.getLayoutParams();
        layoutParams.width = widthPixels;
        layoutParams.height = widthPixels / 3;
        vpBar.setLayoutParams(layoutParams);
        vpBar.setAdapter(new HomePageCarouselAdapter(recyclerViewList));
        vpBar.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setUpWithViewPager(llBarPoints, position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setUpWithViewPager(LinearLayout linearLayout, int position) {
        for (int i = 0; i < linearLayout.getChildCount(); i++) {
            linearLayout.getChildAt(i).setEnabled(true);
        }
        linearLayout.getChildAt(position).setEnabled(false);
    }

    private ImageView getImagePoints() {
        ImageView point = new ImageView(context);
        int px = dp2px(10);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(px, px);
        layoutParams.leftMargin = px * 2;
        point.setLayoutParams(layoutParams);
        point.setImageResource(R.drawable.point_selector);
        point.setEnabled(true);
        return point;
    }

    private void initCarousel(CarouselViewHolder holder) {
        final LinearLayout llPoints = holder.llPoints;
        List<ImageView> imgList = new ArrayList<>();
        for (int i = 0; i < slideData.size(); i++) {

            llPoints.addView(getImagePoints());

            ImageView imageView = new ImageView(context);
            String cover = slideData.get(i).getCover();
            Glide.with(context).load(cover).into(imageView);
            imgList.add(imageView);
        }

        llPoints.getChildAt(0).setEnabled(false);

        HomePageCarouselAdapter homePageCarouselAdapter = new HomePageCarouselAdapter(imgList);

        ViewPager vpCarousel = holder.vpCarousel;
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) vpCarousel.getLayoutParams();
        layoutParams.width = widthPixels;
        layoutParams.height = widthPixels / 2;
        vpCarousel.setLayoutParams(layoutParams);
        vpCarousel.setAdapter(homePageCarouselAdapter);
        vpCarousel.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setUpWithViewPager(llPoints, position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public int getItemCount() {
        return 5 + dataBeen.size();
    }

    public int dp2px(int dp) {
        int densityDpi = context.getResources().getDisplayMetrics().densityDpi;
        return densityDpi / 160 * dp;
    }

}


text:
from CIM14.CDPSM.Unbalanced.IEC61970.Core.PowerSystemResource import PowerSystemResource

class Equipment(PowerSystemResource):
    """The parts of a power system that are physical devices, electronic or mechanical
    """

    def __init__(self, normaIlyInService=False, EquipmentContainer=None, *args, **kw_args):
        """Initialises a new 'Equipment' instance.

        @param normaIlyInService: The equipment is normally in service.
        @param EquipmentContainer: The association is used in the naming hierarchy.
        """
        #: The equipment is normally in service.
        self.normaIlyInService = normaIlyInService

        self._EquipmentContainer = None
        self.EquipmentContainer = EquipmentContainer

        super(Equipment, self).__init__(*args, **kw_args)

    _attrs = ["normaIlyInService"]
    _attr_types = {"normaIlyInService": bool}
    _defaults = {"normaIlyInService": False}
    _enums = {}
    _refs = ["EquipmentContainer"]
    _many_refs = []

    def getEquipmentContainer(self):
        """The association is used in the naming hierarchy.
        """
        return self._EquipmentContainer

    def setEquipmentContainer(self, value):
        if self._EquipmentContainer is not None:
            filtered = [x for x in self.EquipmentContainer.Equipments if x != self]
            self._EquipmentContainer._Equipments = filtered

        self._EquipmentContainer = value
        if self._EquipmentContainer is not None:
            if self not in self._EquipmentContainer._Equipments:
                self._EquipmentContainer._Equipments.append(self)

    EquipmentContainer = property(getEquipmentContainer, setEquipmentContainer)


text:
package util;

import java.util.*;

import it.unimi.dsi.fastutil.ints.Int2FloatLinkedOpenHashMap;

public class MapUtil {

    /**
     * Sort a Map by value in descending order
     **
     * @param map
     * @return a sorted map
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map) {
	List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
	    public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
		return (o2.getValue()).compareTo(o1.getValue());
	    }
	});

	LinkedHashMap<K, V> result = new LinkedHashMap<K, V>();
	for (Map.Entry<K, V> entry : list) {
	    result.put(entry.getKey(), entry.getValue());
	}
	return result;
    }

    /**
     * Sort a Map by value in ascending order
     **
     * @param map
     * @return a sorted map
     */
    public static Map<Integer, Float> sortByValueAscending(final Map<Integer, Float> unsortMap) {
	// Convert Map to List
	final List<Map.Entry<Integer, Float>> list = new LinkedList<Map.Entry<Integer, Float>>(unsortMap.entrySet());
	// Sort list with comparator, to compare the Map values
	final Comparator<Map.Entry<Integer, Float>> comparator = new Comparator<Map.Entry<Integer, Float>>() {
	    public int compare(Map.Entry<Integer, Float> o1, Map.Entry<Integer, Float> o2) {
		if (o1.getValue().floatValue() > o2.getValue().floatValue()) {
		    return 1;
		} else if (o1.getValue().floatValue() < o2.getValue().floatValue()) {
		    return -1;
		} else {
		    return 0;
		}
	    }
	};
	Collections.sort(list, comparator);
	// Convert sorted map back to a Map
	Map<Integer, Float> sortedMap = new LinkedHashMap<Integer, Float>();
	for (Iterator<Map.Entry<Integer, Float>> it = list.iterator(); it.hasNext();) {
	    Map.Entry<Integer, Float> entry = it.next();
	    sortedMap.put(entry.getKey(), entry.getValue());
	}
	return sortedMap;
    }

    /**
     * Sort a Map by value in descending order
     **
     * @param similarities
     * @return a sorted map
     */
    public static  Int2FloatLinkedOpenHashMap sortByValueDescendingNew(Int2FloatLinkedOpenHashMap similarities) {

        List<Map.Entry<Integer, Float>> list = new LinkedList<Map.Entry<Integer,Float>>(similarities.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Integer, Float>>() {
            public int compare(Map.Entry<Integer, Float> o1, Map.Entry<Integer, Float> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });

        final Int2FloatLinkedOpenHashMap result = new Int2FloatLinkedOpenHashMap();
        for (Map.Entry<Integer, Float> entry : list) {
            result.put((int)entry.getKey(), (float)entry.getValue());
        }
        return result;
    }
}


text:
package guitests.guihandles;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import guitests.GuiRobot;
import javafx.scene.Node;
import javafx.scene.control.Labeled;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import seedu.ezdo.model.tag.UniqueTagList;
import seedu.ezdo.model.todo.ReadOnlyTask;
import seedu.ezdo.ui.TaskCard;

//@@author A0139177W
/**
 * Provides a handle to a task card in the task list panel.
 */
public class TaskCardHandle extends GuiHandle {
    private static final String NAME_FIELD_ID = "#name";
    private static final String STARTDATE_FIELD_ID = "#startDate";
    private static final String PRIORITY_FIELD_ID = "#priority";
    private static final String DUEDATE_FIELD_ID = "#dueDate";
    private static final String TAGS_FIELD_ID = "#tags";

    private static final String TEST_DEFAULT_PRIORITY_NUMBER = "";
    private static final String TEST_DEFAULT_PRIORITY_COLOR = "transparent";

    private static final String TEST_HIGH_PRIORITY_NUMBER = "1";
    private static final String TEST_HIGH_PRIORITY_COLOR = "red";

    private static final String TEST_MEDIUM_PRIORITY_NUMBER = "2";
    private static final String TEST_MEDIUM_PRIORITY_COLOR = "orange";

    private static final String TEST_LOW_PRIORITY_NUMBER = "3";
    private static final String TEST_LOW_PRIORITY_COLOR = "green";

    public static final HashMap<String, String> TEST_PRIORITY_COLOR_HASHMAP = new HashMap<>();

    private Node node;

    /**
     * Initialises TaskCardHandle and TEST_PRIORITY_COLOR_HASHMAP.
     */
    public TaskCardHandle(GuiRobot guiRobot, Stage primaryStage, Node node) {
        super(guiRobot, primaryStage, null);
        setTestPriorityColorHashMap();
        this.node = node;
    }

    /** Returns text from label **/
    protected String getTextFromLabel(String fieldId) {
        return getTextFromLabel(fieldId, node);
    }

    /** Returns task name from label **/
    public String getFullName() {
        return getTextFromLabel(NAME_FIELD_ID);
    }

    /** Returns start date from label **/
    public String getStartDate() {
        return getTextFromLabel(STARTDATE_FIELD_ID);
    }

    /** Returns due date from label **/
    public String getDueDate() {
        return getTextFromLabel(DUEDATE_FIELD_ID);
    }

    /** Returns priority from label **/
    public String getPriority() {
        return getTextFromLabel(PRIORITY_FIELD_ID);
    }

    /** Returns priority color of the task **/
    public String getTaskPriorityColor() {
        String priority = getPriority();
        return TaskCard.PRIORITY_COLOR_HASHMAP.get(priority);
    }
    //@@author

    /** Returns tags from task **/
    public List<String> getTags() {
        return getTags(getTagsContainer());
    }

    /** Return tags from tagsContainer **/
    private List<String> getTags(Region tagsContainer) {
        return tagsContainer.getChildrenUnmodifiable().stream().map(node -> ((Labeled) node).getText())
                .collect(Collectors.toList());
    }
    /** Return tags from a list of tags **/
    private List<String> getTags(UniqueTagList tags) {
        return tags.asObservableList().stream().sorted((f1, f2) -> f1.tagName.compareTo(f2.tagName))
                .map(tag -> tag.tagName).collect(Collectors.toList());
    }

    private Region getTagsContainer() {
        return guiRobot.from(node).lookup(TAGS_FIELD_ID).query();
    }
    //@@author A0139177W
    /** Sets priority numbers and its corresponding colors in TEST_PRIORITY_COLOR_HASHMAP. **/
    private void setTestPriorityColorHashMap() {
        TEST_PRIORITY_COLOR_HASHMAP.put(TEST_DEFAULT_PRIORITY_NUMBER, TEST_DEFAULT_PRIORITY_COLOR);
        TEST_PRIORITY_COLOR_HASHMAP.put(TEST_LOW_PRIORITY_NUMBER, TEST_LOW_PRIORITY_COLOR);
        TEST_PRIORITY_COLOR_HASHMAP.put(TEST_MEDIUM_PRIORITY_NUMBER, TEST_MEDIUM_PRIORITY_COLOR);
        TEST_PRIORITY_COLOR_HASHMAP.put(TEST_HIGH_PRIORITY_NUMBER, TEST_HIGH_PRIORITY_COLOR);
    }
    //@@author

    /** Checks if two tasks are the same. **/
    public boolean isSameTask(ReadOnlyTask task) {
        List<String> taskTags = getTags(task.getTags());
        List<String> cardTags = getTags();
        boolean equalTags = taskTags.containsAll(cardTags) && cardTags.containsAll(taskTags);
        return getFullName().equals(task.getName().fullName) && getPriority().equals(task.getPriority().value)
                && getTaskPriorityColor().equals(TEST_PRIORITY_COLOR_HASHMAP.get(getPriority()))
                && getStartDate().equals(task.getStartDate().value) && getDueDate().equals(task.getDueDate().value)
                && equalTags;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof TaskCardHandle) {
            TaskCardHandle handle = (TaskCardHandle) obj;
            return getFullName().equals(handle.getFullName()) && getPriority().equals(handle.getPriority())
                    && getTaskPriorityColor().equals(TEST_PRIORITY_COLOR_HASHMAP.get(getPriority()))
                    && getStartDate().equals(handle.getStartDate()) && getTags().equals(handle.getTags());
        }
        return super.equals(obj);
    }

    @Override
    public String toString() {
        String space = " ";
        return getFullName() + space + getStartDate();
    }
}
//@@author


text:
<package>
  <name>hector_quadrotor_controller</name>
  <version>0.3.5</version>
  <description>hector_quadrotor_controller provides libraries and a node for quadrotor control using ros_control.</description>
  <maintainer email="meyer@fsr.tu-darmstadt.de">Johannes Meyer</maintainer>

  <license>BSD</license>

  <url type="website">http://ros.org/wiki/hector_quadrotor_controller</url>
  <url type="bugtracker">https://github.com/tu-darmstadt-ros-pkg/hector_quadrotor/issues</url>

  <author email="meyer@fsr.tu-darmstadt.de">Johannes Meyer</author>

  <buildtool_depend>catkin</buildtool_depend>

  <build_depend>roscpp</build_depend>
  <build_depend>geometry_msgs</build_depend>
  <build_depend>sensor_msgs</build_depend>
  <build_depend>nav_msgs</build_depend>
  <build_depend>hector_uav_msgs</build_depend>
  <build_depend>std_srvs</build_depend>
  <build_depend>hardware_interface</build_depend>
  <build_depend>controller_interface</build_depend>

  <run_depend>roscpp</run_depend>
  <run_depend>geometry_msgs</run_depend>
  <run_depend>sensor_msgs</run_depend>
  <run_depend>nav_msgs</run_depend>
  <run_depend>hector_uav_msgs</run_depend>
  <run_depend>std_srvs</run_depend>
  <run_depend>hardware_interface</run_depend>
  <run_depend>controller_interface</run_depend>

  <export>
    <controller_interface plugin="${prefix}/plugin.xml"/>
  </export>
</package>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Pap. 116: 42 (1969)

#### Original name
Trichoderma longibrachiatum Rifai, 1969

### Remarks
null


text:
<?php

/**
 * @file
 * Tests for ChapterThree\AppleNewsAPI\Document\Behaviors\Springy.
 */

use ChapterThree\AppleNewsAPI\Document\Behaviors\Springy;

/**
 * Tests for the Springy class.
 */
class SpringyTest extends PHPUnit_Framework_TestCase {

  /**
   * Setting properties and outputting json.
   */
  public function testSetters() {

    $expected = '{"type":"springy"}';

    $obj = new Springy();
    $this->assertJsonStringEqualsJsonString($expected, $obj->json());

  }

}


text: StandardMaterial Prefabs::material;


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

<title>Y-Index</title>
<meta name="date" content="2021-01-31">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Y

Y - Static variable in class math.doubleV.AbstractAxes

Y - Static variable in class math.doubleV.AbstractBasis

Y - Static variable in class math.doubleV.RotationOrder

Y - Static variable in class math.doubleV.sgRayd

y - Variable in class math.doubleV.Vec3d

the y-component of this vector

Y - Static variable in class math.doubleV.Vec3d

Y - Static variable in class math.floatV.AbstractAxes

Y - Static variable in class math.floatV.AbstractBasis

Y - Static variable in class math.floatV.RotationOrder

Y - Static variable in class math.floatV.sgRayf

y - Variable in class math.floatV.Vec3f

the y-component of this vector

Y - Static variable in class math.floatV.Vec3f

y_() - Method in class math.doubleV.AbstractAxes

return a ray / segment representing this Axes global y basis position and direction and magnitude

y_() - Method in class math.doubleV.CartesianAxes

y_() - Method in class math.floatV.AbstractAxes

return a ray / segment representing this Axes global y basis position and direction and magnitude

y_() - Method in class math.floatV.CartesianAxes

YXY - Static variable in class math.doubleV.RotationOrder

Set of Euler angles.

YXY - Static variable in class math.floatV.RotationOrder

Set of Euler angles.

YXZ - Static variable in class math.doubleV.RotationOrder

Set of Cardan angles.

YXZ - Static variable in class math.floatV.RotationOrder

Set of Cardan angles.

YZX - Static variable in class math.doubleV.RotationOrder

Set of Cardan angles.

YZX - Static variable in class math.floatV.RotationOrder

Set of Cardan angles.

YZY - Static variable in class math.doubleV.RotationOrder

Set of Euler angles.

YZY - Static variable in class math.floatV.RotationOrder

Set of Euler angles.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package com.jakewharton.rxbinding2.widget;

import android.app.Instrumentation;
import android.support.test.InstrumentationRegistry;
import android.support.test.annotation.UiThreadTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.PopupMenu;
import com.jakewharton.rxbinding2.RecordingObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;

@RunWith(AndroidJUnit4.class) public final class RxPopupMenuTest {
  @Rule public final ActivityTestRule<RxPopupMenuTestActivity> activityRule =
      new ActivityTestRule<>(RxPopupMenuTestActivity.class);

  private final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

  PopupMenu view;

  @Before public void setUp() {
    view = activityRule.getActivity().popupMenu;
  }

  @Test @UiThreadTest public void itemClicks() {
    Menu menu = view.getMenu();
    MenuItem item1 = menu.add(0, 1, 0, "Hi");
    MenuItem item2 = menu.add(0, 2, 0, "Hey");

    RecordingObserver<MenuItem> o = new RecordingObserver<>();
    RxPopupMenu.itemClicks(view).subscribe(o);
    o.assertNoMoreEvents();

    menu.performIdentifierAction(2, 0);
    assertSame(item2, o.takeNext());

    menu.performIdentifierAction(1, 0);
    assertSame(item1, o.takeNext());

    o.dispose();

    menu.performIdentifierAction(2, 0);
    o.assertNoMoreEvents();
  }

  @Test public void dismisses() {
    RecordingObserver<Object> o = new RecordingObserver<>();
    RxPopupMenu.dismisses(view).subscribeOn(AndroidSchedulers.mainThread()).subscribe(o);
    o.assertNoMoreEvents(); // No initial value.

    instrumentation.runOnMainSync(new Runnable() {
      @Override public void run() {
        view.show();
      }
    });
    o.assertNoMoreEvents();

    instrumentation.runOnMainSync(new Runnable() {
      @Override public void run() {
        view.dismiss();
      }
    });
    assertNotNull(o.takeNext());

    o.dispose();
    instrumentation.runOnMainSync(new Runnable() {
      @Override public void run() {
        view.show();
      }
    });
    instrumentation.runOnMainSync(new Runnable() {
      @Override public void run() {
        view.dismiss();
      }
    });

    o.assertNoMoreEvents();
  }
}


text:
This example illustrates the class
:doxygen:`MeanRatioImageFilter` for detecting changes
between pairs of images. This filter computes the mean intensity in
the neighborhood of each pixel of the pair of images to be compared
and uses the ratio of means as a change indicator. This change
indicator is then normalized between 0 and 1 by using the classical

.. math::

    r = 1 - min\{\frac{\mu_A}{\mu_B},\frac{\mu_B}{\mu_A} \}

where :math:`\mu_A` and :math:`\mu_B` are the local means.

.. |image1| image:: /Input/GomaAvant.png

.. |image2| image:: /Input/GomaApres.png

.. |image3| image:: /Output/RatioChDet.png

.. _Figure1:

+--------------------------+-------------------------+-------------------------+
|        |image1|          |         |image2|        |         |image3|        |
+--------------------------+-------------------------+-------------------------+

    Radarsat fine mode acquisitions before (left) and after (middle) a lava flow
    resulting from a volcanic eruption. On the right is the result of the change
    detection by ratio of local means.


text:
{-# language CPP #-}
-- No documentation found for Chapter "DeviceCreateFlags"
module Vulkan.Core10.Enums.DeviceCreateFlags  (DeviceCreateFlags(..)) where

import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showString)
import Numeric (showHex)
import Vulkan.Zero (Zero)
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Foreign.Storable (Storable)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import Vulkan.Core10.FundamentalTypes (Flags)
-- | VkDeviceCreateFlags - Reserved for future use
--
-- = Description
--
-- 'DeviceCreateFlags' is a bitmask type for setting a mask, but is
-- currently reserved for future use.
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
-- 'Vulkan.Core10.Device.DeviceCreateInfo'
newtype DeviceCreateFlags = DeviceCreateFlags Flags
  deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)

conNameDeviceCreateFlags :: String
conNameDeviceCreateFlags = "DeviceCreateFlags"

enumPrefixDeviceCreateFlags :: String
enumPrefixDeviceCreateFlags = ""

showTableDeviceCreateFlags :: [(DeviceCreateFlags, String)]
showTableDeviceCreateFlags = []

instance Show DeviceCreateFlags where
  showsPrec =
    enumShowsPrec
      enumPrefixDeviceCreateFlags
      showTableDeviceCreateFlags
      conNameDeviceCreateFlags
      (\(DeviceCreateFlags x) -> x)
      (\x -> showString "0x" . showHex x)

instance Read DeviceCreateFlags where
  readPrec =
    enumReadPrec
      enumPrefixDeviceCreateFlags
      showTableDeviceCreateFlags
      conNameDeviceCreateFlags
      DeviceCreateFlags


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright (C) 2008 ZXing authors

 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.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.zxing.client.android" > <!-- Support Android 2.3+. -->
    <uses-sdk android:minSdkVersion="9" />

    <uses-permission android:name="android.permission.CAMERA" />

    <!-- Don't require camera, as this requires a rear camera. This allows it to work on the Nexus 7 -->
    <uses-feature
        android:name="android.hardware.camera"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.front"
        android:required="false" />
    <!-- TODO replace above two with next line after Android 4.2 -->
    <!-- <uses-feature android:name="android.hardware.camera.any"/> -->
    <uses-feature
        android:name="android.hardware.camera.autofocus"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.camera.flash"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.screen.landscape"
        android:required="false" />
    <uses-feature
        android:name="android.hardware.wifi"
        android:required="false" />

    <application>
        <activity
            android:name="com.journeyapps.barcodescanner.CaptureActivity"
            android:clearTaskOnLaunch="true"
            android:screenOrientation="sensorLandscape"
            android:stateNotNeeded="true"
            android:theme="@style/zxing_CaptureTheme"
            android:windowSoftInputMode="stateAlwaysHidden" />
    </application>

</manifest>


text:
<?php

namespace Respect\Validation\Rules;

$GLOBALS['is_readable'] = null;

function is_readable($readable)
{
    $return = \is_readable($readable); // Running the real function
    if (null !== $GLOBALS['is_readable']) {
        $return = $GLOBALS['is_readable'];
        $GLOBALS['is_readable'] = null;
    }

    return $return;
}

/**
 * @group  rule
 * @covers Respect\Validation\Rules\Readable
 * @covers Respect\Validation\Exceptions\ReadableException
 */
class ReadableTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Respect\Validation\Rules\Readable::validate
     */
    public function testValidReadableFileShouldReturnTrue()
    {
        $GLOBALS['is_readable'] = true;

        $rule = new Readable();
        $input = '/path/of/a/valid/readable/file.txt';
        $this->assertTrue($rule->validate($input));
    }

    /**
     * @covers Respect\Validation\Rules\Readable::validate
     */
    public function testInvalidReadableFileShouldReturnFalse()
    {
        $GLOBALS['is_readable'] = false;

        $rule = new Readable();
        $input = '/path/of/an/invalid/readable/file.txt';
        $this->assertFalse($rule->validate($input));
    }

    /**
     * @covers Respect\Validation\Rules\Readable::validate
     */
    public function testShouldValidateObjects()
    {
        $rule = new Readable();
        $object = $this->getMock('SplFileInfo', ['isReadable'], ['somefile.txt']);
        $object->expects($this->once())
                ->method('isReadable')
                ->will($this->returnValue(true));

        $this->assertTrue($rule->validate($object));
    }
}


text: from l8 import *


text:
layout: null
limit: 10
---
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
{% if site.url %}
    {% capture base %}http://{{ site.url }}{% endcapture %}
{% elsif site.github.url %}
    {% assign base = site.github.url %}
{% endif %}
    <title>{{ site.name }}</title>
    {% if site.description %}<subtitle>{{ site.description }}</subtitle>{% endif %}
    <link href="{{ base }}{{ page.url }}" type="application/atom+xml" rel="self"/>
    <link href="{{ base }}/" rel="alternate" type="text/html"/>
    <link href="https://pubsubhubbub.superfeedr.com" rel="hub"/>
    <updated>{{ site.time | date_to_xmlschema }}</updated>
    <id>{{ base }}/</id>
    <author>
        <name>{{ site.name }}</name>
        <uri>{{ base }}</uri>
    </author>

    {% for post in site.posts limit: page.limit %}
    <entry>
        <title>{{ post.title | xml_escape }}</title>
        <link href="{{ base }}{{ post.url }}"/>
        <updated>{{ post.date | date_to_xmlschema }}</updated>
        <id>{{ base }}{{ post.id }}</id>
        {% if post.author.name or post.author.email or post.author.url %}
        <author>
            {% if post.author.name %}<name>{{ post.author.name }}</name>{% endif %}
            {% if post.author.email %}<email>{{ post.author.email }}</email>{% endif %}
            {% if post.author.url %}<uri>{{ post.author.url }}</uri>{% endif %}
        </author>
        {% endif %}
        <category term="{{ post.categories }}" />
        <content type="html">{{ post.content | xml_escape }}</content>
    </entry>
    {% endfor %}
</feed>


text:
package com.urswolfer.gerrit.client.rest.http;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.CharStreams;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gson.*;
import com.urswolfer.gerrit.client.rest.GerritAuthData;
import com.urswolfer.gerrit.client.rest.RestClient;
import com.urswolfer.gerrit.client.rest.Version;
import com.urswolfer.gerrit.client.rest.gson.DateDeserializer;
import com.urswolfer.gerrit.client.rest.gson.DateSerializer;
import org.apache.http.*;
import org.apache.http.auth.*;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.*;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Urs Wolfer
 */
public class GerritRestClient implements RestClient {

    private static final String JSON_MIME_TYPE = ContentType.APPLICATION_JSON.getMimeType();
    private static final Pattern GERRIT_AUTH_PATTERN = Pattern.compile(".*?xGerritAuth=\"(.+?)\"");
    private static final int CONNECTION_TIMEOUT_MS = 30000;
    private static final String PREEMPTIVE_AUTH = "preemptive-auth";
    private static final Gson GSON = initGson();

    private final GerritAuthData authData;
    private final HttpRequestExecutor httpRequestExecutor;
    private final List<HttpClientBuilderExtension> httpClientBuilderExtensions;

    private final BasicCookieStore cookieStore;
    private final LoginCache loginCache;

    public GerritRestClient(GerritAuthData authData,
                            HttpRequestExecutor httpRequestExecutor,
                            HttpClientBuilderExtension... httpClientBuilderExtensions) {
        this.authData = authData;
        this.httpRequestExecutor = httpRequestExecutor;
        this.httpClientBuilderExtensions = Arrays.asList(httpClientBuilderExtensions);

        cookieStore = new BasicCookieStore();
        loginCache = new LoginCache(authData, cookieStore);
    }

    @Override
    public Gson getGson() {
        return GSON;
    }

    @Override
    public JsonElement getRequest(String path) throws RestApiException {
        return requestJson(path, null, HttpVerb.GET);
    }

    @Override
    public JsonElement postRequest(String path, String requestBody) throws RestApiException {
        return requestJson(path, requestBody, HttpVerb.POST);
    }

    @Override
    public JsonElement putRequest(String path) throws RestApiException {
        return putRequest(path, null);
    }

    @Override
    public JsonElement putRequest(String path, String requestBody) throws RestApiException {
        return requestJson(path, requestBody, HttpVerb.PUT);
    }

    @Override
    public JsonElement deleteRequest(String path) throws RestApiException {
        return requestJson(path, null, HttpVerb.DELETE);
    }

    @Override
    public JsonElement requestJson(String path, String requestBody, HttpVerb verb) throws RestApiException {
        try {
            HttpResponse response = requestRest(path, requestBody, verb);

            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }

            checkContentType(entity);

            JsonElement ret = parseResponse(entity.getContent());
            if (ret.isJsonNull()) {
                throw new RestApiException("Unexpectedly empty response.");
            }
            return ret;
        } catch (IOException e) {
            throw new RestApiException("Request failed.", e);
        }
    }

    @Override
    public HttpResponse requestRest(String path,
                                    String requestBody,
                                    HttpVerb verb) throws IOException, HttpStatusException {
        BasicHeader acceptHeader = new BasicHeader("Accept", JSON_MIME_TYPE);
        return request(path, requestBody, verb, acceptHeader);
    }

    @Override
    public HttpResponse request(String path,
                                String requestBody,
                                HttpVerb verb,
                                Header... headers) throws IOException, HttpStatusException {
        HttpContext httpContext = new BasicHttpContext();
        HttpClientBuilder client = getHttpClient(httpContext);

        Optional<String> gerritAuthOptional = updateGerritAuthWhenRequired(httpContext, client);

        String uri = authData.getHost();
        // only use /a when http login is required (i.e. we haven't got a gerrit-auth cookie)
        // it would work in most cases also with /a, but it breaks with HTTP digest auth ("Forbidden" returned)
        if (authData.isLoginAndPasswordAvailable() && !gerritAuthOptional.isPresent()) {
            uri += "/a";
        }
        uri += path;

        HttpRequestBase method;
        switch (verb) {
            case POST:
                method = new HttpPost(uri);
                setRequestBody(requestBody, method);
                break;
            case GET:
                method = new HttpGet(uri);
                break;
            case DELETE:
                method = new HttpDelete(uri);
                break;
            case PUT:
                method = new HttpPut(uri);
                setRequestBody(requestBody, method);
                break;
            default:
                throw new IllegalStateException("Unknown or unsupported HttpVerb method: " + verb.toString());
        }
        if (gerritAuthOptional.isPresent()) {
            method.addHeader("X-Gerrit-Auth", gerritAuthOptional.get());
        }

        for (Header header : headers) {
            method.addHeader(header);
        }

        HttpResponse response = httpRequestExecutor.execute(client, method, httpContext);

        if (response.getStatusLine().getStatusCode() == 403 && loginCache.getGerritAuthOptional().isPresent()) {
            // handle expired sessions: try again with a fresh login
            loginCache.invalidate();
            response = requestRest(path, requestBody, verb);
        }

        checkStatusCode(response);

        return response;
    }

    private void setRequestBody(String requestBody, HttpRequestBase method) {
        if (requestBody != null) {
            ((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
        }
    }

    private Optional<String> updateGerritAuthWhenRequired(HttpContext httpContext, HttpClientBuilder client) throws IOException {
        if (!loginCache.getHostSupportsGerritAuth()) {
            // We do not not need a cookie here since we are sending credentials as HTTP basic / digest header again.
            // In fact cookies could hurt: googlesource.com Gerrit instances block requests which send a magic cookie
            // named "gi" with a 400 HTTP status (as of 01/29/15).
            cookieStore.clear();
            return Optional.absent();
        }
        Optional<Cookie> gerritAccountCookie = findGerritAccountCookie();
        if (!gerritAccountCookie.isPresent() || gerritAccountCookie.get().isExpired(new Date())) {
            return updateGerritAuth(httpContext, client);
        }
        return loginCache.getGerritAuthOptional();
    }

    private Optional<String> updateGerritAuth(HttpContext httpContext, HttpClientBuilder client) throws IOException {
        Optional<String> gerritAuthOptional = tryGerritHttpAuth(client, httpContext)
            .or(tryGerritHttpFormAuth(client, httpContext));
        loginCache.setGerritAuthOptional(gerritAuthOptional);
        return gerritAuthOptional;
    }

    /**
     * Handles LDAP auth (but not LDAP_HTTP) which uses a HTML form.
     */
    private Optional<String> tryGerritHttpFormAuth(HttpClientBuilder client, HttpContext httpContext) throws IOException {
        if (!authData.isLoginAndPasswordAvailable()) {
            return Optional.absent();
        }
        String loginUrl = authData.getHost() + "/login/";
        HttpPost method = new HttpPost(loginUrl);
        List<BasicNameValuePair> parameters = Lists.newArrayList(
            new BasicNameValuePair("username", authData.getLogin()),
            new BasicNameValuePair("password", authData.getPassword())
        );
        method.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
        HttpResponse loginResponse = httpRequestExecutor.execute(client, method, httpContext);
        return extractGerritAuth(loginResponse);
    }

    /**
     * Try to authenticate against Gerrit instances with HTTP auth (not OAuth or something like that).
     * In case of success we get a GerritAccount cookie. In that case no more login credentials need to be sent as
     * long as we use the *same* HTTP client. Even requests against authenticated rest api (/a) will be processed
     * with the GerritAccount cookie.
     *
     * This is a workaround for "double" HTTP authentication (i.e. reverse proxy *and* Gerrit do HTTP authentication
     * for rest api (/a)).
     *
     * Following old notes from README about the issue:
     * If you have correctly set up a HTTP Password in Gerrit, but still have authentication issues, your Gerrit instance
     * might be behind a HTTP Reverse Proxy (like Nginx or Apache) with enabled HTTP Authentication. You can identify that if
     * you have to enter an username and password (browser password request) for opening the Gerrit web interface. Since this
     * plugin uses Gerrit REST API (with authentication enabled), you need to tell your system administrator that he should
     * disable HTTP Authentication for any request to <code>/a</code> path (e.g. https://git.example.com/a). For these requests
     * HTTP Authentication is done by Gerrit (double HTTP Authentication will not work). For more information see
     * [Gerrit documentation].
     * [Gerrit documentation]: https://gerrit-review.googlesource.com/Documentation/rest-api.html#authentication
     */
    private Optional<String> tryGerritHttpAuth(HttpClientBuilder client, HttpContext httpContext) throws IOException {
        String loginUrl = authData.getHost() + "/login/";
        HttpResponse loginResponse = httpRequestExecutor.execute(client, new HttpGet(loginUrl), httpContext);
        return extractGerritAuth(loginResponse);
    }

    private Optional<String> extractGerritAuth(HttpResponse loginResponse) throws IOException {
        if (loginResponse.getStatusLine().getStatusCode() != HttpStatus.SC_UNAUTHORIZED) {
            Optional<Cookie> gerritAccountCookie = findGerritAccountCookie();
            if (gerritAccountCookie.isPresent()) {
                Matcher matcher = GERRIT_AUTH_PATTERN.matcher(EntityUtils.toString(loginResponse.getEntity(), Consts.UTF_8));
                if (matcher.find()) {
                    return Optional.of(matcher.group(1));
                }
            }
        }
        return Optional.absent();
    }

    private Optional<Cookie> findGerritAccountCookie() {
        List<Cookie> cookies = cookieStore.getCookies();
        return Iterables.tryFind(cookies, new Predicate<Cookie>() {
            @Override
            public boolean apply(Cookie cookie) {
                return cookie.getName().equals("GerritAccount");
            }
        });
    }

    private HttpClientBuilder getHttpClient(HttpContext httpContext) {
        HttpClientBuilder client = HttpClients.custom();

        client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

        // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
        client.setRedirectStrategy(new LaxRedirectStrategy());

        httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

        RequestConfig.Builder requestConfig = RequestConfig.custom()
                .setConnectTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to connect to remote host
                .setSocketTimeout(CONNECTION_TIMEOUT_MS) // how long it takes to retrieve data from remote host
                .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS);
        client.setDefaultRequestConfig(requestConfig.build());

        CredentialsProvider credentialsProvider = getCredentialsProvider();
        client.setDefaultCredentialsProvider(credentialsProvider);

        if (authData.isLoginAndPasswordAvailable()) {
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

            BasicScheme basicAuth = new BasicScheme();
            httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
            client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
        }

        client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

        for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
            client = httpClientBuilderExtension.extend(client, authData);
            credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider, authData);
        }

        return client;
    }

    /**
     * With this impl, it only returns the same credentials once. Otherwise it's possible that a loop will occur.
     * When server returns status code 401, the HTTP client provides the same credentials forever.
     * Since we create a new HTTP client for every request, we can handle it this way.
     */
    private BasicCredentialsProvider getCredentialsProvider() {
        return new BasicCredentialsProvider() {
            private Set<AuthScope> authAlreadyTried = Sets.newHashSet();

            @Override
            public Credentials getCredentials(AuthScope authscope) {
                if (authAlreadyTried.contains(authscope)) {
                    return null;
                }
                authAlreadyTried.add(authscope);
                return super.getCredentials(authscope);
            }
        };
    }

    private JsonElement parseResponse(InputStream response) throws IOException {
        Reader reader = new InputStreamReader(response, Consts.UTF_8);
        try {
            return new JsonParser().parse(reader);
        } catch (JsonSyntaxException jse) {
            throw new IOException(String.format("Couldn't parse response: %n%s", CharStreams.toString(reader)), jse);
        } finally {
            reader.close();
        }
    }

    private void checkStatusCode(HttpResponse response) throws HttpStatusException, IOException {
        StatusLine statusLine = response.getStatusLine();
        int code = statusLine.getStatusCode();
        switch (code) {
            case HttpStatus.SC_OK:
            case HttpStatus.SC_CREATED:
            case HttpStatus.SC_ACCEPTED:
            case HttpStatus.SC_NO_CONTENT:
                return;
            case HttpStatus.SC_BAD_REQUEST:
            case HttpStatus.SC_UNAUTHORIZED:
            case HttpStatus.SC_PAYMENT_REQUIRED:
            case HttpStatus.SC_FORBIDDEN:
            default:
                String body = "<empty>";
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    body = EntityUtils.toString(entity).trim();
                }
                String message = String.format("Request not successful. Message: %s. Status-Code: %s. Content: %s.",
                        statusLine.getReasonPhrase(), statusLine.getStatusCode(), body);
                throw new HttpStatusException(statusLine.getStatusCode(), statusLine.getReasonPhrase(), message);
        }
    }

    private void checkContentType(HttpEntity entity) throws RestApiException {
        Header contentType = entity.getContentType();
        if (contentType != null && !contentType.getValue().contains(JSON_MIME_TYPE)) {
            throw new RestApiException(String.format("Expected JSON but got '%s'.", contentType.getValue()));
        }
    }

    /**
     * With preemptive auth, it will send the basic authentication response even before the server gives an unauthorized
     * response in certain situations, thus reducing the overhead of making the connection again.
     *
     * Based on:
     * https://subversion.jfrog.org/jfrog/build-info/trunk/build-info-client/src/main/java/org/jfrog/build/client/PreemptiveHttpClient.java
     */
    private static class PreemptiveAuthHttpRequestInterceptor implements HttpRequestInterceptor {
        private GerritAuthData authData;

        public PreemptiveAuthHttpRequestInterceptor(GerritAuthData authData) {
            this.authData = authData;
        }

        public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

            // if no auth scheme available yet, try to initialize it preemptively
            if (authState.getAuthScheme() == null) {
                AuthScheme authScheme = (AuthScheme) context.getAttribute(PREEMPTIVE_AUTH);
                UsernamePasswordCredentials creds = new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword());
                authState.update(authScheme, creds);
            }
        }
    }

    private static class UserAgentHttpRequestInterceptor implements HttpRequestInterceptor {

        public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            Header existingUserAgent = request.getFirstHeader(HttpHeaders.USER_AGENT);
            String userAgent = String.format("gerrit-rest-java-client/%s", Version.get());
            userAgent += " using " + existingUserAgent.getValue();
            request.setHeader(HttpHeaders.USER_AGENT, userAgent);
        }
    }

    private static Gson initGson() {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Date.class, new DateDeserializer());
        builder.registerTypeAdapter(Date.class, new DateSerializer());
        builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        return builder.create();
    }
}


text:
![Hoverfly](core/static/img/hoverfly_logo.png)

[![Circle CI][CircleCI-Image]][CircleCI-Url]
[![Documentation Status](https://readthedocs.org/projects/hoverfly/badge/?version=latest)](http://hoverfly.readthedocs.io/en/latest/?badge=latest)
[![Join the chat at https://gitter.im/SpectoLabs/hoverfly](https://badges.gitter.im/SpectoLabs/hoverfly.svg)](https://gitter.im/SpectoLabs/hoverfly?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

## API simulations for development and testing

Hoverfly is a lightweight, open source API simulation tool. Using Hoverfly, you can create realistic simulations of the APIs your application depends on.

* Replace slow, flaky API dependencies with realistic, re-usable simulations
* Simulate network latency, random failures or rate limits to test edge-cases
* Extend and customize with any programming language
* Export, share, edit and import API simulations
* CLI and native language bindings for [Java](https://hoverfly-java.readthedocs.io/en/latest/) and [Python](https://hoverpy.readthedocs.io/en/latest/)
* REST API
* Lightweight, high-performance, run anywhere
* Apache 2 license

Hoverfly is developed and maintained by [SpectoLabs](https://specto.io).

## Quickstart

* [Download and installation](https://hoverfly.readthedocs.io/en/latest/pages/introduction/downloadinstallation.html)
* [Read the docs](https://hoverfly.readthedocs.io)
* [Join the mailing list](https://groups.google.com/a/specto.io/forum/#!forum/hoverfly)

## Contributing

Contributions are welcome!

To contribute, please:

1. Fork the repository
1. Create a feature branch on your fork
1. Commit your changes, and create a pull request against Hoverfly's master branch
1. In your pull request, include details regarding your change, i.e
    1. why you made it
    1. how to test it
    1. any information about testing you have performed

To read more about forking model, check out this link: [forking workflow](https://www.atlassian.com/git/tutorials/comparing-workflows/forking-workflow).

## Building, running & testing

```bash
cd $GOPATH/src
mkdir -p github.com/SpectoLabs/
cd github.com/SpectoLabs/
git clone https://github.com/SpectoLabs/hoverfly.git
# or: git clone https://github.com/<your_username>/hoverfly.git
cd hoverfly
make build
```

Notice the binaries are in the ``target`` directory.

Finally to test your build:

```bash
make test
```

## License

Apache License version 2.0 [See LICENSE for details](https://github.com/SpectoLabs/hoverfly/blob/master/LICENSE).

(c) [SpectoLabs](https://specto.io) 2017.

[CircleCI-Image]: https://circleci.com/gh/SpectoLabs/hoverfly.svg?style=shield
[CircleCI-Url]: https://circleci.com/gh/SpectoLabs/hoverfly


text:
#pragma once

#include "w_graphics_device_manager.h"
#include "w_texture.h"
#include <python_exporter/w_boost_python_helper.h>

namespace wolf::render::vulkan
{
	enum w_shader_binding_type
	{
		SAMPLER2D = 0,
		SAMPLER,
		UNIFORM,
		IMAGE,
		STORAGE
	};

	struct w_pipeline_shader_stage_create_info : public
#ifdef __VULKAN__
		VkPipelineShaderStageCreateInfo
#endif
	{
	};

	struct w_shader_binding_param
	{
		//index of shader variable
		uint32_t                    index;
		//type of shader variable
		w_shader_binding_type       type;
		//shader stage flags
		w_shader_stage_flag_bits    stage;
		//descriptor buffer info
		w_descriptor_buffer_info    buffer_info;
		//descriptor image info
		w_descriptor_image_info     image_info;
	};

	class w_shader_pimp;
	class w_shader
	{
	public:
		W_VK_EXP w_shader();
		W_VK_EXP virtual ~w_shader();

		//load shader from binary file
		W_VK_EXP W_RESULT load(_In_ const std::shared_ptr<w_graphics_device>& pGDevice,
			_In_z_ const std::wstring& pShaderBinaryPath,
			_In_ const w_shader_stage_flag_bits& pShaderStage,
			_In_z_ const std::string& pMainFunctionName = "main");

		//release all resources
		W_VK_EXP ULONG release();

#pragma region Getters

		W_VK_EXP const std::vector<w_shader_binding_param> get_shader_binding_params() const;
		W_VK_EXP const std::vector<w_pipeline_shader_stage_create_info>* get_shader_stages() const;
		W_VK_EXP const w_pipeline_shader_stage_create_info get_compute_shader_stage() const;

		W_VK_EXP const w_descriptor_set get_descriptor_set() const;
		W_VK_EXP const w_descriptor_set get_compute_descriptor_set() const;

		W_VK_EXP const w_descriptor_set_layout get_descriptor_set_layout() const;
		W_VK_EXP const w_descriptor_set_layout get_compute_descriptor_set_layout() const;

#pragma endregion

#pragma region Setters

		//set and update shader binding params
		W_VK_EXP W_RESULT set_shader_binding_params(_In_ std::vector<w_shader_binding_param> pShaderBindingParams);

#pragma endregion

		W_VK_EXP static W_RESULT load_shader(
			_In_ const std::shared_ptr<w_graphics_device>& pGDevice,
			_In_z_ const std::string& pName,
			_In_z_ const std::wstring& pVertexShaderPath,
			_In_z_ const std::wstring& pTessellationControlShaderPath,
			_In_z_ const std::wstring& pTessellationEvaluationShaderPath,
			_In_z_ const std::wstring& pGeometryShaderPath,
			_In_z_ const std::wstring& pFragmentShaderPath,
			_In_z_ const std::wstring& pComputeShaderPath,
			_In_ const std::vector<w_shader_binding_param> pShaderBindingParams,
			_In_ const bool pStoreToSharedShaders,
			_Inout_ w_shader** pShader,
			_In_z_ const std::string& pMainFunctionName = "main");

		W_VK_EXP static w_shader* get_shader_from_shared(_In_z_ const std::string& pName);
		W_VK_EXP static ULONG release_shared_shaders();

#ifdef __PYTHON__

		W_RESULT py_load(
			_In_ boost::shared_ptr<w_graphics_device>& pGDevice,
			_In_z_ const std::wstring& pShaderBinaryPath,
			_In_ const w_shader_stage_flag_bits& pShaderStage,
			_In_z_ const std::string& pMainFunctionName = "main")
		{
			if (!pGDevice.get()) return W_FAILED;
			//boost::shared to std::shared
			auto _gDevice = boost_shared_ptr_to_std_shared_ptr<w_graphics_device>(pGDevice);

			auto _hr = load(
				_gDevice,
				pShaderBinaryPath,
				pShaderStage,
				pMainFunctionName.c_str());

			//reset local shared_ptr
			_gDevice.reset();

			return _hr;
		}

		boost::python::list py_get_shader_binding_params()
		{
			boost::python::list _list;
			auto _binding_params = get_shader_binding_params();
			for (size_t i = 0; i < _binding_params.size(); ++i)
			{
				_list.append(_binding_params[i]);
			}
			_binding_params.clear();
			return _list;
		}

		boost::python::list py_get_shader_stages()
		{
			boost::python::list _list;
			auto _stages = get_shader_stages();
			if (_stages)
			{
				for (size_t i = 0; i < _stages->size(); ++i)
				{
					_list.append(_stages[i]);
				}
			}
			return _list;
		}

		W_RESULT py_set_shader_binding_params(_In_ boost::python::list pShaderBindingParams)
		{
			std::vector<w_shader_binding_param> _shader_binding_params;
			//get command buffers
			for (size_t i = 0; i < len(pShaderBindingParams); ++i)
			{
				boost::python::extract<w_shader_binding_param> _param(pShaderBindingParams[i]);
				if (_param.check())
				{
					_shader_binding_params.push_back(_param());
				}
			}

			if (_shader_binding_params.size())
			{
				return set_shader_binding_params(_shader_binding_params);
			}
			return W_FAILED;
		}

		static W_RESULT py_load_shader(
			_In_ boost::shared_ptr<w_graphics_device>& pGDevice,
			_In_z_ const std::string& pName,
			_In_z_ const std::wstring& pVertexShaderPath,
			_In_z_ const std::wstring& pTessellationControlShaderPath,
			_In_z_ const std::wstring& pTessellationEvaluationShaderPath,
			_In_z_ const std::wstring& pGeometryShaderPath,
			_In_z_ const std::wstring& pFragmentShaderPath,
			_In_z_ const std::wstring& pComputeShaderPath,
			_In_ boost::python::list pShaderBindingParams,
			_In_z_ const std::string& pMainFunctionName = "main")
		{
			if (!pGDevice.get()) return W_FAILED;
			//boost::shared to std::shared
			auto _gDevice = boost_shared_ptr_to_std_shared_ptr<w_graphics_device>(pGDevice);

			std::vector<w_shader_binding_param> _shader_binding_params;
			//get command buffers
			for (size_t i = 0; i < len(pShaderBindingParams); ++i)
			{
				boost::python::extract<w_shader_binding_param> _param(pShaderBindingParams[i]);
				if (_param.check())
				{
					_shader_binding_params.push_back(_param());
				}
			}

			w_shader* _shader = nullptr;
			auto _hr = load_shader(
				_gDevice,
				pName,
				pVertexShaderPath,
				pTessellationControlShaderPath,
				pTessellationEvaluationShaderPath,
				pGeometryShaderPath,
				pFragmentShaderPath,
				pComputeShaderPath,
				_shader_binding_params,
				true,
				&_shader,
				pMainFunctionName.c_str());

			_shader_binding_params.clear();

			//reset local shared_ptr
			_gDevice.reset();

			return _hr;
		}
#endif

	private:
		bool													_is_released;
		w_shader_pimp* _pimp;
		static std::map<std::string, w_shader*>                 _shared;
	};
}

#include "python_exporter/py_shader.h"


text:
package at.ac.tuwien.infosys.jcloudscale.datastore.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation to inject an external datastore lib
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DatastoreLib {

    /** the name of the datastore */
    String datastore();

    /** the name of the datastore lib to inject */
    String name();
}


text:
from __future__ import unicode_literals, print_function

import logging
import os
import re
import shutil

# For html escaping/unescaping
import HTMLParser
try:
    from html import escape as html_escape  # py3
except ImportError:
    from cgi import escape as html_escape # py2

import six

from blinker import signal

from pelican import signals, generators
from pelican.contents import Static
from pelican.utils import mkdir_p, get_relative_path

logger = logging.getLogger(__name__)
html_parser = HTMLParser.HTMLParser()

autostatic_generator = None
detected_autostatic_paths = {}

autostatic_path_found = signal("autostatic_path_found")

CUSTOM_STATIC_REF_PATTERN_KEY = "AUTOSTATIC_REFERENCE_PATTERN"
USE_PELICAN_LIKE_REF_KEY = "AUTOSTATIC_USE_PELICANLIKE_REF"

# Works everywhere
DEFAULT_STATIC_REF_PATTERN = r"""{static(?:\s+|\|)((?:"|'|"|'|"|')?)(?P<path>.+?)\1(?:(?:\s+|\|)(?P<extra>.*))?\s*}"""

# Works just in url-value attributes
PELICAN_LIKE_REF_TAG = r"""{static(?:(?:\s+|\|)(?P<extra>.*))?}"""
PELICAN_LIKE_HREF_PATTERN = r"""
    (?P<markup><\s*[^\>]*  # match tag with all url-value attributes
        (?:href|src|poster|data|cite|formaction|action)\s*=)

    (?P<quote>["\'])      # require value to be quoted
    (?P<ref>{0}(?P<path>.*?))  # the url value
    \2""".format(PELICAN_LIKE_REF_TAG)

def html_unescape(text):
    if text is None:
        return text

    return html_parser.unescape(text)

def parse_static_references(instance, text):
    def _get_static_path(match_obj):
        path = match_obj.group("path")
        extra = html_unescape(match_obj.group("extra"))
        extra_dict = {}
        instance_destination_dir = os.path.dirname(instance.save_as)
        relative_path = False
        using_relative_urls = instance._context.get("RELATIVE_URLS")

        if extra:
            for match in re.finditer(r'(\w+)="?((?:(?<!")[^\s|]+|(?<=")(?:\\.|[^"\\])*(?=")))"?', extra):
                extra_dict[match.group(1)] = match.group(2)

        if path.startswith('/'):
            source_path = path[1:]
            destination_path = source_path
            relative_path = False
        else:
            source_path = instance.get_relative_source_path(
                os.path.join(instance.relative_dir, path))
            destination_path = os.path.join(instance_destination_dir, path)
            relative_path = True

        if "output" in extra_dict:
            output_override = extra_dict["output"]

            if output_override.startswith('/'):
                destination_path = output_override[1:]
                relative_path = False
            else:
                destination_path = os.path.join(instance_destination_dir, output_override)
                relative_path = True

        if using_relative_urls:
            siteurl = get_relative_path(instance.save_as)
        else:
            siteurl = instance._context.get("localsiteurl", "")

        if relative_path and using_relative_urls:
            url = os.path.relpath(destination_path, instance_destination_dir)
        else:
            url = siteurl + "/" + destination_path

        if "url" in extra_dict:
            url_override = extra_dict["url"]

            if url_override.startswith('/'):
                url = siteurl + url_override
            else:
                url = url_override

                if not using_relative_urls:
                    url = siteurl + "/" + os.path.dirname(instance.save_as) + "/" + url

        url = url.replace('\\', '/')  # for Windows paths.

        static_path_obj = StaticPath(source_path, destination_path, url, extra_dict)
        autostatic_path_found.send(autostatic_path=static_path_obj)

        logger.debug("Detected autostatic path: {} -> {} ({})".format(
            static_path_obj.source,
            static_path_obj.destination,
            static_path_obj.url))

        detected_autostatic_paths[static_path_obj.destination] = static_path_obj.source

        return html_escape(static_path_obj.url)

    def _parse_pelican_like_reference(m):
        return ''.join((m.group('markup'), m.group('quote'),
                        _get_static_path(m),
                        m.group('quote')))

    if text is None:
        return text

    if isinstance(text, six.string_types):
        settings = instance.settings

        static_ref_re_pattern = DEFAULT_STATIC_REF_PATTERN

        if settings and CUSTOM_STATIC_REF_PATTERN_KEY in settings:
            static_ref_re_pattern = settings[CUSTOM_STATIC_REF_PATTERN_KEY]

        text = re.sub(static_ref_re_pattern, _get_static_path, text)

        if settings and settings.get(USE_PELICAN_LIKE_REF_KEY, False):
            text = re.sub(PELICAN_LIKE_HREF_PATTERN,
                          _parse_pelican_like_reference, text, flags=re.X)

        return text
    elif isinstance(text, list):
        return [parse_static_references(instance, item) for item in text]
    else:
        return text

class StaticPath(object):
    def __init__(self, source, destination, url, extra):
        self._source = source
        self._original_destination = destination
        self._destination = destination
        self._original_url = url
        self._url = url
        self._extra = extra

    @property
    def source(self):
        return self._source

    @property
    def original_destination(self):
        return self._original_destination

    @property
    def destination(self):
        return self._destination

    @destination.setter
    def destination(self, value):
        self._destination = value

    @property
    def original_url(self):
        return self._original_url

    @property
    def url(self):
        return self._url

    @url.setter
    def url(self, value):
        self._url = value

    @property
    def extra(self):
        return self._extra

class AutoStaticGenerator(generators.Generator):
    """copy static paths (what you want to copy, like images, medias etc.
    to output"""

    autostatic_generator_init = signal("autostatic_generator_init")
    autostatic_generator_preread = signal("autostatic_generator_preread")
    autostatic_generator_context = signal("autostatic_generator_context")
    autostatic_generator_finalized = signal("autostatic_generator_finalized")

    def __init__(self, *args, **kwargs):
        super(AutoStaticGenerator, self).__init__(*args, **kwargs)
        self.autostatic_files = []
        self.autostatic_generator_init.send(self)

    def add_static_path(self, source_path, save_as):
        try:
            static = self.readers.read_file(
                    base_path=self.path, path=source_path, content_class=Static,
                    fmt='static', context=self.context,
                    preread_signal=self.autostatic_generator_preread,
                    preread_sender=self,
                    context_signal=self.autostatic_generator_context,
                    context_sender=self)
            static.override_save_as = save_as
            self.autostatic_files.append(static)
            self.add_source_path(static)
        except Exception as e:
            logger.error("Could not process %s\n%s", source_path, e,
                    exc_info=self.settings.get("DEBUG", False))

    def finalize_context(self):
        for save_as, source_path in detected_autostatic_paths.items():
            self.add_static_path(source_path, save_as)

        self._update_context(('autostatic_files',))
        self.autostatic_generator_finalized.send(self)

    def generate_output(self, writer):
        # copy all Static files
        for sc in self.autostatic_files:
            source_path = os.path.join(self.path, sc.source_path)
            save_as = os.path.join(self.output_path, sc.save_as)
            mkdir_p(os.path.dirname(save_as))
            shutil.copy2(source_path, save_as)
            logger.info('Copying %s to %s', sc.source_path, sc.save_as)

def find_static_references(instance):
    if hasattr(instance, "_content"):
        instance._content = parse_static_references(instance, instance._content)
    if hasattr(instance, "_summary"):
        instance._summary = parse_static_references(instance, instance._summary)

    for key in instance.metadata.keys():
        instance.metadata[key] = parse_static_references(instance, instance.metadata[key])
        try:
            setattr(instance, key.lower(), parse_static_references(instance, getattr(instance, key.lower())))
        except AttributeError as e:
            pass

def get_generators(_):
    return AutoStaticGenerator

def autostatic_generator_initialized(generator):
    global autostatic_generator
    autostatic_generator = generator

def generators_finished(_):
    global autostatic_generator
    autostatic_generator.finalize_context()

def register():
    signals.content_object_init.connect(find_static_references)
    signals.get_generators.connect(get_generators)
    AutoStaticGenerator.autostatic_generator_init.connect(autostatic_generator_initialized)
    signals.get_writer.connect(generators_finished)


text:
<?php

namespace Iggy\Handler;

use Iggy\HandlerInterface;
use Iggy\Twig\TwigFactory;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use React\Http\Response;
use Webmozart\PathUtil\Path;

/**
 * Class TwigHandler
 * @package Iggy\Handler
 */
class TwigHandler implements HandlerInterface
{
    /**
     * @var string
     */
    private $basePath;

    /**
     * @var TwigFactory
     */
    private $twigFactory;

    /**
     * TwigHandler constructor.
     * @param TwigFactory $twigFactory
     * @param string $basePath
     * @internal param \Twig_Environment $twig
     */
    public function __construct(TwigFactory $twigFactory, $basePath)
    {
        $this->basePath    = $basePath;
        $this->twigFactory = $twigFactory;
    }

    /**
     * @param \SplFileInfo $file
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     * @throws \Twig_Error_Loader
     * @throws \Twig_Error_Runtime
     * @throws \Twig_Error_Syntax
     */
    public function handle(\SplFileInfo $file, ServerRequestInterface $request): ResponseInterface
    {
        $twig = $this->twigFactory->getTwigEnvironment($request);
        $relativePath = trim(Path::makeRelative($file->getRealPath(), $this->basePath), '/');
        return new Response(200, ['Content-Type' => 'text/html'], $twig->render($relativePath, [
            'query' => $request->getQueryParams()
        ]));
    }
}


text:
<?php
namespace Orm;

/**
 * @Entity
 * @Table(name="_article")
 **/
class Article
{
	/**
	 * @Id
	 * @Column(type="integer")
	 * @GeneratedValue
	 **/
	protected $id;

	/**
	 * @ManyToOne(targetEntity="WorkFiles")
	 */
	protected $workfile;

	/**
	 * @ManyToOne(targetEntity="Users")
	 */
	protected $owner;

	/**
	 * @Column(type="string")
	 **/
	protected $text;

	/**
	 * @Column(type="string")
	 **/
	protected $title;

	public function getId() {
		return $this->id;
	}
	public function getWorkfile() {
		return $this->workfile;
	}
	public function getOwner() {
		return $this->owner;
	}
	public function getText() {
		return $this->text;
	}
	public function getTitle() {
		return $this->title;
	}
	public function setId($x) {
		$this->id = $x;
	}
	public function setOwner($x) {
		$this->owner = $x;
	}
	public function setWorkfile($x) {
		$this->workfile = $x;
	}
	public function setText($x) {
		$this->text = $x;
	}
	public function setTitle($x) {
		$this->title = $x;
	}
}
?>


text:
Leaderboards-XL
===============

The original Meteor leaderboards example with a button to add new players as well as sort functionality. Made with Coffeescript and Bootstrap.


text:
var rewire = require('rewire');

describe('watch()', function () {
    var timeout;
    var watch;
    var watcher;
    var unmock;

    beforeEach(function () {
        timeout = mockTimeout();
        var watchModule = rewire('./watch');
        unmock = watchModule.__set__(timeout.mocks);
        watch = watchModule.__get__('watch');
    });

    afterEach(function () {
        // Shouldn't really be necessary, but...
        if (watcher) {
            watcher.close();
            watcher = null;
        }
        unmock();
        expect(timeout.pending).toBe(0);
        timeout = null;
    });

    it('should fire callback once for events which occur within `delay` window', function () {
        var cb = jasmine.createSpy('callback');
        watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);

        watcher._emit('add', './$$fake_path/test.txt');
        timeout.flush(9);
        expect(cb).not.toHaveBeenCalled();

        watcher._emit('change', './$$fake_path/test.txt');
        watcher._emit('add', './$$fake_path/test2.txt');
        watcher._emit('change', './$$fake_path/test2.txt');
        watcher._emit('add', './$$fake_path/test3.txt');
        watcher._emit('change', './$$fake_path/test3.txt');
        expect(cb).not.toHaveBeenCalled();

        timeout.flush(1);
        expect(cb.calls.count()).toBe(1);
    });

    it('should trigger callback if events are collected during task running', function () {
        var calls = 0;
        function cb(done) {
            if (++calls !== 1)
                return done();

            watcher._emit('change', './$$fake_path/test1.txt');
            watcher._emit('change', './$$fake_path/test2.txt');

            // Before the done callback, there are no pending timer events
            expect(timeout.pending).toBe(0);
            done();

            // Afterwards, there is one
            expect(timeout.pending).toBe(1);
        }

        var watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);

        watcher._emit('change', './$$fake_path/test1.txt');
        expect(timeout.pending).toBe(1);
        expect(calls).toBe(0);

        timeout.flush(10);
        expect(calls).toBe(2);
    });

    it('should continue to trigger callbacks if task throws', function () {
        var calls = 0;
        spyOn(console, 'log');
        function cb(done) {
            calls += 1;
            if (calls === 1)
                throw new Error('oops!');
            done();
        }

        var watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);

        watcher._emit('change', './$$fake_path/test1.txt');
        timeout.flush();
        expect(calls).toBe(1);
        expect(console.log).toHaveBeenCalledWith('Watch task error:', 'Error: oops!');

        watcher._emit('change', './$$fake_path/test2.txt');
        timeout.flush();
        expect(calls).toBe(2);
    });

    it('should cancel pending callback if FSWatcher is closed', function () {
        var cb = jasmine.createSpy('callback');
        var watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);

        watcher._emit('change', './$$fake_path/test1.txt');
        expect(timeout.pending).toBe(1);
        expect(cb).not.toHaveBeenCalled();

        watcher.close();
        expect(timeout.pending).toBe(0);
    });

    it('should cancel followup pending callback if FSWatcher is closed during task', function () {
        var calls = 0;
        function cb(done) {
            if (++calls !== 1)
                return done();

            watcher._emit('change', './$$fake_path/test2.txt');
            done();
            expect(timeout.pending).toBe(1);
            watcher.close();
            expect(timeout.pending).toBe(0);
        }

        var watcher = watch('./$$fake_path/**/*', {delay: 10, log: false}, cb);
        watcher._emit('change', './$$fake_path/test1.txt');

        timeout.flush(10);

        expect(calls).toBe(1);
    });
});

// setTimeout/clearTimeout mocking, mostly stolen from angular-mocks.js
function mockTimeout() {
    var events = [];
    var id = 0;
    var now = 0;

    return {
        mocks: {
            setTimeout: mockSetTimeout,
            clearTimeout: mockClearTimeout
        },
        flush: flush,
        get pending() {
            return events.length;
        }
    };

    function mockSetTimeout(fn, delay) {
        delay = delay || 0;
        events.push({
            time: now + delay,
            fn: fn,
            id: id
        });
        events.sort(function (a, b) {
            return a.time - b.time;
        });
        return id++;
    }

    function mockClearTimeout(id) {
        for (var i = 0; i < events.length; ++i) {
            if (events[i].id === id) {
                events.splice(i, 1);
                break;
            }
        }
    }

    function flush(delay) {
        if (delay !== undefined)
            now += delay;
        else if (events.length)
            now = events[events.length - 1].time;
        else
            throw new Error('No timer events registered');

        while (events.length && events[0].time <= now) {
            events.shift().fn();
        }
    }
}


text:
<?php
//============================================================+
// File name   : example_010.php
// Begin       : 2008-03-04
// Last Update : 2011-04-26
//
// Description : Example 010 for TCPDF class
//               Text on multiple columns
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               Manor Coach House, Church Hill
//               Aldershot, Hants, GU12 4RQ
//               UK
//               www.tecnick.com
//               info@tecnick.com
//============================================================+

/**
 * Creates an example PDF TEST document using TCPDF
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Example: Text on multiple columns
 * @author Nicola Asuni
 * @since 2008-03-04
 */

require_once('../config/lang/eng.php');
require_once('../tcpdf.php');

/**
 * Extend TCPDF to work with multiple columns
 */
class MC_TCPDF extends TCPDF {

	/**
	 * Print chapter
	 * @param $num (int) chapter number
	 * @param $title (string) chapter title
	 * @param $file (string) name of the file containing the chapter body
	 * @param $mode (boolean) if true the chapter body is in HTML, otherwise in simple text.
	 * @public
	 */
	public function PrintChapter($num, $title, $file, $mode=false) {
		// add a new page
		$this->AddPage();
		// disable existing columns
		$this->resetColumns();
		// print chapter title
		$this->ChapterTitle($num, $title);
		// set columns
		$this->setEqualColumns(3, 57);
		// print chapter body
		$this->ChapterBody($file, $mode);
	}

	/**
	 * Set chapter title
	 * @param $num (int) chapter number
	 * @param $title (string) chapter title
	 * @public
	 */
	public function ChapterTitle($num, $title) {
		$this->SetFont('helvetica', '', 14);
		$this->SetFillColor(200, 220, 255);
		$this->Cell(180, 6, 'Chapter '.$num.' : '.$title, 0, 1, '', 1);
		$this->Ln(4);
	}

	/**
	 * Print chapter body
	 * @param $file (string) name of the file containing the chapter body
	 * @param $mode (boolean) if true the chapter body is in HTML, otherwise in simple text.
	 * @public
	 */
	public function ChapterBody($file, $mode=false) {
		$this->selectColumn();
		// get esternal file content
		$content = file_get_contents($file, false);
		// set font
		$this->SetFont('times', '', 9);
		$this->SetTextColor(50, 50, 50);
		// print content
		if ($mode) {
			// ------ HTML MODE ------
			$this->writeHTML($content, true, false, true, false, 'J');
		} else {
			// ------ TEXT MODE ------
			$this->Write(0, $content, '', 0, 'J', true, 0, false, true, 0);
		}
		$this->Ln();
	}
} // end of extended class

// ---------------------------------------------------------
// EXAMPLE
// ---------------------------------------------------------
// create new PDF document
$pdf = new MC_TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 010');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 010', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

//set some language-dependent strings
$pdf->setLanguageArray($l);

// ---------------------------------------------------------

// print TEXT
$pdf->PrintChapter(1, 'LOREM IPSUM [TEXT]', '../cache/chapter_demo_1.txt', false);

// print HTML
$pdf->PrintChapter(2, 'LOREM IPSUM [HTML]', '../cache/chapter_demo_2.txt', true);

// ---------------------------------------------------------

//Close and output PDF document
$pdf->Output('example_010.pdf', 'I');

//============================================================+
// END OF FILE
//============================================================+


text:
import { css } from '@emotion/css';

import { GrafanaTheme } from '@grafana/data';
import { stylesFactory } from '@grafana/ui';

export const cardStyle = stylesFactory((theme: GrafanaTheme, complete: boolean) => {
  const completeGradient = 'linear-gradient(to right, #5182CC 0%, #245BAF 100%)';
  const darkThemeGradients = complete ? completeGradient : 'linear-gradient(to right, #f05a28 0%, #fbca0a 100%)';
  const lightThemeGradients = complete ? completeGradient : 'linear-gradient(to right, #FBCA0A 0%, #F05A28 100%)';

  const borderGradient = theme.isDark ? darkThemeGradients : lightThemeGradients;

  return `
      background-color: ${theme.colors.bg2};
      margin-right: ${theme.spacing.xl};
      border: 1px solid ${theme.colors.border1};
      border-bottom-left-radius: ${theme.border.radius.md};
      border-bottom-right-radius: ${theme.border.radius.md};
      position: relative;
      max-height: 230px;

      @media only screen and (max-width: ${theme.breakpoints.xxl}) {
        margin-right: ${theme.spacing.md};
      }
      &::before {
        display: block;
        content: ' ';
        position: absolute;
        left: 0;
        right: 0;
        height: 2px;
        top: 0;
        background-image: ${borderGradient};
      }
`;
});

export const iconStyle = stylesFactory(
  (theme: GrafanaTheme, complete: boolean) => css`
    color: ${complete ? theme.palette.blue95 : theme.colors.textWeak};

    @media only screen and (max-width: ${theme.breakpoints.sm}) {
      display: none;
    }
  `
);

export const cardContent = css`
  padding: 16px;
`;


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>BESA.Extern.Directory</title>
<meta name="date" content="2012-06-19">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

BESA.Extern.Directory

Classes

AgExternHandlerBESA

Exceptions

ExternDirectoryExceptionBESA


text:
import random from '../core/random';

const LIPSUM_WORDS = `Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est
laborum`.split(/\W/);

/**
 * Generates randomized array of single lorem ipsum words.
 *
 * @param length
 * @returns {Array.<string>}
 */
function wordsGenerator(length) {
  const words = random.shuffle(LIPSUM_WORDS);

  return words.slice(0, length);
}

export default wordsGenerator;


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../libc/fn.nl_langinfo_l.html">

Redirecting to ../../../../libc/fn.nl_langinfo_l.html...


text:
<?php
/**
 * 单进程处理
 *
 * @author ciogao@gmail.com
 * Date: 14-3-10 上午9:48
 */
namespace core\analyzer;

use constant\config as config;

class single extends analyzerBase
{
    static public function run()
    {
        $analyz = config::getAnalyz();

        if (!is_array($analyz) || count($analyz) < 1) return '';

        foreach ($analyz as $rName => $config) {
            self::analyzerRun($rName, $config);
        }

        \SeasLog::info('Single Process Done.', array(), 'SeasLogAnalyzer');
    }
}


text:
package stroom.widget.tab.client.presenter;

import stroom.widget.menu.client.presenter.ShowMenuEvent.HasShowMenuHandlers;
import stroom.widget.tab.client.event.HasRequestCloseTabHandlers;

import com.google.gwt.event.logical.shared.HasSelectionHandlers;
import com.google.gwt.user.client.ui.Focus;

import java.util.List;

public interface TabBar extends
        HasSelectionHandlers<TabData>,
        HasRequestCloseTabHandlers,
        HasShowMenuHandlers,
        Focus {

    void addTab(TabData tab);

    void removeTab(TabData tab);

    void clear();

    void selectTab(TabData tab);

    TabData getSelectedTab();

    List<TabData> getTabs();

    void setTabHidden(TabData tab, boolean hidden);

    boolean isTabHidden(TabData tab);

    void refresh();
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace SATInterface
{
    internal class NotExpr : BoolExpr
    {
        public BoolVar inner;

        internal NotExpr(BoolVar _inner)
        {
            inner = _inner;
        }

        internal static BoolExpr Create(BoolExpr _inner)
        {
            if (_inner is NotExpr ne)
                return ne.inner;
            else if (ReferenceEquals(_inner, Model.True))
                return Model.False;
            else if (ReferenceEquals(_inner, Model.False))
                return Model.True;
            else if (_inner is BoolVar bv)
                return bv.Negated;
            else if (_inner is AndExpr ae)
            {
                var be = new BoolExpr[ae.Elements.Length];
                for (var i = 0; i < be.Length; i++)
                    be[i] = !ae.Elements[i];
                return OrExpr.Create(be);
            }
            else if (_inner is OrExpr oe)
            {
                var be = new BoolExpr[oe.Elements.Length];
                for (var i = 0; i < be.Length; i++)
                    be[i] = !oe.Elements[i];
                return AndExpr.Create(be);
            }
            else
                throw new NotImplementedException();
        }

        public override BoolExpr Flatten() => this;

        internal override IEnumerable<BoolVar> EnumVars()
        {
            yield return inner;
        }

        internal override Model? GetModel() => inner.GetModel();

        public override string ToString() => "!" + inner;

        public override bool X => !inner.X;

        public override int VarCount => 1;

        public override bool Equals(object? _obj) => (_obj is NotExpr ne) && inner.Equals(ne.inner);

        public override int GetHashCode() => ~inner.GetHashCode();
    }
}