text:
"""Report jobs resolved, change count, customer issues fixed."""

import argparse
from collections import defaultdict
import re
import sys

import P4

# Permit loose pattern matching -- case insensitive, optional space before
# ':' '^Jobs:' '^jobs:'  '^Jobs :' '^jobs :' '^JOBS :'
JOB_REX = re.compile(r'^[jJ][oO][bB][sS] ?:')

class P4Changelist:

    """A changelist, as reported by p4 changes."""

    def __init__(self):
        """Construct instance of P4Changelist."""
        self.change = None
        self.description = None
        self.user = None
        self.time = None

    @staticmethod
    def create_using_changes(vardict):
        """Create a P4Changelist from the output of p4 changes."""
        cl = P4Changelist()
        cl.change = int(vardict["change"])
        cl.description = vardict["desc"]
        cl.user = vardict["user"]
        cl.time = int(vardict["time"])
        return cl

class ChangesHandler(P4.OutputHandler):

    """OutputHandler for p4 changes, passes changelists to callback function."""

    def __init__(self, callback):
        """Construct instance of ChangesHandler."""
        P4.OutputHandler.__init__(self)
        self.callback = callback

    def outputStat(self, h):
        """Grab clientFile from fstat output."""
        change = P4Changelist.create_using_changes(h)
        self.callback(change)
        return P4.OutputHandler.HANDLED

def extract_jobs(desc):
    """Scan the commit description looking for fixed jobs.

    :return: list, or None if no jobs found

    """
    if not desc:
        return None
    lines = desc.splitlines()
    for i in range(0, len(lines)):
        line = lines[i].strip()
        m = JOB_REX.match(line)
        if m:
            jobs = []
            line = line[m.span()[1]:]
            if line:
                jobs.append(line.strip())
            for i in range(i + 1, len(lines)):
                line = lines[i].strip()
                if not line or ' ' in line or ':' in line:
                    # reached the end of the job identifiers
                    break
                # whatever is left of the line is a job identifier
                jobs.append(line)
            return jobs
    return None

def first_dict(result_list):
    """Return the first dict from a p4 result list."""
    for e in result_list:
        if isinstance(e, dict):
            return e
    return None

def process_changes(p4, username, after_change):
    """Collect metrics from the changes."""
    change_count = 0
    all_jobs = list()

    def callback(changelist):
        """Process the given list."""
        nonlocal change_count
        change_count += 1
        jobs = extract_jobs(changelist.description)
        if jobs:
            all_jobs.extend(jobs)

    cmd = ["changes", "-l", "-u", username]
    if after_change:
        cmd.append("-e")
        cmd.append(after_change)
    handler = ChangesHandler(callback)
    with p4.using_handler(handler):
        p4.run(cmd)

    job_counts = defaultdict(int)
    customer_issues = 0
    for job in all_jobs:
        r = p4.run(['job', '-o', job])
        if isinstance(r, list):
            job_spec = first_dict(r)
            if 'CallNumbers' in job_spec or 'Customers' in job_spec:
                customer_issues += 1
            job_type = job_spec['Type']
            job_counts[job_type] += 1

    print("Changes: {}".format(change_count))
    for job_type, count in job_counts.items():
        print("{}(s): {}".format(job_type, count))
    print("Customer issues: {}".format(customer_issues))

def main():
    """Run P4 commands to collect metrics."""
    desc = """Examine p4 changes and jobs to report metrics."""
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('--after', type=int,
                        help="select changes after (and including) the given change")
    args = parser.parse_args()
    p4 = P4.P4()
    p4.connect()
    user = p4.fetch_user()
    if user:
        process_changes(p4, user["User"], args.after)
    else:
        sys.stderr.write("Cannot retrieve current Perforce user\n")

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
import os
from ..utils import BasicSegment

class Segment(BasicSegment):
    def add_to_powerline(self):
        self.powerline.append(
            " %s " % os.getenv(self.segment_def["var"]),
            self.segment_def.get("fg_color", self.powerline.theme.PATH_FG),
            self.segment_def.get("bg_color", self.powerline.theme.PATH_BG))


text:
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由Codesmith工具生成。
// 此文件的更改可能会导致不正确的行为,如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Common;
using ZyGames.Framework.Collection;
using ZyGames.Framework.Model;
using ProtoBuf;
using System.Runtime.Serialization;
using ZyGames.Tianjiexing.Model.Config;

namespace ZyGames.Tianjiexing.Model
{
    /// <summary>
    /// 玩家集邮表
    /// </summary>
    /// <![CDATA[
    /// @periodTime:设置生存周期(秒)
    /// @personalName: 映射UserId对应的字段名,默认为"UserId"
    /// ]]>
    /// </remarks>
    [Serializable, ProtoContract]
    [EntityTable(DbConfig.Data, "UserAlbum", DbConfig.PeriodTime, DbConfig.PersonalName)]
    public class UserAlbum : BaseEntity
    {

        /// <summary>
        /// </summary>
        public UserAlbum()
            : base(AccessLevel.ReadWrite)
        {
            AlbumList = new CacheList<Album>();
        }
        /// <summary>
        /// </summary>
        public UserAlbum(string userID)
            : this()
        {
            _userID = userID;
        }

        #region 自动生成属性
        private string _userID;
        /// <summary>
        /// 玩家Id
        /// </summary>
        [ProtoMember(1)]
        [EntityField("UserID", IsKey = true)]
        public string UserID
        {
            get
            {
                return _userID;
            }
            set
            {
                SetChange("UserID", value);
            }

        }
        private CacheList<Album> _albumList;
        /// <summary>
        /// 集邮列表[CacheList<Album>]
        /// </summary>
        [ProtoMember(2)]
        [EntityField("AlbumList", IsJsonSerialize = true, DbType = ColumnDbType.Text)]
        public CacheList<Album> AlbumList
        {
            get
            {
                return _albumList;
            }
            set
            {
                SetChange("AlbumList", value);
            }
        }

        protected override object this[string index]
        {
            get
            {
                #region
                switch (index)
                {
                    case "UserID": return _userID;
                    case "AlbumList": return _albumList;
                    default: throw new ArgumentException(string.Format("UserAlbum index[{0}] isn't exist.", index));
                }
                #endregion
            }
            set
            {
                #region
                switch (index)
                {
                    case "UserID":
                        _userID = value.ToNotNullString();
                        break;
                    case "AlbumList":
                        _albumList = ConvertCustomField<CacheList<Album>>(value, index);
                        break;
                    default: throw new ArgumentException(string.Format("UserAlbum index[{0}] isn't exist.", index));
                }
                #endregion
            }
        }

        #endregion

        protected override int GetIdentityId()
        {
            //设置玩家的UserID
            //若要做为全局使用设置类绑定的自定义属性[EntityTable(CacheType.Entity, DbConfig.Config, @TableName, @PeriodTime)]
            return UserID.ToInt();
        }
    }
}


text:
using std::max;

namespace caffe {

const float kLOG_THRESHOLD = 1e-20;

template <typename Dtype>
void MultinomialLogisticLossLayer<Dtype>::SetUp(
    const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
  CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input.";
  CHECK_EQ(top->size(), 0) << "Loss Layer takes no output.";
  CHECK_EQ(bottom[0]->num(), bottom[1]->num())
      << "The data and label should have the same number.";
  CHECK_EQ(bottom[1]->channels(), 1);
  CHECK_EQ(bottom[1]->height(), 1);
  CHECK_EQ(bottom[1]->width(), 1);
}

template <typename Dtype>
Dtype MultinomialLogisticLossLayer<Dtype>::Forward_cpu(
    const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
  const Dtype* bottom_data = bottom[0]->cpu_data();
  const Dtype* bottom_label = bottom[1]->cpu_data();
  int num = bottom[0]->num();
  int dim = bottom[0]->count() / bottom[0]->num();
  Dtype loss = 0;
  for (int i = 0; i < num; ++i) {
    int label = static_cast<int>(bottom_label[i]);
    Dtype prob = max(bottom_data[i * dim + label], Dtype(kLOG_THRESHOLD));
    loss -= log(prob);
  }
  return loss / num;
}

template <typename Dtype>
void MultinomialLogisticLossLayer<Dtype>::Backward_cpu(
    const vector<Blob<Dtype>*>& top, const bool propagate_down,
    vector<Blob<Dtype>*>* bottom) {
  const Dtype* bottom_data = (*bottom)[0]->cpu_data();
  const Dtype* bottom_label = (*bottom)[1]->cpu_data();
  Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
  int num = (*bottom)[0]->num();
  int dim = (*bottom)[0]->count() / (*bottom)[0]->num();
  memset(bottom_diff, 0, sizeof(Dtype) * (*bottom)[0]->count());
  for (int i = 0; i < num; ++i) {
    int label = static_cast<int>(bottom_label[i]);
    Dtype prob = max(bottom_data[i * dim + label], Dtype(kLOG_THRESHOLD));
    bottom_diff[i * dim + label] = -1. / prob / num;
  }
}

template <typename Dtype>
void InfogainLossLayer<Dtype>::SetUp(
    const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
  CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input.";
  CHECK_EQ(top->size(), 0) << "Loss Layer takes no output.";
  CHECK_EQ(bottom[0]->num(), bottom[1]->num())
      << "The data and label should have the same number.";
  CHECK_EQ(bottom[1]->channels(), 1);
  CHECK_EQ(bottom[1]->height(), 1);
  CHECK_EQ(bottom[1]->width(), 1);
  BlobProto blob_proto;
  ReadProtoFromBinaryFile(this->layer_param_.infogain_loss_param().source(),
                          &blob_proto);
  infogain_.FromProto(blob_proto);
  CHECK_EQ(infogain_.num(), 1);
  CHECK_EQ(infogain_.channels(), 1);
  CHECK_EQ(infogain_.height(), infogain_.width());
}

template <typename Dtype>
Dtype InfogainLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    vector<Blob<Dtype>*>* top) {
  const Dtype* bottom_data = bottom[0]->cpu_data();
  const Dtype* bottom_label = bottom[1]->cpu_data();
  const Dtype* infogain_mat = infogain_.cpu_data();
  int num = bottom[0]->num();
  int dim = bottom[0]->count() / bottom[0]->num();
  CHECK_EQ(infogain_.height(), dim);
  Dtype loss = 0;
  for (int i = 0; i < num; ++i) {
    int label = static_cast<int>(bottom_label[i]);
    for (int j = 0; j < dim; ++j) {
      Dtype prob = max(bottom_data[i * dim + j], Dtype(kLOG_THRESHOLD));
      loss -= infogain_mat[label * dim + j] * log(prob);
    }
  }
  return loss / num;
}

template <typename Dtype>
void InfogainLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const bool propagate_down,
    vector<Blob<Dtype>*>* bottom) {
  const Dtype* bottom_data = (*bottom)[0]->cpu_data();
  const Dtype* bottom_label = (*bottom)[1]->cpu_data();
  const Dtype* infogain_mat = infogain_.cpu_data();
  Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
  int num = (*bottom)[0]->num();
  int dim = (*bottom)[0]->count() / (*bottom)[0]->num();
  CHECK_EQ(infogain_.height(), dim);
  for (int i = 0; i < num; ++i) {
    int label = static_cast<int>(bottom_label[i]);
    for (int j = 0; j < dim; ++j) {
      Dtype prob = max(bottom_data[i * dim + j], Dtype(kLOG_THRESHOLD));
      bottom_diff[i * dim + j] = - infogain_mat[label * dim + j] / prob / num;
    }
  }
}

template <typename Dtype>
void EuclideanLossLayer<Dtype>::SetUp(
  const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
  CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input.";
  CHECK_EQ(top->size(), 0) << "Loss Layer takes no as output.";
  CHECK_EQ(bottom[0]->num(), bottom[1]->num())
      << "The data and label should have the same number.";
  CHECK_EQ(bottom[0]->channels(), bottom[1]->channels());
  CHECK_EQ(bottom[0]->height(), bottom[1]->height());
  CHECK_EQ(bottom[0]->width(), bottom[1]->width());
  difference_.Reshape(bottom[0]->num(), bottom[0]->channels(),
      bottom[0]->height(), bottom[0]->width());
}

template <typename Dtype>
Dtype EuclideanLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    vector<Blob<Dtype>*>* top) {
  int count = bottom[0]->count();
  int num = bottom[0]->num();
  caffe_sub(count, bottom[0]->cpu_data(), bottom[1]->cpu_data(),
      difference_.mutable_cpu_data());
  Dtype loss = caffe_cpu_dot(
      count, difference_.cpu_data(), difference_.cpu_data()) / num / Dtype(2);
  return loss;
}

template <typename Dtype>
void EuclideanLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
  int count = (*bottom)[0]->count();
  int num = (*bottom)[0]->num();
  // Compute the gradient
  caffe_cpu_axpby(count, Dtype(1) / num, difference_.cpu_data(), Dtype(0),
      (*bottom)[0]->mutable_cpu_diff());
}

template <typename Dtype>
void AccuracyLayer<Dtype>::SetUp(
  const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
  CHECK_EQ(bottom.size(), 2) << "Accuracy Layer takes two blobs as input.";
  CHECK_EQ(top->size(), 1) << "Accuracy Layer takes 1 output.";
  CHECK_EQ(bottom[0]->num(), bottom[1]->num())
      << "The data and label should have the same number.";
  CHECK_EQ(bottom[1]->channels(), 1);
  CHECK_EQ(bottom[1]->height(), 1);
  CHECK_EQ(bottom[1]->width(), 1);
  (*top)[0]->Reshape(1, 2, 1, 1);
}

template <typename Dtype>
Dtype AccuracyLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    vector<Blob<Dtype>*>* top) {
  Dtype accuracy = 0;
  Dtype logprob = 0;
  const Dtype* bottom_data = bottom[0]->cpu_data();
  const Dtype* bottom_label = bottom[1]->cpu_data();
  int num = bottom[0]->num();
  int dim = bottom[0]->count() / bottom[0]->num();
  for (int i = 0; i < num; ++i) {
    // Accuracy
    Dtype maxval = -FLT_MAX;
    int max_id = 0;
    for (int j = 0; j < dim; ++j) {
      if (bottom_data[i * dim + j] > maxval) {
        maxval = bottom_data[i * dim + j];
        max_id = j;
      }
    }
    if (max_id == static_cast<int>(bottom_label[i])) {
      ++accuracy;
    }
    Dtype prob = max(bottom_data[i * dim + static_cast<int>(bottom_label[i])],
                     Dtype(kLOG_THRESHOLD));
    logprob -= log(prob);
  }
  // LOG(INFO) << "Accuracy: " << accuracy;
  (*top)[0]->mutable_cpu_data()[0] = accuracy / num;
  (*top)[0]->mutable_cpu_data()[1] = logprob / num;
  // Accuracy layer should not be used as a loss function.
  return Dtype(0);
}

template <typename Dtype>
void OutAccuracyLayer<Dtype>::SetUp(
  const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
  CHECK_EQ(bottom.size(), 3) << "Accuracy Layer takes three blobs as input.";
  CHECK_EQ(top->size(), 1) << "Accuracy Layer takes 1 output.";
  CHECK_EQ(bottom[0]->num(), bottom[1]->num())
      << "The data and label should have the same number.";
  CHECK_EQ(bottom[0]->num(), bottom[2]->num())
      << "The data and image should have the same number.";
  CHECK_EQ(bottom[1]->channels(), 1);
  CHECK_EQ(bottom[1]->height(), 1);
  CHECK_EQ(bottom[1]->width(), 1);
  (*top)[0]->Reshape(1, 2, 1, 1);

  index = 1;
  outFile.open(".//ClassfierResult.txt");
}

template <typename Dtype>
Dtype OutAccuracyLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    vector<Blob<Dtype>*>* top) {

  Dtype accuracy = 0;
  Dtype logprob = 0;

  const Dtype* bottom_data = bottom[0]->cpu_data();
  const Dtype* bottom_label = bottom[1]->cpu_data();
  int num = bottom[0]->num();
  int dim = bottom[0]->count() / bottom[0]->num();

  int width = bottom[2]->width();
  int height = bottom[2]->height();
  int channels = bottom[2]->channels();
  int step = width*channels;
  int numStep = step*height;

  for (int i = 0; i < num; ++i) {
    // Accuracy
    Dtype maxval = -FLT_MAX;
    int max_id = 0;

	outFile << index << " ";

    for (int j = 0; j < dim; ++j) {

      if (bottom_data[i * dim + j] > maxval) {
        maxval = bottom_data[i * dim + j];
        max_id = j;
      }

	  outFile << bottom_data[i * dim + j] << " ";
    }
    if (max_id == static_cast<int>(bottom_label[i])) {
      ++accuracy;
    }
	else
	{
		IplImage *img = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, channels);
		const Dtype *dataPoint = bottom[2]->cpu_data();
		unsigned char *imgData = (unsigned char *)img->imageData;
		for(int h = 0 ; h < height ; h++)
			for(int w = 0 ; w < width ; w++)
				for(int c = 0 ; c < channels ; c++)
					imgData[c + w*channels + h*step] = dataPoint[w + h*width + c*width*height + i*numStep]*255;

		string path = ".//Errorimg";

		if( (_access( path.c_str(), 0 )) == -1 )
		{
			_mkdir(path.c_str());
		}

		char tmp[10];
		sprintf(tmp, "%d", static_cast<int>(bottom_label[i]));
		path = path + "//" +tmp;
		if( (_access( path.c_str(), 0 )) == -1 )
		{
			_mkdir(path.c_str());
		}

		sprintf(tmp, "%d", index);
		string fileName = path + "//" + tmp;
		sprintf(tmp, "%d", max_id);
		fileName = fileName + "_" + tmp + ".png";

		cvSaveImage(fileName.c_str(), img );
		cvReleaseImage(&img);
	}
    Dtype prob = max(bottom_data[i * dim + static_cast<int>(bottom_label[i])],
                     Dtype(kLOG_THRESHOLD));
    logprob -= log(prob);

	outFile << bottom_data[i * dim + max_id] << " " << bottom_data[i * dim + static_cast<int>(bottom_label[i])] << " ";
	outFile << max_id << " " << static_cast<int>(bottom_label[i]) << endl;

	index++;
  }
  // LOG(INFO) << "Accuracy: " << accuracy;
  (*top)[0]->mutable_cpu_data()[0] = accuracy / num;
  (*top)[0]->mutable_cpu_data()[1] = logprob / num;

  // Accuracy layer should not be used as a loss function.

  return Dtype(0);
}

template <typename Dtype>
void HingeLossLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom,
    vector<Blob<Dtype>*>* top) {
  CHECK_EQ(bottom.size(), 2) << "Hinge Loss Layer takes two blobs as input.";
  CHECK_EQ(top->size(), 0) << "Hinge Loss Layer takes no output.";
}

template <typename Dtype>
Dtype HingeLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    vector<Blob<Dtype>*>* top) {
  const Dtype* bottom_data = bottom[0]->cpu_data();
  Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
  const Dtype* label = bottom[1]->cpu_data();
  int num = bottom[0]->num();
  int count = bottom[0]->count();
  int dim = count / num;

  caffe_copy(count, bottom_data, bottom_diff);
  for (int i = 0; i < num; ++i) {
    bottom_diff[i * dim + static_cast<int>(label[i])] *= -1;
  }
  for (int i = 0; i < num; ++i) {
    for (int j = 0; j < dim; ++j) {
      bottom_diff[i * dim + j] = max(Dtype(0), 1 + bottom_diff[i * dim + j]);
    }
  }
  return caffe_cpu_asum(count, bottom_diff) / num;
}

template <typename Dtype>
void HingeLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
  Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
  const Dtype* label = (*bottom)[1]->cpu_data();
  int num = (*bottom)[0]->num();
  int count = (*bottom)[0]->count();
  int dim = count / num;

  caffe_cpu_sign(count, bottom_diff, bottom_diff);
  for (int i = 0; i < num; ++i) {
    bottom_diff[i * dim + static_cast<int>(label[i])] *= -1;
  }
  caffe_scal(count, Dtype(1. / num), bottom_diff);
}

INSTANTIATE_CLASS(MultinomialLogisticLossLayer);
INSTANTIATE_CLASS(InfogainLossLayer);
INSTANTIATE_CLASS(EuclideanLossLayer);
INSTANTIATE_CLASS(AccuracyLayer);
INSTANTIATE_CLASS(OutAccuracyLayer);
INSTANTIATE_CLASS(HingeLossLayer);

}  // namespace caffe


text:
(function() {
    function ModalCtrl($uibModalInstance) {
        this.name="";
        this.cancel = function(){
            $uibModalInstance.dismiss('cancel');
        };
        this.submit = function(){
            $uibModalInstance.close(this.name);
        };
    }

    angular
         .module('blocChat')
         .controller('ModalCtrl', ['$uibModalInstance', ModalCtrl]);
 })();


text:
namespace v8 {
namespace internal {

class JSArrayBuffer;
class ParseInfo;

// Interface to compile and instantiate for asmjs.
class AsmJs {
 public:
  static MaybeHandle<FixedArray> ConvertAsmToWasm(ParseInfo* info);
  static bool IsStdlibValid(Isolate* isolate, Handle<FixedArray> wasm_data,
                            Handle<JSReceiver> stdlib);
  static MaybeHandle<Object> InstantiateAsmWasm(Isolate* isolate,
                                                Handle<FixedArray> wasm_data,
                                                Handle<JSArrayBuffer> memory,
                                                Handle<JSReceiver> foreign);
};

}  // namespace internal
}  // namespace v8
#endif


text:
module SchoolsHelper

	def facilities_list_helper(school)
		facilities = school.api_facilities
		if facilities.present?
			array = []
			array << 'Art Room' 							if facilities[:hasartroom] == 'True'
			array << 'Athletic Field' 				if facilities[:hasathleticfield] == 'True'
			array << 'Auditorium' 						if facilities[:hasauditorium] == 'True'
			array << 'Cafeteria' 							if facilities[:hascafeteria] == 'True'
			array << 'Computer Lab' 					if facilities[:hascomputerlab] == 'True'
			array << 'Gymnasium' 							if facilities[:hasgymnasium] == 'True'
			array << 'Library' 								if facilities[:haslibrary] == 'True'
			array << 'Music Room' 						if facilities[:hasmusicroom] == 'True'
			array << 'Outdoor Classrooms' 		if facilities[:hasoutdoorclassroom] == 'True'
			array << 'Playground' 						if facilities[:hasplayground] == 'True'
			array << 'Pool' 									if facilities[:haspool] == 'True'
			array << 'Science Lab'	 					if facilities[:hassciencelab] == 'True'
			return array.compact
		else
			return []
		end
	end

	def sports_list_helper(school)
		sports = school.api_sports
		if sports.present?
			array = []
			array << 'Baseball' 						if sports[:Baseball] == true
			array << 'Basketball' 					if (sports[:boyBasketball] == true || sports[:girlBasketball] == true)
			array << 'Cheerleading' 				if sports[:Cheer] == true
			array << 'Cross Country' 				if (sports[:boyCrossCountry] == true || sports[:girlCrossCountry] == true)
			array << 'Double Dutch' 				if (sports[:boyDoubleDutch] == true || sports[:girlDoubleDutch] == true)
			array << 'Football' 						if sports[:Football] == true
			array << 'Golf'									if sports[:Golf] == true
			array << 'Hockey' 							if sports[:Hockey] == true
			array << 'Indoor Track' 				if (sports[:boyIndoorTrack] == true || sports[:girlIndoorTrack] == true)
			array << 'Soccer' 							if (sports[:boySoccer] == true || sports[:girlSoccer] == true)
			array << 'Softball' 						if sports[:Softball] == true
			array << 'Swimming' 						if (sports[:boySwim] == true || sports[:girlSwim] == true)
			array << 'Tennis' 							if (sports[:boyTennis] == true || sports[:girlTennis] == true)
			array << 'Track' 								if (sports[:boyOutdoorTrack] == true || sports[:girlOutdoorTrack] == true)
			array << 'Volleyball' 					if (sports[:boyVolleyball] == true || sports[:girlVolleyball] == true)
			array << 'Wrestling' 						if sports[:Wrestling] == true
			return array.compact
		else
			return []
		end
	end

	def student_support_list_helper(school)
		student_support = school.api_student_support
		facilities = school.api_facilities
		if student_support.present? || facilities.present?
			array = []
			array << 'Family Coordinator'			if student_support.try(:[], :HasFamilyCoord) == 'True' if student_support.present?
			array << 'Full-Time Nurse'				if student_support.try(:[], :HasFullTimeNurse) == 'True' if student_support.present?
			array << 'Guidance Counselor'			if student_support.try(:[], :HasGuidanceCoord) == 'True' if student_support.present?
			array << 'Handicap Access'				if facilities.try(:[], :HandicappedAccess) == 'T' if facilities.present?
			array << 'Online Health Center' 	if student_support.try(:[], :HasOnlineHealthCntr) == 'True' if student_support.present?
			array << 'Part-Time Nurse'				if student_support.try(:[], :HasPartTimeNurse) == 'True' if student_support.present?
			array << 'Social Worker'					if student_support.try(:[], :HasSocialWorker) == 'True' if student_support.present?
			return array.compact
		else
			return []
		end
	end

	def programs_list_helper(school)
		programs = school.api_programs
		if programs.present?
			array = []
			array << 'Advanced Work Class'					if programs.try(:[], :HasAdvancedClassWork) == 'True'
			array << 'Advanced Placement'						if programs.try(:[], :HasAdvancedPlacement) == 'True'
			array << 'Arts' 												if programs.try(:[], :HasArts) == 'True'
			array << 'Dual Enrollment'							if programs.try(:[], :HasDualEnroll) == 'True'
			array << 'Dual Language'								if programs.try(:[], :HasDualLanguage) == 'True'
			array << 'ELL'													if programs.try(:[], :HasELL) == 'True'
			array << 'Health'												if programs.try(:[], :HasHealth) == 'True'
			array << 'Inclusion'										if programs.try(:[], :HasInclusion) == 'True'
			array << 'Internship'										if programs.try(:[], :HasInternship) == 'True'
			array << 'International Baccalaureate'	if programs.try(:[], :HasIntnlBaccalr) == 'True'
			array << 'Phys Education'								if programs.try(:[], :HasPhysicalEd) == 'True'
			array << 'SPED'													if programs.try(:[], :HasSPED) == 'True'
			array << 'STEAM'												if programs.try(:[], :HasSTEAM) == 'True'
			array << 'STEM'													if programs.try(:[], :HasSTEM) == 'True'
			array << 'Tech Focus'										if programs.try(:[], :HasTechFocus) == 'True'
			array << 'Vocational'										if programs.try(:[], :HasVocational) == 'True'
			array << 'World Language'								if programs.try(:[], :HasWorldLanguage) == 'True'
			return array.compact
		else
			return []
		end
	end

	def preview_dates_list_helper(school)
		preview_dates = school.api_preview_dates
		if preview_dates.present?
			array = []
			array << preview_dates[:PreviewDate1] 	if preview_dates.try(:[], :PreviewDate1).present?
			array << preview_dates[:PreviewDate2] 	if preview_dates.try(:[], :PreviewDate2).present?
			array << preview_dates[:PreviewDate3] 	if preview_dates.try(:[], :PreviewDate3).present?
			array << preview_dates[:PreviewDate4] 	if preview_dates.try(:[], :PreviewDate4).present?
			array << preview_dates[:PreviewDate5] 	if preview_dates.try(:[], :PreviewDate5).present?
			array << preview_dates[:PreviewDate6] 	if preview_dates.try(:[], :PreviewDate6).present?
			array.compact
		else
			return []
		end
	end

	def partners_list_helper(school)
		partners = school.api_partners
		if partners.present?
			list = []
			partners.each do |partner|
				list << partner[:description]
			end
			return list.compact
		else
			return []
		end
	end

	def eligibility_helper(tier)
		tier.try(:gsub, /:/, ', ')
	end

	def school_tier_helper(tier)
		if tier.present?
			if tier == 'NR'
				tier_name = 'Not Ranked'
			elsif tier == 'N/A'
				tier_name = 'Not Applicable'
			else
				tier_name = "Tier #{tier}"
			end
			return tier_name
		else
			return ''
		end
	end

	def grade_levels_helper(array)
		if array.present?
			if array.length == 0
				"N/A"
			elsif array.length == 1
				array[0]
			else
				"#{array[0]} - #{array[-1]}"
			end
		else
			return nil
		end
	end

	def school_hours_start_time_helper(hours)
		if hours.present?
			hour 			= hours.match(/^\d*/).to_s.to_i
			minutes 	= hours.match(/^\d*:\d*/).to_s.gsub(/^\d*:/,'').to_s.to_i
			decimal 	= hour + (minutes / 60.0)
			range_percent = (decimal - 7) / 17
			(range_percent * 100).to_i
		else
			return ''
		end
	end

	def school_hours_end_time_helper(hours)
		if hours.present?
			hour 		= hours.gsub(/am/,'').gsub(/pm/,'').match(/-\s?\d*:/).to_s.gsub(/-\s?/,'').gsub(/:/,'').to_s.to_i
			minutes = hours.gsub(/am/,'').gsub(/pm/,'').match(/-\s?\d*:\d*/).to_s.gsub(/-\s?\d*:/,'').to_s.to_i
			hour += 12 if (hour > 0 && hour < 8) # add 12 if it's pm
			decimal = hour + (minutes / 60.0)
			range_percent = (17 - decimal) / 17
			(range_percent * 100).to_i
		end
	end

	def special_application_helper(string)
		if string.blank? || string == 'False'
			'No'
		elsif string == 'True'
			'Yes'
		end
	end

	def awc_helper(string)
		if string.blank? || string == 'No'
			'No'
		elsif string == 'Yes'
			'Yes'
		end
	end

	def spacer_helper(string)
		raw string.try(:strip).try(:gsub, /\s/, ' ')
	end

end


text:
import { Point3D, Vector3D } from '../../core';
import { Camera } from './camera';

export class MovableCamera extends Camera {
  /**
   * @link http://en.wikipedia.org/wiki/3D_projection#Perspective_projection
   * @constructor
   * @extends Camera
   */
  constructor() {
    super();

    this.position = new Point3D(0, 0, 0);
    this.orientation = new Vector3D(0, 0, 100.0);
    this.viewerPosition = new Point3D(-320, -240, 200.0);
  }

  /**
   * @param {Vertex[]} vertices
   */
  transform(vertices) {
    const camPos = this.position;
    const l = vertices.length;

    const cosX = Math.cos(this.orientation.x);
    const sinX = Math.sin(this.orientation.x);

    const cosY = Math.cos(this.orientation.y);
    const sinY = Math.sin(this.orientation.y);

    const cosZ = Math.cos(this.orientation.z);
    const sinZ = Math.sin(this.orientation.z);

    for (let i = 0; i < l; i++) {
      const vertex = vertices[i];
      const sourcePoint = vertex.transformed;
      const targetPoint = vertex.cameraTransformed;

      const sourceMinusCamX = sourcePoint.x - camPos.x;
      const sourceMinusCamY = sourcePoint.y - camPos.y;
      const sourceMinusCamZ = sourcePoint.z - camPos.z;

      const cosZSourceMinusCamX = cosZ * (sourceMinusCamX);
      const sinZSourceMinusCamX = sinZ * (sourceMinusCamX);

      const cosZSourceMinusCamY = cosZ * (sourceMinusCamY);
      const sinZSourceMinusCamY = sinZ * (sourceMinusCamY);

      const cosYSourceMinusCamZ = cosY * (sourceMinusCamZ);

      const sinYsinZcosZCamYCamX = sinY * (sinZSourceMinusCamY + cosZSourceMinusCamX);

      targetPoint.x = cosZ *
        (
          sinZSourceMinusCamY +
          cosZSourceMinusCamX
        ) -
        (
          sinY * sourceMinusCamZ
        );

      targetPoint.y = sinX *
        (
          cosYSourceMinusCamZ +
          sinYsinZcosZCamYCamX
        ) +
        cosX *
        (
          cosZSourceMinusCamY -
          sinZSourceMinusCamX
        );

      targetPoint.z = cosX *
        (
          cosYSourceMinusCamZ +
          sinYsinZcosZCamYCamX
        ) -
        sinX *
        (
          cosZSourceMinusCamY -
          sinZSourceMinusCamX
        );
    }
  }

  /**
   * @param {Vertex[]} vertices
   */

  project(vertices) {
    const l = vertices.length;
    const viewerPosition = this.viewerPosition;

    for (let i = 0; i < l; i++) {
      const vertex = vertices[i];
      const sourcePoint = vertex.cameraTransformed;
      const targetPoint = vertex.cameraProjected;

      const zDiv = viewerPosition.z / sourcePoint.z;

      targetPoint.x = zDiv * sourcePoint.x - viewerPosition.x;
      targetPoint.y = zDiv * sourcePoint.y - viewerPosition.y;
    }
  }
}


text:
package com.zimbra.common.zmime;

import java.io.ByteArrayInputStream;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.util.SharedByteArrayInputStream;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.zimbra.common.util.ByteUtil;
import com.zimbra.common.zmime.ZMimeUtility.ByteBuilder;
import com.zimbra.common.zmime.ZTransferEncoding.Base64EncoderStream;

public class ZMimeMultipartTest {
    @BeforeClass
    public static void init() {
        System.setProperty("mail.mime.ignoremultipartencoding", "false");
    }

    @Test
    public void encoded() throws Exception {
        final String boundary = "dfghjkl";
        final String preamble = "when in the course of human events...";
        final String plain = "The Rain in Spain.";
        final String html = "The Rain in Spain.";

        ByteBuilder bbheader = new ByteBuilder();
        bbheader.append("From: test@example.com\r\n");
        bbheader.append("To: rcpt@example.com\r\n");
        bbheader.append("Subject: message subject\r\n");
        bbheader.append("Message-ID: <11e1-b0c4-0800200c9a66@example.com>\r\n");
        bbheader.append("Content-Transfer-Encoding: base64\r\n");
        bbheader.append("Content-Type: multipart/alternative; boundary=").append(boundary).append("\r\n");
        bbheader.append("\r\n");

        ByteBuilder bbmulti = new ByteBuilder();
        bbmulti.append(preamble).append("\r\n");
        bbmulti.append("--").append(boundary).append("\r\n");
        bbmulti.append("Content-Type: text/plain\r\n");
        bbmulti.append("\r\n");
        bbmulti.append(plain).append("\r\n");
        bbmulti.append("--").append(boundary).append("\r\n");
        bbmulti.append("Content-Type: text/html\r\n");
        bbmulti.append("\r\n");
        bbmulti.append(html).append("\r\n");
        bbmulti.append("--").append(boundary).append("--\r\n");

        // message with CTE header and base64-encoded body
        ByteBuilder bb = new ByteBuilder();
        bb.append(bbheader);
        bb.append(ByteUtil.getContent(new Base64EncoderStream(new ByteArrayInputStream(bbmulti.toByteArray())), -1));

        Session s = Session.getDefaultInstance(new Properties());
        ZMimeMessage mm = new ZMimeMessage(s, new SharedByteArrayInputStream(bb.toByteArray()));
        Object o = mm.getContent();
        Assert.assertTrue("content is ZMimeMultipart", o instanceof ZMimeMultipart);
        ZMimeMultipart multi = (ZMimeMultipart) o;
        Assert.assertEquals("preamble matches", preamble, multi.getPreamble());
        Assert.assertEquals("2 subparts", 2, multi.getCount());
        Assert.assertEquals("part 1 content match", plain, multi.getBodyPart(0).getContent());
        Assert.assertEquals("part 2 content match", html, multi.getBodyPart(1).getContent());

        // message with CTE header and nonencoded body
        bb = new ByteBuilder();
        bb.append(bbheader);
        bb.append(bbmulti);

        mm = new ZMimeMessage(s, new SharedByteArrayInputStream(bb.toByteArray()));
        o = mm.getContent();
        Assert.assertTrue("content is ZMimeMultipart", o instanceof ZMimeMultipart);
        multi = (ZMimeMultipart) o;
        Assert.assertEquals("preamble matches", preamble, multi.getPreamble());
        Assert.assertEquals("2 subparts", 2, multi.getCount());
        Assert.assertEquals("part 1 content match", plain, multi.getBodyPart(0).getContent());
        Assert.assertEquals("part 2 content match", html, multi.getBodyPart(1).getContent());
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<TITLE>Options</TITLE>

Options

	Note: This feature is only available in weekly releases and versions after 2.11.

	The Network add-on provides the following options screens:

			Local Servers/Proxies
			Allows to manage and configure the local servers/proxies.

			Server Certificates
			Allows to manage and configure the root CA certificate and issued certificates.

See also

			Network
			the introduction to Network add-on


text:
package com.haulmont.cuba.gui.config;

import com.google.common.base.Strings;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableList;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.core.global.Resources;
import com.haulmont.cuba.core.global.Scripting;
import com.haulmont.cuba.core.sys.AppContext;
import com.haulmont.cuba.core.sys.xmlparsing.Dom4jTools;
import com.haulmont.cuba.gui.NoSuchScreenException;
import com.haulmont.cuba.gui.components.AbstractFrame;
import com.haulmont.cuba.gui.components.Window;
import com.haulmont.cuba.gui.screen.*;
import com.haulmont.cuba.gui.sys.*;
import com.haulmont.cuba.gui.xml.layout.ScreenXmlLoader;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringTokenizer;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * GenericUI class holding information about all registered in screens.xml screens.
 */
@Component(WindowConfig.NAME)
public class WindowConfig {

    public static final String NAME = "cuba_WindowConfig";

    public static final String WINDOW_CONFIG_XML_PROP = "cuba.windowConfig";

    public static final Pattern ENTITY_SCREEN_PATTERN = Pattern.compile("([A-Za-z0-9]+[$_][A-Z][_A-Za-z0-9]*)\\..+");

    protected static final List<String> LOGIN_SCREEN_IDS = ImmutableList.of("login", "loginWindow");
    protected static final List<String> MAIN_SCREEN_IDS = ImmutableList.of("main", "mainWindow");

    protected static final String LOGIN_SCREEN_PROP = "cuba.web.loginScreenId";
    protected static final String MAIN_SCREEN_PROP = "cuba.web.mainScreenId";

    private final Logger log = LoggerFactory.getLogger(WindowConfig.class);

    protected Map<String, WindowInfo> screens = new HashMap<>();
    // route -> screen id
    protected BiMap<String, String> routes = HashBiMap.create();

    protected Map<Class, WindowInfo> primaryEditors = new HashMap<>();
    protected Map<Class, WindowInfo> primaryLookups = new HashMap<>();

    @Autowired(required = false)
    protected List<UiControllersConfiguration> configurations = Collections.emptyList();

    @Inject
    protected Resources resources;
    @Inject
    protected Scripting scripting;
    @Inject
    protected Metadata metadata;
    @Inject
    protected ScreenXmlLoader screenXmlLoader;
    @Inject
    protected Dom4jTools dom4JTools;

    @Inject
    protected ApplicationContext applicationContext;
    @Inject
    protected AnnotationScanMetadataReaderFactory metadataReaderFactory;
    @Inject
    protected UiControllerMetaProvider uiControllerMetaProvider;

    protected volatile boolean initialized;

    protected ReadWriteLock lock = new ReentrantReadWriteLock();

    protected WindowAttributesProvider windowAttributesProvider = new WindowAttributesProvider() {
        @Override
        public WindowInfo.Type getType(WindowInfo windowInfo) {
            return resolveWindowInfo(windowInfo).getType();
        }

        @Nullable
        @Override
        public String getTemplate(WindowInfo windowInfo) {
            return resolveWindowInfo(windowInfo).getTemplate();
        }

        @Nonnull
        @Override
        public Class<? extends FrameOwner> getControllerClass(WindowInfo windowInfo) {
            return resolveWindowInfo(windowInfo).getControllerClass();
        }

        @Override
        public WindowInfo resolve(WindowInfo windowInfo) {
            return resolveWindowInfo(windowInfo);
        }
    };

    protected WindowInfo resolveWindowInfo(WindowInfo windowInfo) {
        Class<? extends FrameOwner> controllerClass;
        String template;

        if (windowInfo.getDescriptor() != null) {
            String className = windowInfo.getDescriptor().attributeValue("class");

            if (Strings.isNullOrEmpty(className)) {
                template = windowInfo.getDescriptor().attributeValue("template");

                Element screenXml = screenXmlLoader.load(template,
                        windowInfo.getId(), Collections.emptyMap());
                className = screenXml.attributeValue("class");
            } else {
                template = null;
            }

            if (Strings.isNullOrEmpty(className)) {
                // fallback for legacy frames
                controllerClass = AbstractFrame.class;
            } else {
                controllerClass = loadDefinedScreenClass(className);
            }

        } else if (windowInfo.getControllerClassName() != null) {
            controllerClass = loadDefinedScreenClass(windowInfo.getControllerClassName());

            UiDescriptor annotation = controllerClass.getAnnotation(UiDescriptor.class);
            if (annotation == null) {
                template = null;
            } else {
                String templatePath = UiDescriptorUtils.getInferredTemplate(annotation, controllerClass);
                if (!templatePath.startsWith("/")) {
                    String packageName = UiControllerUtils.getPackage(controllerClass);
                    if (StringUtils.isNotEmpty(packageName)) {
                        String relativePath = packageName.replace('.', '/');
                        templatePath = "/" + relativePath + "/" + templatePath;
                    }
                }

                template = templatePath;
            }
        } else {
            throw new IllegalStateException("Neither screen class nor descriptor is set for WindowInfo " + windowInfo.getId());
        }

        WindowInfo.Type type = extractWindowInfoType(windowInfo, controllerClass);

        return new ResolvedWindowInfo(windowInfo, type, controllerClass, template);
    }

    protected MetadataReaderFactory getMetadataReaderFactory() {
        return metadataReaderFactory;
    }

    protected ResourceLoader getResourceLoader() {
        return applicationContext;
    }

    protected WindowInfo.Type extractWindowInfoType(WindowInfo windowInfo, Class<? extends FrameOwner> controllerClass) {
        if (Screen.class.isAssignableFrom(controllerClass)) {
            return WindowInfo.Type.SCREEN;
        }

        if (ScreenFragment.class.isAssignableFrom(controllerClass)) {
            return WindowInfo.Type.FRAGMENT;
        }

        throw new IllegalStateException("Unknown type of screen " + windowInfo.getId());
    }

    @SuppressWarnings("unchecked")
    protected Class<? extends FrameOwner> loadDefinedScreenClass(String className) {
        return (Class<? extends FrameOwner>) scripting.loadClassNN(className);
    }

    protected void checkInitialized() {
        if (!initialized) {
            lock.readLock().unlock();
            lock.writeLock().lock();
            try {
                if (!initialized) {
                    init();
                    initialized = true;
                }
            } finally {
                lock.readLock().lock();
                lock.writeLock().unlock();
            }
        }
    }

    protected void init() {
        long startTime = System.currentTimeMillis();

        screens.clear();
        primaryEditors.clear();
        primaryLookups.clear();

        routes.clear();

        loadScreenConfigurations();
        loadScreensXml();

        log.info("WindowConfig initialized in {} ms", System.currentTimeMillis() - startTime);
    }

    protected void loadScreenConfigurations() {
        for (UiControllersConfiguration provider : configurations) {
            List<UiControllerDefinition> uiControllers = provider.getUiControllers();

            Map<String, String> projectScreens = new HashMap<>(uiControllers.size());

            for (UiControllerDefinition definition : uiControllers) {
                String existingScreenController = projectScreens.get(definition.getId());
                if (existingScreenController != null
                        && !Objects.equals(existingScreenController, definition.getControllerClass())) {
                    throw new RuntimeException(
                            String.format("Project contains screens with the same id: '%s'. See '%s' and '%s'",
                                    definition.getId(),
                                    definition.getControllerClass(),
                                    existingScreenController));
                } else {
                    projectScreens.put(definition.getId(), definition.getControllerClass());
                }

                WindowInfo windowInfo = new WindowInfo(definition.getId(), windowAttributesProvider,
                        definition.getControllerClass(), definition.getRouteDefinition());
                registerScreen(definition, windowInfo);
            }

            projectScreens.clear();
        }
    }

    protected void loadScreensXml() {
        String configName = AppContext.getProperty(WINDOW_CONFIG_XML_PROP);
        StringTokenizer tokenizer = new StringTokenizer(configName);
        for (String location : tokenizer.getTokenArray()) {
            Resource resource = resources.getResource(location);
            if (resource.exists()) {
                try (InputStream stream = resource.getInputStream()) {
                    loadConfig(dom4JTools.readDocument(stream).getRootElement());
                } catch (IOException e) {
                    throw new RuntimeException("Unable to read window config from " + location, e);
                }
            } else {
                log.warn("Resource {} not found, ignore it", location);
            }
        }
    }

    protected void loadConfig(Element rootElem) {
        for (Element element : rootElem.elements("include")) {
            String fileName = element.attributeValue("file");
            if (!StringUtils.isBlank(fileName)) {
                String incXml = resources.getResourceAsString(fileName);
                if (incXml == null) {
                    log.warn("File {} not found, ignore it", fileName);
                    continue;
                }
                loadConfig(dom4JTools.readDocument(incXml).getRootElement());
            }
        }
        for (Element element : rootElem.elements("screen")) {
            String id = element.attributeValue("id");
            if (StringUtils.isBlank(id)) {
                log.warn("Invalid window config: 'id' attribute not defined");
                continue;
            }

            RouteDefinition routeDef = loadRouteDefinition(element);

            WindowInfo windowInfo = new WindowInfo(id, windowAttributesProvider, element, routeDef);
            registerScreen(id, windowInfo);
        }
    }

    protected RouteDefinition loadRouteDefinition(Element screenElement) {
        String screenId = screenElement.attributeValue("id");
        String route = screenElement.attributeValue("route");
        String parentPrefix = screenElement.attributeValue("routeParentPrefix");
        boolean rootRoute = Boolean.parseBoolean(screenElement.attributeValue("rootRoute"));

        RouteDefinition routeDefinition;

        WindowInfo superScreen = screens.get(screenId);
        RouteDefinition superScreenRouteDefinition = superScreen != null
                ? superScreen.getRouteDefinition()
                : null;

        if (route != null && !route.isEmpty()) {
            if (superScreenRouteDefinition != null) {
                String superScreenRoute = superScreenRouteDefinition.getPath();
                String superScreenParentPrefix = superScreenRouteDefinition.getParentPrefix();

                if (!route.equals(superScreenRoute)) {
                    log.debug("Route for screen '{}' is redefined from '{}' to '{}'",
                            screenId, superScreenRoute, rootRoute);

                    routes.remove(superScreenRoute);
                }

                if (parentPrefix == null || parentPrefix.isEmpty()) {
                    parentPrefix = superScreenParentPrefix;
                }
            }
            routeDefinition = new RouteDefinition(route, parentPrefix, rootRoute);
        } else {
            routeDefinition = superScreenRouteDefinition;
        }

        return routeDefinition;
    }

    protected void registerScreen(UiControllerDefinition controllerDefinition, WindowInfo windowInfo) {
        String controllerClassName = windowInfo.getControllerClassName();
        if (controllerClassName != null) {
            registerPrimaryEditor(windowInfo, controllerDefinition);
            registerPrimaryLookup(windowInfo, controllerDefinition);
        }

        screens.put(controllerDefinition.getId(), windowInfo);

        registerScreenRoute(controllerDefinition.getId(), windowInfo);
    }

    protected void registerScreen(String id, WindowInfo windowInfo) {
        String controllerClassName = windowInfo.getControllerClassName();
        if (controllerClassName != null) {
            MetadataReader classMetadata = loadClassMetadata(controllerClassName);
            AnnotationMetadata annotationMetadata = classMetadata.getAnnotationMetadata();

            registerPrimaryEditor(windowInfo, annotationMetadata);
            registerPrimaryLookup(windowInfo, annotationMetadata);
        }

        screens.put(id, windowInfo);

        registerScreenRoute(id, windowInfo);
    }

    protected void registerScreenRoute(String screenId, WindowInfo windowInfo) {
        RouteDefinition routeDef = windowInfo.getRouteDefinition();
        if (routeDef != null) {
            String route = routeDef.getPath();
            String registeredScreenId = routes.get(route);
            if (registeredScreenId != null
                    && !Objects.equals(screenId, registeredScreenId)) {

                if (!routeOverrideAllowed(screenId)) {
                    return;
                }

                log.debug("Multiple use of the route '{}' for different screens is detected: '{}' and '{}'. " +
                                "The screen '{}' will be opened during navigation as the last registered screen",
                        route, screenId, registeredScreenId, screenId);
            }

            String registeredRoute = routes.inverse().get(screenId);
            if (StringUtils.isNotEmpty(registeredRoute)
                    && !Objects.equals(registeredRoute, route)) {
                log.debug("Route for screen '{}' is redefined from '{}' to '{}'",
                        screenId, registeredRoute, route);

                routes.remove(registeredRoute);
            }

            routes.put(route, screenId);
        }
    }

    /**
     * Have to do this check due to Login/Main Screen are registered
     * before legacy LoginWindow / AppMainWindow.
     */
    protected boolean routeOverrideAllowed(String newScreenId) {
        if (LOGIN_SCREEN_IDS.contains(newScreenId)) {
            String loginScreenId = AppContext.getProperty(LOGIN_SCREEN_PROP);
            return StringUtils.equals(loginScreenId, newScreenId);
        }

        if (MAIN_SCREEN_IDS.contains(newScreenId)) {
            String mainScreenId = AppContext.getProperty(MAIN_SCREEN_PROP);
            return StringUtils.equals(mainScreenId, newScreenId);
        }

        return true;
    }

    protected void registerPrimaryEditor(WindowInfo windowInfo, AnnotationMetadata annotationMetadata) {
        Map<String, Object> primaryEditorAnnotation =
                annotationMetadata.getAnnotationAttributes(PrimaryEditorScreen.class.getName());
        registerPrimaryEditor(windowInfo, primaryEditorAnnotation);
    }

    protected void registerPrimaryEditor(WindowInfo windowInfo, UiControllerDefinition controllerDefinition) {
        Map<String, Object> primaryEditorAnnotation = controllerDefinition.getControllerMeta()
                .getAnnotationAttributes(PrimaryEditorScreen.class.getName());
        registerPrimaryEditor(windowInfo, primaryEditorAnnotation);
    }

    protected void registerPrimaryEditor(WindowInfo windowInfo, @Nullable Map<String, Object> primaryEditorAnnotation) {
        if (primaryEditorAnnotation != null) {
            Class entityClass = (Class) primaryEditorAnnotation.get("value");
            if (entityClass != null) {
                MetaClass metaClass = metadata.getClass(entityClass);
                MetaClass originalMetaClass = metadata.getExtendedEntities().getOriginalOrThisMetaClass(metaClass);
                primaryEditors.put(originalMetaClass.getJavaClass(), windowInfo);
            }
        }
    }

    protected void registerPrimaryLookup(WindowInfo windowInfo, AnnotationMetadata annotationMetadata) {
        Map<String, Object> primaryEditorAnnotation =
                annotationMetadata.getAnnotationAttributes(PrimaryLookupScreen.class.getName());
        registerPrimaryLookup(windowInfo, primaryEditorAnnotation);
    }

    protected void registerPrimaryLookup(WindowInfo windowInfo, UiControllerDefinition controllerDefinition) {
        Map<String, Object> primaryEditorAnnotation = controllerDefinition.getControllerMeta()
                .getAnnotationAttributes(PrimaryLookupScreen.class.getName());
        registerPrimaryLookup(windowInfo, primaryEditorAnnotation);
    }

    protected void registerPrimaryLookup(WindowInfo windowInfo, @Nullable Map<String, Object> primaryEditorAnnotation) {
        if (primaryEditorAnnotation != null) {
            Class entityClass = (Class) primaryEditorAnnotation.get("value");
            if (entityClass != null) {
                MetaClass metaClass = metadata.getClass(entityClass);
                MetaClass originalMetaClass = metadata.getExtendedEntities().getOriginalOrThisMetaClass(metaClass);
                primaryLookups.put(originalMetaClass.getJavaClass(), windowInfo);
            }
        }
    }

    protected MetadataReader loadClassMetadata(String className) {
        Resource resource = getResourceLoader().getResource("/" + className.replace(".", "/") + ".class");
        if (!resource.isReadable()) {
            throw new RuntimeException(String.format("Resource %s is not readable for class %s", resource, className));
        }
        try {
            return getMetadataReaderFactory().getMetadataReader(resource);
        } catch (IOException e) {
            throw new RuntimeException("Unable to read resource " + resource, e);
        }
    }

    /**
     * Loads hot-deployed {@link UiController} screens and registers
     * {@link UiControllersConfiguration} containing new {@link UiControllerDefinition}.
     *
     * @param className the fully qualified name of the screen class to load
     */
    public void loadScreenClass(final String className) {
        final Class screenClass = scripting.loadClass(className);
        if (screenClass == null
                || !FrameOwner.class.isAssignableFrom(screenClass)) {
            log.warn("Failed to hot deploy screen '{}'. Unable to load screen class", className);
            return;
        }

        //noinspection unchecked
        UiControllerDefinition uiControllerDefinition = new UiControllerDefinition(uiControllerMetaProvider.get(screenClass));

        UiControllersConfiguration controllersConfiguration = new UiControllersConfiguration();

        controllersConfiguration.setApplicationContext(applicationContext);
        controllersConfiguration.setMetadataReaderFactory(metadataReaderFactory);
        controllersConfiguration.setExplicitDefinitions(Collections.singletonList(uiControllerDefinition));

        configurations.add(controllersConfiguration);

        reset();
    }

    /**
     * Make the config to reload screens on next request.
     */
    public void reset() {
        initialized = false;
    }

    /**
     * Get screen information by screen ID.
     *
     * @param id screen ID as set up in screens.xml
     * @return screen's registration information or null if not found
     */
    @Nullable
    public WindowInfo findWindowInfo(String id) {
        lock.readLock().lock();
        try {
            checkInitialized();

            WindowInfo windowInfo = screens.get(id);
            if (windowInfo == null) {
                Matcher matcher = ENTITY_SCREEN_PATTERN.matcher(id);
                if (matcher.matches()) {
                    MetaClass metaClass = metadata.getClass(matcher.group(1));
                    if (metaClass == null)
                        return null;
                    MetaClass originalMetaClass = metadata.getExtendedEntities().getOriginalMetaClass(metaClass);
                    if (originalMetaClass != null) {
                        String originalId = new StringBuilder(id)
                                .replace(matcher.start(1), matcher.end(1), originalMetaClass.getName()).toString();
                        windowInfo = screens.get(originalId);
                    }
                }
            }
            return windowInfo;
        } finally {
            lock.readLock().unlock();
        }
    }

    /**
     * Get screen information by screen ID.
     *
     * @param id screen ID as set up in screens.xml
     * @return screen's registration information
     * @throws NoSuchScreenException if the screen with specified ID is not registered
     */
    public WindowInfo getWindowInfo(String id) {
        WindowInfo windowInfo = findWindowInfo(id);
        if (windowInfo == null) {
            throw new NoSuchScreenException(id);
        }
        return windowInfo;
    }

    /**
     * Get screen information by route.
     *
     * @param route route
     * @return screen's registration information or null if not found
     */
    @Nullable
    public WindowInfo findWindowInfoByRoute(String route) {
        String screenId = routes.get(route);
        return screenId != null
                ? findWindowInfo(screenId)
                : null;
    }

    /**
     * Find route by screen id.
     *
     * @param id screen id
     * @return registered route or null if no route for screen
     */
    @Nullable
    public String findRoute(String id) {
        return routes.inverse().get(id);
    }

    /**
     * @return true if the configuration contains a screen with provided ID
     */
    public boolean hasWindow(String id) {
        return findWindowInfo(id) != null;
    }

    /**
     * All registered screens
     */
    public Collection<WindowInfo> getWindows() {
        lock.readLock().lock();
        try {
            checkInitialized();
            return screens.values();
        } finally {
            lock.readLock().unlock();
        }
    }

    public String getMetaClassScreenId(MetaClass metaClass, String suffix) {
        MetaClass screenMetaClass = metaClass;
        MetaClass originalMetaClass = metadata.getExtendedEntities().getOriginalMetaClass(metaClass);
        if (originalMetaClass != null) {
            screenMetaClass = originalMetaClass;
        }

        return screenMetaClass.getName() + suffix;
    }

    public String getBrowseScreenId(MetaClass metaClass) {
        return getMetaClassScreenId(metaClass, Window.BROWSE_WINDOW_SUFFIX);
    }

    public String getLookupScreenId(MetaClass metaClass) {
        MetaClass originalMetaClass = metadata.getExtendedEntities().getOriginalOrThisMetaClass(metaClass);
        WindowInfo windowInfo = primaryLookups.get(originalMetaClass.getJavaClass());
        if (windowInfo != null) {
            return windowInfo.getId();
        }

        return getMetaClassScreenId(metaClass, Window.LOOKUP_WINDOW_SUFFIX);
    }

    public String getEditorScreenId(MetaClass metaClass) {
        MetaClass originalMetaClass = metadata.getExtendedEntities().getOriginalOrThisMetaClass(metaClass);
        WindowInfo windowInfo = primaryEditors.get(originalMetaClass.getJavaClass());
        if (windowInfo != null) {
            return windowInfo.getId();
        }

        return getMetaClassScreenId(metaClass, Window.EDITOR_WINDOW_SUFFIX);
    }

    public WindowInfo getEditorScreen(Entity entity) {
        MetaClass metaClass = entity.getMetaClass();
        MetaClass originalMetaClass = metadata.getExtendedEntities().getOriginalOrThisMetaClass(metaClass);
        WindowInfo windowInfo = primaryEditors.get(originalMetaClass.getJavaClass());
        if (windowInfo != null) {
            return windowInfo;
        }

        String editorScreenId = getEditorScreenId(metaClass);
        return getWindowInfo(editorScreenId);
    }

    /**
     * Get available lookup screen by class of entity
     *
     * @param entityClass entity class
     * @return id of lookup screen
     * @throws NoSuchScreenException if the screen with specified ID is not registered
     */
    public WindowInfo getLookupScreen(Class<? extends Entity> entityClass) {
        MetaClass metaClass = metadata.getSession().getClass(entityClass);

        MetaClass originalMetaClass = metadata.getExtendedEntities().getOriginalOrThisMetaClass(metaClass);
        WindowInfo windowInfo = primaryLookups.get(originalMetaClass.getJavaClass());
        if (windowInfo != null) {
            return windowInfo;
        }

        String lookupScreenId = getAvailableLookupScreenId(metaClass);
        return getWindowInfo(lookupScreenId);
    }

    public String getAvailableLookupScreenId(MetaClass metaClass) {
        String id = getLookupScreenId(metaClass);
        if (!hasWindow(id)) {
            id = getBrowseScreenId(metaClass);
        }
        return id;
    }

    public static class ResolvedWindowInfo extends WindowInfo {

        protected final String template;
        protected final Class<? extends FrameOwner> controllerClass;
        protected final Type type;

        public ResolvedWindowInfo(WindowInfo windowInfo, Type type, Class<? extends FrameOwner> controllerClass,
                                  @Nullable String template) {
            super(windowInfo.getId(), null, windowInfo.getDescriptor(),
                    windowInfo.getControllerClassName(), windowInfo.getRouteDefinition());

            this.template = template;

            this.controllerClass = controllerClass;
            this.type = type;
        }

        @Nullable
        @Override
        public String getTemplate() {
            return template;
        }

        @Override
        public Type getType() {
            return type;
        }

        @Nonnull
        @Override
        public Class<? extends FrameOwner> getControllerClass() {
            return controllerClass;
        }

        @Override
        public WindowInfo resolve() {
            return this;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            ResolvedWindowInfo that = (ResolvedWindowInfo) o;
            return Objects.equals(template, that.template) &&
                    Objects.equals(controllerClass, that.controllerClass) &&
                    type == that.type;
        }

        @Override
        public int hashCode() {
            return Objects.hash(template, controllerClass, type);
        }
    }
}


text:
package org.apache.karaf.shell.osgi;

import java.util.List;

import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.osgi.service.packageadmin.PackageAdmin;
import org.apache.felix.gogo.commands.Command;

@Command(scope = "osgi", name = "resolve", description = "Resolve bundle(s).")
public class ResolveBundle extends BundlesCommandOptional {

    protected void doExecute(List<Bundle> bundles) throws Exception {
        // Get package admin service.
        ServiceReference ref = getBundleContext().getServiceReference(PackageAdmin.class.getName());
        if (ref == null) {
            System.out.println("PackageAdmin service is unavailable.");
            return;
        }
        try {
            PackageAdmin pa = (PackageAdmin) getBundleContext().getService(ref);
            if (pa == null) {
                System.out.println("PackageAdmin service is unavailable.");
                return;
            }
            if (bundles.isEmpty()) {
                pa.resolveBundles(null);
            } else {
                pa.resolveBundles(bundles.toArray(new Bundle[bundles.size()]));
            }
        }
        finally {
            getBundleContext().ungetService(ref);
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static SDL2.SDL;

namespace UniqueEngine
{
    public class Color
    {
        public byte R, G, B, A;
        public Color() { }
        public Color(byte r, byte g, byte b, byte a)
        {
            A = a;
            B = b;
            G = g;
            R = r;
        }

        public static readonly Color Black = new Color(0, 0, 0, 255);
        public static readonly Color White = new Color(255, 255, 255, 255);

        internal SDL_Color ToSDL2Color()
        {
            return new SDL_Color() { r = R, g = G, b = B, a = A };
        }
    }
}


text:
Fotos do veículo

    <spacer></spacer>

        <input id="input-image" input-image type="file" class="file-loading"
               name="urlImage"
               focus-on-show
               ng-bind="regCtrl.car.urlImage"
               data-show-caption="true"
               data-show-remove="false"
               data-initial-caption="Selecione a imagem principal *"
               data-show-upload="false"
               data-show-preview="false"
               data-main-class="input-group-lg"
               data-show-cancel="false"
               data-upload-url="#">

        <input id="input-images" ng-bind="regCtrl.car.thumbnails" input-images type="file" multiple="multiple"
               class="file-loading">

    <spacer></spacer>

            <button type="button" role="button" class="btn btn-default btn-lg col-xs-12 card-shadow"
                    tabindex="-1" ng-click="SystemService.page = 0">
                Cancelar
            </button>

            <button type="button" role="button" class="btn btn-primary btn-lg col-xs-12 card-shadow"
                    ng-click="regCtrl.submit()"
                    >
                Salvar
            </button>


text:
#include "HandshakeHandler.hpp"
#include "MessageHandler.hpp"
#include "MessageChanger.hpp"
#include "MessagePostprocessor.hpp"
#include "../Types.hpp"
#include "../Controller.hpp"

#include <queue>

namespace pipeline {

class Pipeline
{
    struct HandshakePipeline {
        HandshakePipeline(ConnectionId id, Controller& controller):
            handler(id, controller) {}

        HandshakeHandler handler;
        std::queue<Message> queue;
    };

public:
    Pipeline(Sender sender, Controller& controller):
        sender_(sender), controller_(controller) {}

    void addConnection(ConnectionId id);
    void deleteConnection(ConnectionId id);
    void processMessage(Message message);

    void addBarrier();
    void flushPipeline();

    size_t queueSize() const {return queue_.size();}

private:
    Sender sender_;
    Controller& controller_;

    std::unordered_map<ConnectionId, HandshakePipeline> handshake_pipelines_;
    std::unordered_map<ConnectionId, MessageHandler> message_handlers_;
    MessageChanger message_changer_;
    std::unordered_map<ConnectionId,
                       MessagePostprocessor> message_postprocessors_;

    std::mutex mutex_;
    QueueWithBarriers<Message> queue_;

    void handle_message(Message message);
    void forward_message(Message message);
    void enqueue_message(Message message);
};

} // namespace pipeline


text:
YUI.add('aui-form-builder-field-types-modal-tests', function(Y) {

    var suite = new Y.Test.Suite('aui-form-builder-field-types-modal');

    suite.add(new Y.Test.Case({
        name: 'AUI Form Builder Field Types Modal Unit Tests',

        tearDown: function() {
            this._fieldTypesModal && this._fieldTypesModal.destroy();
        },

        createFieldTypesSettingsModal: function(config) {
            this._fieldTypesModal = new Y.FormBuilderFieldTypesModal(
                Y.merge({
                    centered: true,
                    cssClass: 'form-builder-modal',
                    draggable: false,
                    fieldTypes: [
                        new Y.FormBuilderFieldType({
                            fieldClass: Y.FormBuilderFieldText,
                            label: 'Text'
                        })
                    ],
                    modal: true,
                    resizable: false,
                    visible: false,
                    zIndex: 3
                }, config)
            );
        },

        'should not render field types before necessary': function() {
            this.createFieldTypesSettingsModal();
            Y.Assert.isNull(Y.one('.form-builder-modal'));

            this._fieldTypesModal.render();
            Y.Assert.isNotNull(Y.one('.form-builder-modal'));
        },

        'should not throw error when hiding the modal before rendered': function() {
            this.createFieldTypesSettingsModal();

            this._fieldTypesModal.hide();
            Y.Assert.isNull(Y.one('.form-builder-modal'));
        },

        'should close field types modal after clicking on the close button': function() {
            var formBuilderModal;

            this.createFieldTypesSettingsModal();
            this._fieldTypesModal.render();
            this._fieldTypesModal.show();

            formBuilderModal = Y.one('.form-builder-modal');
            formBuilderModal.one('.close').simulate('mousemove');
            formBuilderModal.one('.close').simulate('click');

            Y.Assert.isTrue(formBuilderModal.hasClass('modal-dialog-hidden'));
            Y.Assert.isFalse(this._fieldTypesModal.get('visible'));
        },

        'should fire the event "selectFieldType" after clicking on a field type': function() {
            var mock = new Y.Mock();

            this.createFieldTypesSettingsModal({
                fieldTypes: [
                    new Y.FormBuilderFieldType({
                        fieldClass: mock.fieldClass,
                        label: 'My Field'
                    })
                ]
            });

            this._fieldTypesModal.render();

            Y.Mock.expect(mock, {
                args: [Y.Mock.Value.Object],
                callCount: 1,
                method: 'callback'
            });

            this._fieldTypesModal.after('selectFieldType', mock.callback);

            this._fieldTypesModal.show();

            Y.one('.field-type').simulate('click');

            Y.Mock.verify(mock);
        },

        'should fire the event "selectFieldType" after keypress on a field type': function() {
            var mock = new Y.Mock();

            this.createFieldTypesSettingsModal({
                fieldTypes: [
                    new Y.FormBuilderFieldType({
                        fieldClass: mock.fieldClass,
                        label: 'My Field'
                    })
                ]
            });

            this._fieldTypesModal.render();

            Y.Mock.expect(mock, {
                args: [Y.Mock.Value.Object],
                callCount: 1,
                method: 'callback'
            });

            this._fieldTypesModal.after('selectFieldType', mock.callback);

            this._fieldTypesModal.show();

            Y.one('.field-type').simulate('keydown', { keyCode: 13 });

            Y.Mock.verify(mock);
        },

        'should update the UI after changing the fieldTypes attribute': function() {
            var mock = new Y.Mock();

            this.createFieldTypesSettingsModal({
                fieldTypes: [
                    new Y.FormBuilderFieldType({
                        fieldClass: mock.fieldClass,
                        label: 'My Field'
                    })
                ]
            });

            this._fieldTypesModal.render();

            Y.Assert.areEqual(Y.all('.field-type').size(), 1);

            this._fieldTypesModal.set('fieldTypes', [
                new Y.FormBuilderFieldType({
                    fieldClass: mock.fieldClass,
                    label: 'My new Field 1'
                }),
                new Y.FormBuilderFieldType({
                    fieldClass: mock.fieldClass,
                    label: 'My new Field 2'
                })
            ]);

            Y.Assert.areEqual(Y.all('.field-type').size(), 2);
        }
    }));

    Y.Test.Runner.add(suite);
}, '', {
    requires: [
        'aui-form-builder',
        'aui-form-builder-field-text',
        'node-event-simulate',
        'test'
    ],
    test: function(Y) {
        return Y.UA.ie === 0 || Y.UA.ie > 8;
    }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <help>The student's enrolment status, for example, full-time or half-time.</help>
    <label>Enrolment Status</label>
    <name>Enrollment_Status__c</name>
    <picklistValues>
        <masterLabel>Full-time</masterLabel>
        <translation>Full-time</translation>
    </picklistValues>
    <picklistValues>
        <masterLabel>Half-time</masterLabel>
        <translation>Half-time</translation>
    </picklistValues>
    <picklistValues>
        <masterLabel>Less than half-time</masterLabel>
        <translation>Less than half-time</translation>
    </picklistValues>
</CustomFieldTranslation>


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Core\Serializer\Filter;

use ApiPlatform\Core\Api\FilterInterface as BaseFilterInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Symfony serializer context builder filter interface.
 *
 * @author Baptiste Meyer <baptiste.meyer@gmail.com>
 */
interface FilterInterface extends BaseFilterInterface
{
    /**
     * Apply a filter to the serializer context.
     *
     * @param Request $request
     * @param bool    $normalization
     * @param array   $attributes
     * @param array   $context
     */
    public function apply(Request $request, bool $normalization, array $attributes, array &$context);
}


text:
<?php

namespace humhub\modules\comment\widgets;

use Yii;

/**
 * This widget is used to show a comment link inside the wall entry controls.
 *
 * @since 0.5
 */
class CommentLink extends \yii\base\Widget
{

    const MODE_INLINE = 'inline';
    const MODE_POPUP = 'popup';

    /**
     * Content Object
     */
    public $object;

    /**
     * Mode
     *
     * inline: Show comments on the same page with CommentsWidget (default)
     * popup: Open comments popup, display only link
     *
     * @var type
     */
    public $mode;

    /**
     * Executes the widget.
     */
    public function run()
    {

        if ($this->mode == "") {
            $this->mode = self::MODE_INLINE;
        }

        if (!Yii::$app->getModule('comment')->canComment($this->object->content)) {
            return;
        }

        return $this->render('link', array(
                    'id' => $this->object->getUniqueId(),
                    'mode' => $this->mode,
                    'objectModel' => $this->object->content->object_model,
                    'objectId' => $this->object->content->object_id,
        ));
    }

    /**
     * Returns count of existing comments
     *
     * @return Int Comment Count
     */
    public function getCommentsCount()
    {
        return \humhub\modules\comment\models\Comment::GetCommentCount(get_class($this->object), $this->object->getPrimaryKey());
    }

}

?>


text:
This is the experimental, community-supported Windows port of MicroPython.
It is based on Unix port, and expected to remain so.
The port requires additional testing, debugging, and patches. Please
consider to contribute.

All gcc-based builds use the gcc compiler from [Mingw-w64](mingw-w64.org),
which is the advancement of the original mingw project. The latter is
getting obsolete and is not actively supported by MicroPython.

Build instruction assume you're in the ports/windows directory.

Building on Debian/Ubuntu Linux system
---------------------------------------

    sudo apt-get install python3 build-essential gcc-mingw-w64
    make -C ../../mpy-cross
    make CROSS_COMPILE=i686-w64-mingw32-

Building under Cygwin
---------------------

Install Cygwin, then install following packages using Cygwin's setup.exe:

* mingw64-i686-gcc-core
* mingw64-x86_64-gcc-core
* make

Also install the python3 package, or install Python globally for Windows (see below).

Build using:

    make -C ../../mpy-cross CROSS_COMPILE=i686-w64-mingw32-
    make CROSS_COMPILE=i686-w64-mingw32-

Or for 64bit:

    make -C ../../mpy-cross CROSS_COMPILE=x86_64-w64-mingw32-
    make CROSS_COMPILE=x86_64-w64-mingw32-

Building under MSYS2
--------------------

Install MSYS2 from http://repo.msys2.org/distrib, start the msys2.exe shell and
install the build tools:

    pacman -Syuu
    pacman -S make mingw-w64-x86_64-gcc pkg-config python3

Start the mingw64.exe shell and build:

    make -C ../../mpy-cross STRIP=echo SIZE=echo
    make

Building using MS Visual Studio 2013 (or higher)
------------------------------------------------

Install Python. There are several ways to do this, for example: download and install the
latest Python 3 release from https://www.python.org/downloads/windows or from
https://docs.conda.io/en/latest/miniconda.html,
or open the Microsoft Store app and search for Python and install it.

Install Visual Studio and the C++ toolset (for recent versions: install
the free Visual Studio Community edition and the *Desktop development with C++* workload).

In the IDE, open `micropython-cross.vcxproj` and `micropython.vcxproj` and build.

To build from the command line:

    msbuild ../../mpy-cross/mpy-cross.vcxproj
    msbuild micropython.vcxproj

__Stack usage__

The msvc compiler is quite stack-hungry which might result in a "maximum recursion depth exceeded"
RuntimeError for code with lots of nested function calls.
There are several ways to deal with this:
- increase the threshold used for detection by altering the argument to `mp_stack_set_limit` in `ports/unix/main.c`
- disable detection all together by setting `MICROPY_STACK_CHECK` to "0" in `ports/windows/mpconfigport.h`
- disable the /GL compiler flag by setting `WholeProgramOptimization` to "false"

See [issue 2927](https://github.com/micropython/micropython/issues/2927) for more information.

Running the tests
-----------------

This is similar for all ports:

    cd ../../tests
    python3 ./run-tests

Depending on the combination of platform and Python version used it might be
needed to first set the MICROPY_MICROPYTHON environment variable to
the full path of micropython.exe.

Running on Linux using Wine
---------------------------

The default build (MICROPY_USE_READLINE=1) uses extended Windows console
functions and thus should be ran using the `wineconsole` tool. Depending
on the Wine build configuration, you may also want to select the curses
backend which has the look&feel of a standard Unix console:

    wineconsole --backend=curses ./micropython.exe

For more info, see https://www.winehq.org/docs/wineusr-guide/cui-programs .

If built without line editing and history capabilities
(MICROPY_USE_READLINE=0), the resulting binary can be run using the standard
`wine` tool.


text:
This will return the html of the page at the point this point in the feature
spec; however, you'll only see the HTML, no styling.

`save_and_open_page`


text:
A single view that demonstrates the Fidor API OAuth login flow and how to get
an access token. Uses Sinatra on its server side.

## Usage

This uses bundler to install the required gems:

  cd ruby_oauth_plain
  bundle install
  ruby example.rb

  # or run on different port than :4567 provided by WEBrick
  ruby example.rb -p 3004

## Configuration

In case you downloaded this project from the Fidor AppManager, all the
configuration should have already been set up for you. In case you
retrieved this example from another source, you'll need to open the
`example.rb` file and fill in the configuration values at the top of the
file. You will be able to find out the values in the AppManager, create
a new App and use the configuration from the new App's detail page.


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

namespace Nether.Web.IntegrationTests.Identity
{
    public class LoginApiTests : WebTestBase, IClassFixture<IntegrationTestUsersFixture>
    {
        [Fact()]
        public async Task As_an_admin_I_can_create_a_user_with_a_login_and_login_as_that_user()
        {
            var client = await AsAdminAsync();

            // create user
            var response = await client.PostAsJsonAsync(
                "/api/identity/users",
                new
                {
                    role = "Player",
                    active = true
                });

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);

            var userLocation = response.Headers.Location.LocalPath;

            // create login
            string username = Guid.NewGuid().ToString();
            const string password = "TestPassword";
            response = await client.PutAsJsonAsync(
                $"{userLocation}/logins/password/{username}",
                new
                {
                    password
                });

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);

            var loginLocation = response.Headers.Location.LocalPath;
            Assert.NotNull(loginLocation);

            // Get the user again and verify the login is present in the returned data
            response = await client.GetAsync(userLocation);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var userContent = await response.Content.ReadAsAsync<dynamic>();
            var user = userContent.user;
            var logins = ((JArray)user.logins).Cast<dynamic>().ToList();
            Assert.Equal(1, logins.Count);

            var login = logins[0];
            Assert.Equal("password", (string)login.providerType);
            Assert.Equal(username, (string)login.providerId);
            Assert.Equal($"/api/identity/users/{user.userId}/logins/password/{username}", (string)login._link);

            // login as that user
            var newClient = await AsPlayerAsync(username, password);

            // delete the user
            response = await client.DeleteAsync(userLocation);
            Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
        }

        private async Task<HttpClient> AsPlayerAsync(string username = "testuser", string password = null)
        {
            return await GetClientAsync(username, password);
        }
        private async Task<HttpClient> AsAdminAsync()
        {
            return await GetClientAsync("devadmin");
        }
    }
}


text:
package GameCollection;
import java.util.Map;
import java.util.TreeMap;

/** A bunch of games and their associated attributes.. */
public class GameCollection {

	/** A game with this feature takes less than an hour to play. */
	public static final int LESS_THAN_ONE_HOUR = 1 << 10;

	/** A game with this feature takes an hour or two to play. */
	public static final int ONE_TO_TWO_HOURS = 1 << 11;

	/** A game with this feature takes over two hours to play. */
	public static final int OVER_TWO_HOURS = 1 << 12;

	/** A game with this feature is easy to pick up. */
	public static final int LOW_DIFFICULTY = 1 << 13;

	/** A game with this feature is of moderate difficulty. */
	public static final int MEDIUM_DIFFICULTY = 1 << 14;

	/** A game with this feature take considerable study to play. */
	public static final int HIGH_DIFFICULTY = 1 << 15;

	/** A game with this feature involves agility or a steady hand. */
	public static final int DEXTERITY = 1 << 16;

	/** A game with this feature involves talking people into things. */
	public static final int DIPLOMACY = 1 << 17;

	/** A game with this feature involves significant randomness. */
	public static final int LUCK = 1 << 18;

	/** A game with this feature involves careful planning. */
	public static final int STRATEGY = 1 << 19;

	/** Map associating game titles with attribute bit vectors. */
	private Map<String, Integer> games;

	/**
	 *  Return a bit vector with a feature for each number of players
	 *  from minPlayers through maxPlayers.
	 */
	public static int playerRange (int minPlayers, int maxPlayers){
		int result = 0;
		for (int i = minPlayers; i <= maxPlayers; i++){
			result |= 1 << (i - 1);
		}
		return result;
	}

	/** A GameCollection is initially empty. */
	public GameCollection(){
		games = new TreeMap<String, Integer>();
	}

	/** Add a new game to this collection. */
	public void addGame (String title, int attributes){
		games.put(title, attributes);
	}

	/**
	 *  Print the names of games which have all of the features in the
	 *  constraints bit vector.
	 */
	public void findGames(int constraints){
		for(Map.Entry<String, Integer> game : games.entrySet()){
			if((constraints & game.getValue()) == constraints){
				System.out.println(game.getKey());
			}
		}
	}

	/** Create a GameCollection, fill it, and find some for today. */
	public static void main(String[] args) {
		GameCollection collection = new GameCollection();
		collection.addGame("Apples to Apples",
										playerRange(4, 8) | LESS_THAN_ONE_HOUR
										| LOW_DIFFICULTY | DIPLOMACY);
		collection.addGame("Bamboleo",
										playerRange(2, 7) | LESS_THAN_ONE_HOUR
										| LOW_DIFFICULTY | DEXTERITY);
		collection.addGame("Bohnanza",
										playerRange(3, 7) | LESS_THAN_ONE_HOUR
										| MEDIUM_DIFFICULTY | DIPLOMACY | LUCK);
		collection.addGame("Carcassonne",
										playerRange(2, 5) | LESS_THAN_ONE_HOUR
										| MEDIUM_DIFFICULTY | LUCK | STRATEGY);
	}

}


text:
package cn.droidlover.xdroidmvp.test.router;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityOptionsCompat;

import cn.droidlover.xdroidmvp.mvp.XActivity;
import cn.droidlover.xdroidmvp.router.Router;

/**
 * Created by wanglei on 2017/1/30.
 */

public class StartActivity extends XActivity {

    @Override
    public void initData(Bundle savedInstanceState) {
        Router.newIntent(context)
                .to(EndActivity.class)
                .putString("arg_name", "xdroid")
                .launch();

        Router.newIntent(context)
                .to(EndActivity.class)
                .putString("arg_name", "xdroid")
                .requestCode(100)
                .launch();

        int exitAnim = 0, enterAnim = 0;
        Router.newIntent(context)
                .to(EndActivity.class)
                .putString("arg_name", "xdroid")
                .anim(enterAnim, exitAnim)
                .launch();

        Router.newIntent(context)
                .to(EndActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                .launch();

        Router.newIntent(context)
                .to(EndActivity.class)
                .options(ActivityOptionsCompat.makeBasic())
                .launch();

    }

    @Override
    public int getLayoutId() {
        return 0;
    }

    @Override
    public Object newP() {
        return null;
    }
}


text:
export * from "./interfaces";
export * from "./object";


text:
package org.opensmartgridplatform.cucumber.platform.smartmetering.support.ws.smartmetering.configuration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.util.CollectionUtils;

import org.opensmartgridplatform.adapter.ws.schema.smartmetering.configuration.ConfigurationFlag;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.configuration.ConfigurationFlagType;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.configuration.ConfigurationFlags;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.configuration.ConfigurationObject;
import org.opensmartgridplatform.adapter.ws.schema.smartmetering.configuration.GprsOperationModeType;
import org.opensmartgridplatform.cucumber.core.ReadSettingsHelper;
import org.opensmartgridplatform.cucumber.platform.helpers.SettingsHelper;
import org.opensmartgridplatform.cucumber.platform.smartmetering.PlatformSmartmeteringKeys;

public class ConfigurationObjectFactory {

    private ConfigurationObjectFactory() {
        // Private constructor for utility class
    }

    public static ConfigurationObject forGprsOperationModeAndFlags(final GprsOperationModeType gprsOperationMode,
            final Set<ConfigurationFlagType> enableFlags, final Set<ConfigurationFlagType> disableFlags) {

        final ConfigurationObject configurationObject = new ConfigurationObject();
        configurationObject.setGprsOperationMode(gprsOperationMode);
        final List<ConfigurationFlag> configurationFlagList = new ArrayList<>();
        configurationFlagList.addAll(getFlags(enableFlags, true));
        configurationFlagList.addAll(getFlags(disableFlags, false));
        if (!configurationFlagList.isEmpty()) {
            final ConfigurationFlags configurationFlags = new ConfigurationFlags();
            configurationFlags.getConfigurationFlag().addAll(configurationFlagList);
            configurationObject.setConfigurationFlags(configurationFlags);
        }
        return configurationObject;
    }

    private static List<ConfigurationFlag> getFlags(final Set<ConfigurationFlagType> flagTypes, final boolean enabled) {
        if (CollectionUtils.isEmpty(flagTypes)) {
            return Collections.emptyList();
        }
        final List<ConfigurationFlag> configurationFlags = new ArrayList<>();
        for (final ConfigurationFlagType flagType : flagTypes) {
            final ConfigurationFlag configurationFlag = new ConfigurationFlag();
            configurationFlag.setConfigurationFlagType(flagType);
            configurationFlag.setEnabled(enabled);
            configurationFlags.add(configurationFlag);
        }
        return configurationFlags;
    }

    public static ConfigurationObject fromParameterMap(final Map<String, String> requestParameters) {
        final ConfigurationObject configurationObject = new ConfigurationObject();
        setConfigurationFlags(configurationObject, requestParameters);
        configurationObject.setGprsOperationMode(ReadSettingsHelper.getEnum(requestParameters,
                PlatformSmartmeteringKeys.GPRS_OPERATION_MODE_TYPE, GprsOperationModeType.class));
        return configurationObject;
    }

    private static boolean hasConfigurationFlags(final Map<String, String> requestParameters) {
        return requestParameters.containsKey(PlatformSmartmeteringKeys.CONFIGURATION_FLAG_COUNT);
    }

    private static void setConfigurationFlags(final ConfigurationObject configurationObject,
            final Map<String, String> requestParameters) {

        if (!hasConfigurationFlags(requestParameters)) {
            return;
        }

        final ConfigurationFlags configurationFlags = new ConfigurationFlags();
        final List<ConfigurationFlag> configurationFlagList = new ArrayList<>();
        final int numberOfFlags = Integer
                .parseInt(requestParameters.get(PlatformSmartmeteringKeys.CONFIGURATION_FLAG_COUNT));
        for (int i = 1; i <= numberOfFlags; i++) {
            configurationFlagList.add(getConfigurationFlag(requestParameters, i));
        }
        configurationFlags.getConfigurationFlag().addAll(configurationFlagList);
        configurationObject.setConfigurationFlags(configurationFlags);
    }

    private static ConfigurationFlag getConfigurationFlag(final Map<String, String> parameters, final int index) {
        final ConfigurationFlag configurationFlag = new ConfigurationFlag();
        configurationFlag.setConfigurationFlagType(getConfigurationFlagType(parameters, index));
        configurationFlag.setEnabled(getConfigurationFlagEnabled(parameters, index));
        return configurationFlag;
    }

    private static ConfigurationFlagType getConfigurationFlagType(final Map<String, String> parameters,
            final int index) {

        final String key = SettingsHelper.makeKey(PlatformSmartmeteringKeys.CONFIGURATION_FLAG_TYPE, index);
        return ReadSettingsHelper.getEnum(parameters, key, ConfigurationFlagType.class);
    }

    private static boolean getConfigurationFlagEnabled(final Map<String, String> parameters, final int index) {
        final String key = SettingsHelper.makeKey(PlatformSmartmeteringKeys.CONFIGURATION_FLAG_ENABLED, index);
        return ReadSettingsHelper.getBoolean(parameters, key);
    }
}


text:
TEABAG_NS

class World;
class Map;

TEABAG_INTERNAL

struct TileInfo {
    std::string name;
    int r, g, b;
};

class TileManager {
private:
    friend class teabag::World;
    friend class teabag::Map;

    TileManager();

    void queueTile(std::string name, int r, int g, int b);
    void loadQueue();
    void loadTile(TileInfo& tile);

    const Tile& tileFromName(std::string name);
    const Tile& tileFromColour(sf::Color colour);

    unsigned int tileWidth();
    unsigned int tileHeight();

    std::vector<TileInfo> tileQueue;

    std::unordered_map<std::string, Tile> tiles;
    std::unordered_map<sf::Color, std::string, std::function<size_t(sf::Color)>> colours;

    unsigned int tileW;
    unsigned int tileH;
};

TEABAG_INTERNAL_END

TEABAG_NS_END

#endif