text:
#ifndef _DDB_DB_COMMAND_H_
#define	_DDB_DB_COMMAND_H_

/*
 *	Author: David B. Golub, Carnegie Mellon University
 *	Date:	7/90
 */

/*
 * Helper functions.
 */
db_expr_t db_hex2dec(db_expr_t expr);

/*
 * Command loop declarations.
 */

void	db_command_init(void);
void	db_command_loop(void);
void	db_command_script(const char *command);

extern db_addr_t	db_dot;		/* current location */
extern db_addr_t	db_last_addr;	/* last explicit address typed */
extern db_addr_t	db_prev;	/* last address examined
					   or written */
extern db_addr_t	db_next;	/* next address to be examined
					   or written */

#endif /* !_DDB_DB_COMMAND_H_ */


text:
module GHCJS.DOM.TextMetrics (
  ) where

redpajama_set_name: RedPajamaGithub


text:
(function() {

var slideSpeed = 20;
var slideInterval = 0;

var currentPage = null;
var currentDialog = null;
var currentWidth = 0;
var currentHash = location.hash;
var hashPrefix = "#_";
var pageHistory = [];
var newPageCount = 0;
var checkTimer;
var hasOrientationEvent = false;
var portraitVal = "portrait";
var landscapeVal = "landscape";

// *************************************************************************************************

window.iui =
{
	animOn: false,	// Experimental slide animation with CSS transition disabled by default

	showPage: function(page, backwards)
	{
		if (page)
		{
			if (currentDialog)
			{
				currentDialog.removeAttribute("selected");
				currentDialog = null;
			}

			if (hasClass(page, "dialog"))
				showDialog(page);
			else
			{
				var fromPage = currentPage;
				currentPage = page;

				if (fromPage)
					setTimeout(slidePages, 0, fromPage, page, backwards);
				else
					updatePage(page, fromPage);
			}
		}
	},

	showPageById: function(pageId)
	{
		var page = $(pageId);
		if (page)
		{
			var index = pageHistory.indexOf(pageId);
			var backwards = index != -1;
			if (backwards)
				pageHistory.splice(index, pageHistory.length);

			iui.showPage(page, backwards);
		}
	},

	showPageByHref: function(href, args, method, replace, cb)
	{
		var req = new XMLHttpRequest();
		req.onerror = function()
		{
			if (cb)
				cb(false);
		};

		req.onreadystatechange = function()
		{
			if (req.readyState == 4)
			{
				if (replace)
					replaceElementWithSource(replace, req.responseText);
				else
				{
					var frag = document.createElement("div");
					frag.innerHTML = req.responseText;
					iui.insertPages(frag.childNodes);
				}
				if (cb)
					setTimeout(cb, 1000, true);
			}
		};

		if (args)
		{
			req.open(method || "GET", href, true);
			req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			req.setRequestHeader("Content-Length", args.length);
			req.send(args.join("&"));
		}
		else
		{
			req.open(method || "GET", href, true);
			req.send(null);
		}
	},

	insertPages: function(nodes)
	{
		var targetPage;
		for (var i = 0; i < nodes.length; ++i)
		{
			var child = nodes[i];
			if (child.nodeType == 1)
			{
				if (!child.id)
					child.id = "__" + (++newPageCount) + "__";

				var clone = $(child.id);
				if (clone)
					clone.parentNode.replaceChild(child, clone);
				else
					document.body.appendChild(child);

				if (child.getAttribute("selected") == "true" || !targetPage)
					targetPage = child;

				--i;
			}
		}

		if (targetPage)
			iui.showPage(targetPage);
	},

	getSelectedPage: function()
	{
		for (var child = document.body.firstChild; child; child = child.nextSibling)
		{
			if (child.nodeType == 1 && child.getAttribute("selected") == "true")
				return child;
		}
	},
	isNativeUrl: function(href)
	{
		for(var i = 0; i < iui.nativeUrlPatterns.length; i++)
		{
			if(href.match(iui.nativeUrlPatterns[i])) return true;
		}
		return false;
	},
	nativeUrlPatterns: [
		new RegExp("^http:\/\/maps.google.com\/maps\?"),
		new RegExp("^mailto:"),
		new RegExp("^tel:"),
		new RegExp("^http:\/\/www.youtube.com\/watch\\?v="),
		new RegExp("^http:\/\/www.youtube.com\/v\/"),
		new RegExp("^javascript:"),

	]
};

// *************************************************************************************************

addEventListener("load", function(event)
{
	var page = iui.getSelectedPage();
	var locPage = getPageFromLoc();

	if (page)
			iui.showPage(page);

	if (locPage && (locPage != page))
		iui.showPage(locPage);

	setTimeout(preloadImages, 0);
	if (typeof window.onorientationchange == "object")
	{
		window.onorientationchange=orientChangeHandler;
		hasOrientationEvent = true;
		setTimeout(orientChangeHandler, 0);
	}
	setTimeout(checkOrientAndLocation, 0);
	checkTimer = setInterval(checkOrientAndLocation, 300);
}, false);

addEventListener("unload", function(event)
{
	return;
}, false);

addEventListener("click", function(event)
{
	var link = findParent(event.target, "a");
	if (link)
	{
		function unselect() { link.removeAttribute("selected"); }

		if (link.href && link.hash && link.hash != "#" && !link.target)
		{
			link.setAttribute("selected", "true");
			iui.showPage($(link.hash.substr(1)));
			setTimeout(unselect, 500);
		}
		else if (link == $("backButton"))
			history.back();
		else if (link.getAttribute("type") == "submit")
			submitForm(findParent(link, "form"));
		else if (link.getAttribute("type") == "cancel")
			cancelDialog(findParent(link, "form"));
		else if (link.target == "_replace")
		{
			link.setAttribute("selected", "progress");
			iui.showPageByHref(link.href, null, null, link, unselect);
		}
		else if (iui.isNativeUrl(link.href))
		{
			return;
		}
		else if (link.target == "_webapp")
		{
			location.href = link.href;
		}
		else if (!link.target)
		{
			link.setAttribute("selected", "progress");
			iui.showPageByHref(link.href, null, null, null, unselect);
		}
		else
			return;

		event.preventDefault();
	}
}, true);

addEventListener("click", function(event)
{
	var div = findParent(event.target, "div");
	if (div && hasClass(div, "toggle"))
	{
		div.setAttribute("toggled", div.getAttribute("toggled") != "true");
		event.preventDefault();
	}
}, true);

function getPageFromLoc()
{
	var page;
	var result = location.hash.match(/#_([^\?_]+)/);
	if (result)
		page = result[1];
	if (page)
		page = $(page);
	return page;
}

function orientChangeHandler()
{
	var orientation=window.orientation;
	switch(orientation)
	{
	case 0:
		setOrientation(portraitVal);
		break;

	case 90:
	case -90:
		setOrientation(landscapeVal);
		break;
	}
}

function checkOrientAndLocation()
{
	if (!hasOrientationEvent)
	{
	  if (window.innerWidth != currentWidth)
	  {
		  currentWidth = window.innerWidth;
		  var orient = currentWidth == 320 ? portraitVal : landscapeVal;
		  setOrientation(orient);
	  }
	}

	if (location.hash != currentHash)
	{
		var pageId = location.hash.substr(hashPrefix.length);
		iui.showPageById(pageId);
	}
}

function setOrientation(orient)
{
	document.body.setAttribute("orient", orient);
	setTimeout(scrollTo, 100, 0, 1);
}

function showDialog(page)
{
	currentDialog = page;
	page.setAttribute("selected", "true");

	if (hasClass(page, "dialog") && !page.target)
		showForm(page);
}

function showForm(form)
{
	form.onsubmit = function(event)
	{
		event.preventDefault();
		submitForm(form);
	};

	form.onclick = function(event)
	{
		if (event.target == form && hasClass(form, "dialog"))
			cancelDialog(form);
	};
}

function cancelDialog(form)
{
	form.removeAttribute("selected");
}

function updatePage(page, fromPage)
{
	if (!page.id)
		page.id = "__" + (++newPageCount) + "__";

	location.hash = currentHash = hashPrefix + page.id;
	pageHistory.push(page.id);

	var pageTitle = $("pageTitle");
	if (page.title)
		pageTitle.innerHTML = page.title;

	if (page.localName.toLowerCase() == "form" && !page.target)
		showForm(page);

	var backButton = $("backButton");
	if (backButton)
	{
		var prevPage = $(pageHistory[pageHistory.length-2]);
		if (prevPage && !page.getAttribute("hideBackButton"))
		{
			backButton.style.display = "inline";
			backButton.innerHTML = prevPage.title ? prevPage.title : "Back";
		}
		else
			backButton.style.display = "none";
	}
}

function slidePages(fromPage, toPage, backwards)
{
	var axis = (backwards ? fromPage : toPage).getAttribute("axis");

	clearInterval(checkTimer);

	if (canDoSlideAnim() && axis != 'y')
	{
	  slide2(fromPage, toPage, backwards, slideDone);
	}
	else
	{
	  slide1(fromPage, toPage, backwards, axis, slideDone);
	}

	function slideDone()
	{
	  if (!hasClass(toPage, "dialog"))
		  fromPage.removeAttribute("selected");
	  checkTimer = setInterval(checkOrientAndLocation, 300);
	  setTimeout(updatePage, 0, toPage, fromPage);
	  fromPage.removeEventListener('webkitTransitionEnd', slideDone, false);
	}
}

function canDoSlideAnim()
{
  return (iui.animOn) && (typeof WebKitCSSMatrix == "object");
}

function slide1(fromPage, toPage, backwards, axis, cb)
{
	if (axis == "y")
		(backwards ? fromPage : toPage).style.top = "100%";
	else
		toPage.style.left = "100%";

	scrollTo(0, 1);
	toPage.setAttribute("selected", "true");
	var percent = 100;
	slide();
	var timer = setInterval(slide, slideInterval);

	function slide()
	{
		percent -= slideSpeed;
		if (percent <= 0)
		{
			percent = 0;
			clearInterval(timer);
			cb();
		}

		if (axis == "y")
		{
			backwards
				? fromPage.style.top = (100-percent) + "%"
				: toPage.style.top = percent + "%";
		}
		else
		{
			fromPage.style.left = (backwards ? (100-percent) : (percent-100)) + "%";
			toPage.style.left = (backwards ? -percent : percent) + "%";
		}
	}
}

function slide2(fromPage, toPage, backwards, cb)
{
	toPage.style.webkitTransitionDuration = '0ms'; // Turn off transitions to set toPage start offset
	// fromStart is always 0% and toEnd is always 0%
	// iPhone won't take % width on toPage
	var toStart = 'translateX(' + (backwards ? '-' : '') + window.innerWidth +	'px)';
	var fromEnd = 'translateX(' + (backwards ? '100%' : '-100%') + ')';
	toPage.style.webkitTransform = toStart;
	toPage.setAttribute("selected", "true");
	toPage.style.webkitTransitionDuration = '';	  // Turn transitions back on
	function startTrans()
	{
		fromPage.style.webkitTransform = fromEnd;
		toPage.style.webkitTransform = 'translateX(0%)'; //toEnd
	}
	fromPage.addEventListener('webkitTransitionEnd', cb, false);
	setTimeout(startTrans, 0);
}

function preloadImages()
{
	var preloader = document.createElement("div");
	preloader.id = "preloader";
	document.body.appendChild(preloader);
}

function submitForm(form)
{
	iui.showPageByHref(form.action || "POST", encodeForm(form), form.method);
}

function encodeForm(form)
{
	function encode(inputs)
	{
		for (var i = 0; i < inputs.length; ++i)
		{
			if (inputs[i].name)
				args.push(inputs[i].name + "=" + escape(inputs[i].value));
		}
	}

	var args = [];
	encode(form.getElementsByTagName("input"));
	encode(form.getElementsByTagName("textarea"));
	encode(form.getElementsByTagName("select"));
	return args;
}

function findParent(node, localName)
{
	while (node && (node.nodeType != 1 || node.localName.toLowerCase() != localName))
		node = node.parentNode;
	return node;
}

function hasClass(self, name)
{
	var re = new RegExp("(^|\\s)"+name+"($|\\s)");
	return re.exec(self.getAttribute("class")) != null;
}

function replaceElementWithSource(replace, source)
{
	var page = replace.parentNode;
	var parent = replace;
	while (page.parentNode != document.body)
	{
		page = page.parentNode;
		parent = parent.parentNode;
	}

	var frag = document.createElement(parent.localName);
	frag.innerHTML = source;

	page.removeChild(parent);

	while (frag.firstChild)
		page.appendChild(frag.firstChild);
}

function $(id) { return document.getElementById(id); }
function ddd() { console.log.apply(console, arguments); }

})();


text:
package com.spotify.helios.rollingupdate;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.spotify.helios.common.descriptors.DeploymentGroup;
import com.spotify.helios.common.descriptors.RolloutTask;
import java.util.List;

public class RollingUndeployPlanner implements RolloutPlanner {

  private final DeploymentGroup deploymentGroup;

  private RollingUndeployPlanner(final DeploymentGroup deploymentGroup) {
    this.deploymentGroup = checkNotNull(deploymentGroup, "deploymentGroup");
  }

  public static RollingUndeployPlanner of(final DeploymentGroup deploymentGroup) {
    return new RollingUndeployPlanner(deploymentGroup);
  }

  @Override
  public List<RolloutTask> plan(final List<String> hosts) {
    // generate the rollout tasks
    final List<RolloutTask> rolloutTasks = Lists.newArrayList();
    final int parallelism = deploymentGroup.getRolloutOptions() != null
                            ? deploymentGroup.getRolloutOptions().getParallelism() : 1;

    Lists.partition(hosts, parallelism)
        .forEach(partition -> rolloutTasks.addAll(rolloutTasks(partition)));

    return ImmutableList.copyOf(rolloutTasks);
  }

  private List<RolloutTask> rolloutTasks(final List<String> hosts) {
    final ImmutableList.Builder<RolloutTask> tasks = ImmutableList.builder();
    hosts.forEach(host -> {
      tasks.add(RolloutTask.of(RolloutTask.Action.FORCE_UNDEPLOY_JOBS, host));
    });
    hosts.forEach(host -> {
      tasks.add(RolloutTask.of(RolloutTask.Action.AWAIT_UNDEPLOYED, host));
      tasks.add(RolloutTask.of(RolloutTask.Action.MARK_UNDEPLOYED, host));
    });
    return tasks.build();
  }
}


text:
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *l, TreeNode *r) : val(x), left(l), right(r) {}
};

int tree_height(TreeNode *root);

string tree_serialize(TreeNode *root);

void tree_free(TreeNode *root);

#endif // TREE_NODE_HPP_


text:
import csv
import os
import random

NOT_AVAILABLE_STRING = 'not available'

class MediaTestMatrix:
  """This class reads video test matrix file and stores them.

  Video test matrix contains different video titles as column and different
  video codec (such as "webm" as columns. The matrix entry contains video
  specification such as "320x240 50 fps VP8 / no audio 1 MBit/s PSNR 36.70"
  or "not available". It also provides methods to generate information based
  on the client's needs. For example, "video" tag or "audio" tag is returned
  based on what kinds of media it is. This matrix is for managing different
  kinds of media files in media testing.

  TODO(imasaki@chromium.org): remove the code duplication in Generate methods.
  """
  # Video extensions such as "webm".
  _exts = []
  # Video specification dictionary of list of video descriptions
  # (the key is video title).
  _specs = {}
  # Video titles such as "bear".
  _video_titles = []
  # Tag dictionary (the key is extension).
  _tags = {}

  def ReadData(self, csv_file):
    """Reads CSV file and stores in list specs and extensions.

    CSV file should have the following format:
    "ext","tag","title1","title2",....
    "0.webm", "video","description1","descrption2", "not available"
    (when it is not available).

    Args:
      csv_file : CSV file name contains video matrix information described
                 above.

    Raises:
      csv.Error if the number of columns is not the same as the number of
        tiles.
    """
    # Clean up all data.
    self._exts = []
    self._specs = {}
    self._video_titles = []
    self._tags = {}
    file = open(csv_file, 'rb')
    reader = csv.reader(file)
    for counter, row in enumerate(reader):
      if counter == 0:
        # First row is comment. So, skip it.
        pass
      elif counter == 1:
        # Second row is for header (video titles).
        for title in row[1:]:
          self._video_titles.append(title)
          self._specs[title] = []
      else:
        # Error checking is done here based on the number of titles
        if len(self._video_titles) != len(row) - 1:
          print "Row %d should have %d columns but has %d columns" % (counter,
            len(self._video_titles), len(row))
          raise csv.Error
        # First column should contain extension.
        self._exts.append(row[0])
        # Second column should contain tag (audio or video).
        self._tags[row[0]] = row[1]
        for i in range(len(row) - 2):
          self._specs[self._video_titles[i]].append(row[i + 2])
    file.close()

  def _GenerateMediaInfo(self, sub_type, name, media_test_matrix_home_url):
    """Generate media information from matrix generated by CSV file.

    Args:
      sub_type: index of the extensions (rows in the CSV file).
      name: the name of the video file (column name in the CSV file).
      media_test_matrix_home_url: url of the matrix home that used
        to generate link.

    Returns:
      a tuple of (info, url, link, tag, is_video, nickname).
        info: description of the video (an entry in the matrix).
        url: URL of the video or audio.
        link: href tag for video or audio.
        tag: a tag string can be used to display video or audio.
        is_video: True if the file is video; False otherwise.
        nickname: nickname of the video for presentation.
    """
    if name is 'none':
      return
    cur_video = name
    is_video = self._tags[self._exts[sub_type]] == 'video'
    file = os.path.join(cur_video, cur_video + self._exts[sub_type])
    # Specs were generated from CSV file in readFile().
    info = self._specs[cur_video][sub_type]
    url = media_test_matrix_home_url + file
    link = '%s  %s' % (url, file, info)
    type = ['audio', 'video'][is_video]
    tag_attr = 'id="v" controls autoplay playbackRate=1 loop valign=top'
    tag = '<%s %s src="%s">' % (type, tag_attr, file)
    nickname = cur_video + self._exts[sub_type]
    return (info, url, link, tag, is_video, nickname)

  def GenerateRandomMediaInfo(self, number_of_tries=10,
                              video_matrix_home_url=''):
    """Generate random video info that can be used for playing this media.

    Args:
      video_only: True if generate random video only.
      video_matrix_home_url: url of the matrix home that is used
        to generate link.

    Returns:
      a list of a tuples (info, url, link, tag, is_video, nickname).
        info: description of the video (an entry in the matrix).
        url: URL of the video/audio.
        link: href tag for video or audio.
        tag: a tag string can be used to display video or audio.
        is_video: True if the file is video; False otherwise.
        nickname: nickname of the video for presentation.
    """
    # Try number_of_tries times to find available video/audio.
    for i in range(number_of_tries):
      sub_type = random.randint(0, len(self._exts))
      name = self._video_titles[random.randint(0, len(self._video_titles)-1)]
      (info, url, link, tag, is_video, nickname) = (
          self._GenerateMediaInfo(sub_type, name, video_matrix_home_url))
      if NOT_AVAILABLE_STRING not in info:
        return (info, url, link, tag, is_video, nickname)
    # Gives up after that (very small chance).
    return None

  def GenerateAllMediaInfos(self, video_only, media_matrix_home_url=''):
    """Generate all video infos that can be used for playing this media.

    Args:
      video_only: True if generate random video only (not audio).
      media_matrix_home_url: url of the matrix home that is used
        to generate link.
    Returns:
      a list of a tuples (info, url, link, tag, is_video, nickname).
        info: description of the video (an entry in the matrix).
        url: URL of the video/audio.
        link: href tag for video or audio.
        tag: a tag string can be used to display video or audio.
        is_video: True if the file is video; False otherwise.
        nickname: nickname of the video for presentation (such as bear.webm).
    """
    media_infos = []

    for i in range(0, len(self._video_titles)-1):
      name = self._video_titles[i]
      for sub_type in range(len(self._exts)):
        (info, url, link, tag, is_video, nickname) = (
            self._GenerateMediaInfo(sub_type, name, media_matrix_home_url))
        if ((NOT_AVAILABLE_STRING not in info) and
            ((not video_only) or (video_only and is_video))):
          media_infos.append([info, url, link, tag, is_video, nickname])
    return media_infos

  def GenerateAllMediaInfosInCompactForm(self, video_only,
                                         media_matrix_home_url=''):
    """Generate all media information in compact form.

    Compact form contains only url, nickname and tag.

    Args:
      video_only: True if generate random video only.
      media_matrix_home_url: url of the matrix home that is used
        to generate link.

    Returns:
      a list of a tuples (url, nickname, tag).
        url: URL of the video/audio.
        nickname: nickname of the video/audio for presentation
                  (such as bear.webm).
        tag: HTML5 tag for the video/audio.
    """
    media_infos = []
    for i in range(0, len(self._video_titles)-1):
      name = self._video_titles[i]
      for sub_type in range(len(self._exts)):
        (info, url, link, tag, is_video, nickname) = (
            self._GenerateMediaInfo(sub_type, name, media_matrix_home_url))
        tag = ['audio', 'video'][is_video]
        if ((not NOT_AVAILABLE_STRING in info) and
            ((not video_only) or (video_only and is_video))):
          media_infos.append([url, nickname, tag])
    return media_infos

  @staticmethod
  def LookForMediaInfoInCompactFormByNickName(compact_list, target):
    """Look for video by its nickname in the compact_list.

    Args:
      compact_list: a list generated by GenerateAllMediaInfosInCompactForm.
      target: a target nickname string to look for.

    Returns:
      A tuple (url, nickname, tag) where nickname is a target string.
        url: URL of the video/audio.
        nickname: nickname of the video/audio for presentation
                  (such as bear.webm).
        tag: HTML5 tag for the video/audio.
    """
    for url, nickname, tag in compact_list:
      if target == nickname:
        return (tag, url, nickname)


text:
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Injectable, Type } from '@angular/core';

import { CoreConstants, ModPurpose } from '@/core/constants';
import { CoreCourseModuleHandler } from '@features/course/services/module-delegate';
import { AddonModLessonIndexComponent } from '../../components/index';
import { makeSingleton } from '@singletons';
import { CoreModuleHandlerBase } from '@features/course/classes/module-base-handler';

/**
 * Handler to support lesson modules.
 */
@Injectable({ providedIn: 'root' })
export class AddonModLessonModuleHandlerService extends CoreModuleHandlerBase implements CoreCourseModuleHandler {

    static readonly PAGE_NAME = 'mod_lesson';

    name = 'AddonModLesson';
    modName = 'lesson';
    protected pageName = AddonModLessonModuleHandlerService.PAGE_NAME;

    supportedFeatures = {
        [CoreConstants.FEATURE_GROUPS]: true,
        [CoreConstants.FEATURE_GROUPINGS]: true,
        [CoreConstants.FEATURE_MOD_INTRO]: true,
        [CoreConstants.FEATURE_COMPLETION_TRACKS_VIEWS]: true,
        [CoreConstants.FEATURE_COMPLETION_HAS_RULES]: true,
        [CoreConstants.FEATURE_GRADE_HAS_GRADE]: true,
        [CoreConstants.FEATURE_GRADE_OUTCOMES]: true,
        [CoreConstants.FEATURE_BACKUP_MOODLE2]: true,
        [CoreConstants.FEATURE_SHOW_DESCRIPTION]: true,
        [CoreConstants.FEATURE_MOD_PURPOSE]: ModPurpose.MOD_PURPOSE_CONTENT,
    };

    /**
     * @inheritdoc
     */
    async getMainComponent(): Promise<Type<unknown>> {
        return AddonModLessonIndexComponent;
    }

}

export const AddonModLessonModuleHandler = makeSingleton(AddonModLessonModuleHandlerService);


text:
<?php

return array(
    // 'By @%s on GitLab' => '',
    // 'GitLab issue comment created' => '',
    // 'GitLab issue reopened' => '',
    'GitLab commit received' => 'Commit ricevuto da GitLab',
    'GitLab issue opened' => 'Issue di GitLab aperta',
    'GitLab issue closed' => 'Issue di GitLab chiusa',
    'GitLab webhooks' => 'Webhooks di GitLab',
    'Help on GitLab webhooks' => 'Guida ai Webhooks di GitLab',
);


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

namespace Exercise
{
    public class ListIterator
    {
        private IList<string> collection;
        private int index;

        public ListIterator(ICollection<string> collection)
        {
            this.Collection = collection.ToList();
            this.index = 0;
        }

        private IList<string> Collection
        {
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException();
                }
                this.collection = value;
            }
        }

        public bool Move()
        {
            if (this.index + 1 >= this.collection.Count)
            {
                return false;
            }
            this.index++;

            return true;
        }

        public bool HasNext()
        {
            if (this.index + 1 >= this.collection.Count)
            {
                return false;
            }
            return true;
        }

        public string Print()
        {
            if (!this.collection.Any())
            {
                throw new InvalidOperationException("Invalid Operation!");
            }
            return this.collection[this.index];
        }
    }
}


text:
var autoUpdatedAt= require('../utils/autoUpdatedAt');

//dbCore
var update= require('../core/update');
var updateEmbeded= require('../core/updateEmbeded');
//Projection utility
var projectionUtil= require('../utils/projectionUtil');

module.exports= function (input) {
	var model= input.model;
	model.updateMany= function (selector,obj) {
		delete obj._id;

		if(!model.schema.hasOwnProperty('embeded'))
		{
			return input.validate(model.schema,obj)
			.then(autoUpdatedAt(model))
			.then(function (obj) {
				return update(model.modelName,selector,obj,projectionUtil(model,{}));
			});
		}
		else
		{
			return input.validate(model.schema,obj)
			.then(autoUpdatedAt(model))
			.then(function (obj) {
				return updateEmbeded(model.modelName,selector,obj,model.schema.embeded,projectionUtil(model,{}));
			});
		}
	};

	return input;
}


text:
import os
import sys
from django.conf import settings

setting_overrides = getattr(settings, 'DJANGO_NODE', {})

NODE_VERSION_REQUIRED = setting_overrides.get(
    'NODE_VERSION_REQUIRED',
    (0, 10, 25)
)

NPM_VERSION_REQUIRED = setting_overrides.get(
    'NPM_VERSION_REQUIRED',
    (2, 0, 0)
)

PATH_TO_NODE = setting_overrides.get(
    'PATH_TO_NODE',
    'node'
)

NODE_VERSION_COMMAND = setting_overrides.get(
    'NODE_VERSION_COMMAND',
    '--version',
)

NODE_VERSION_FILTER = setting_overrides.get(
    'NODE_VERSION_FILTER',
    lambda version: tuple(map(int, (version[1:] if version[0] == 'v' else version).split('.'))),
)

PATH_TO_NPM = setting_overrides.get(
    'PATH_TO_NPM',
    'npm'
)

NPM_VERSION_COMMAND = setting_overrides.get(
    'NPM_VERSION_COMMAND',
    '--version',
)

NPM_VERSION_FILTER = setting_overrides.get(
    'NPM_VERSION_FILTER',
    lambda version: tuple(map(int, version.split('.'))),
)

NPM_INSTALL_COMMAND = setting_overrides.get(
    'NPM_INSTALL_COMMAND',
    'install',
)

NPM_INSTALL_PATH_TO_PYTHON = setting_overrides.get(
    'NPM_INSTALL_PATH_TO_PYTHON',
    None,
)

SERVER = setting_overrides.get(
    'SERVER',
    'django_node.node_server.NodeServer',
)

SERVER_PROTOCOL = setting_overrides.get(
    'SERVER_PROTOCOL',
    'http',
)

SERVER_ADDRESS = setting_overrides.get(
    'SERVER_ADDRESS',
    '127.0.0.1',
)

# Read in the server port from a `DJANGO_NODE_SERVER_PORT` environment variable
SERVER_PORT = os.environ.get('DJANGO_NODE_SERVER_PORT', None)
if SERVER_PORT is None:
    SERVER_PORT = setting_overrides.get(
        'SERVER_PORT',
        '63578',
    )

SERVICES = setting_overrides.get(
    'SERVICES',
    (),
)

SERVICE_TIMEOUT = setting_overrides.get(
    'SERVICE_TIMEOUT',
    10.0,
)

SERVER_TEST_TIMEOUT = setting_overrides.get(
    'SERVER_TEST_TIMEOUT',
    2.0,
)

PACKAGE_DEPENDENCIES = setting_overrides.get(
    'PACKAGE_DEPENDENCIES',
    ()
)

INSTALL_PACKAGE_DEPENDENCIES_DURING_RUNTIME = setting_overrides.get(
    'INSTALL_PACKAGE_DEPENDENCIES_DURING_RUNTIME',
    True,
)

if INSTALL_PACKAGE_DEPENDENCIES_DURING_RUNTIME:
    # Prevent dependencies from being installed during init if
    # either of the package dependency commands are being run
    for i, arg in enumerate(sys.argv):
        if (
            arg.endswith('manage.py') and
            'uninstall_package_dependencies' in sys.argv or
            'install_package_dependencies' in sys.argv
        ):
            INSTALL_PACKAGE_DEPENDENCIES_DURING_RUNTIME = False
            break


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.contracts.productadmin;

import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;

/**
 *	Properties of the publishing status of the product, including its current state and the details of the last product change published to the catalog.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class ProductPublishingInfo implements Serializable
{
	// Default Serial Version UID
	private static final long serialVersionUID = 1L;

	/**
	 * The user ID of the user who last published changes for this product in the catalog.
	 */
	protected String lastPublishedBy;

	public String getLastPublishedBy() {
		return this.lastPublishedBy;
	}

	public void setLastPublishedBy(String lastPublishedBy) {
		this.lastPublishedBy = lastPublishedBy;
	}

	/**
	 * The date and time a draft change for this product was published to the catalog.
	 */
	protected DateTime lastPublishedDate;

	public DateTime getLastPublishedDate() {
		return this.lastPublishedDate;
	}

	public void setLastPublishedDate(DateTime lastPublishedDate) {
		this.lastPublishedDate = lastPublishedDate;
	}

	/**
	 * The current publishing state of this product in the catalog, which is Live, New, or Draft. Live products appear on the storefront and have no pending changes. New products have been created but do not yet appear on the storefront. Draft products appear on the storefront but have pending changes that have not yet been published.
	 */
	protected String publishedState;

	public String getPublishedState() {
		return this.publishedState;
	}

	public void setPublishedState(String publishedState) {
		this.publishedState = publishedState;
	}

	protected String publishSetCode;

	public String getPublishSetCode() {
		return this.publishSetCode;
	}

	public void setPublishSetCode(String publishSetCode) {
		this.publishSetCode = publishSetCode;
	}

}


text:
package com.bitfire.postprocessing;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.bitfire.postprocessing.utils.PingPongBuffer;
import com.bitfire.utils.ItemsManager;

/** Provides a way to capture the rendered scene to an off-screen buffer and to apply a chain of effects on it before rendering to
 * screen.
 *
 * Effects can be added or removed via {@link #addEffect(PostProcessorEffect)} and {@link #removeEffect(PostProcessorEffect)}.
 *
 * @author bmanuel */
public final class PostProcessor implements Disposable {
	/** Enable pipeline state queries: beware the pipeline can stall! */
	public static boolean EnableQueryStates = false;

	private static PipelineState pipelineState = null;
	private static Format fbFormat;
	private final PingPongBuffer composite;
	private TextureWrap compositeWrapU;
	private TextureWrap compositeWrapV;
	private final ItemsManager<PostProcessorEffect> effectsManager = new ItemsManager<PostProcessorEffect>();
	private static final Array<PingPongBuffer> buffers = new Array<PingPongBuffer>(5);
	private final Color clearColor = Color.CLEAR;
	private int clearBits = GL20.GL_COLOR_BUFFER_BIT;
	private float clearDepth = 1f;
	private static Rectangle viewport = new Rectangle();
	private static boolean hasViewport = false;

	private boolean enabled = true;
	private boolean capturing = false;
	private boolean hasCaptured = false;
	private boolean useDepth = false;

	private PostProcessorListener listener = null;

	// maintains a per-frame updated list of enabled effects
	private Array<PostProcessorEffect> enabledEffects = new Array<PostProcessorEffect>(5);

	/** Construct a new PostProcessor with FBO dimensions set to the size of the screen */
	public PostProcessor (boolean useDepth, boolean useAlphaChannel, boolean use32Bits) {
		this(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), useDepth, useAlphaChannel, use32Bits);
	}

	/** Construct a new PostProcessor with the given parameters, defaulting to TextureWrap.ClampToEdge as texture wrap mode */
	public PostProcessor (int fboWidth, int fboHeight, boolean useDepth, boolean useAlphaChannel, boolean use32Bits) {
		this(fboWidth, fboHeight, useDepth, useAlphaChannel, use32Bits, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge);
	}

	/** Construct a new PostProcessor with the given parameters and viewport, defaulting to TextureWrap.ClampToEdge as
	 * texture wrap mode */
	public PostProcessor (Rectangle viewport, boolean useDepth, boolean useAlphaChannel, boolean use32Bits) {
		this((int)viewport.width, (int)viewport.height, useDepth, useAlphaChannel, use32Bits, TextureWrap.ClampToEdge,
			TextureWrap.ClampToEdge);
		setViewport(viewport);
	}

	/** Construct a new PostProcessor with the given parameters, viewport and the specified texture wrap mode */
	public PostProcessor (Rectangle viewport, boolean useDepth, boolean useAlphaChannel, boolean use32Bits, TextureWrap u,
		TextureWrap v) {
		this((int)viewport.width, (int)viewport.height, useDepth, useAlphaChannel, use32Bits, u, v);
		setViewport(viewport);
	}

	/** Construct a new PostProcessor with the given parameters and the specified texture wrap mode */
	public PostProcessor (int fboWidth, int fboHeight, boolean useDepth, boolean useAlphaChannel, boolean use32Bits,
		TextureWrap u, TextureWrap v) {
		if (use32Bits) {
			if (useAlphaChannel) {
				fbFormat = Format.RGBA8888;
			} else {
				fbFormat = Format.RGB888;
			}
		} else {
			if (useAlphaChannel) {
				fbFormat = Format.RGBA4444;
			} else {
				fbFormat = Format.RGB565;
			}
		}

		composite = newPingPongBuffer(fboWidth, fboHeight, fbFormat, useDepth);
		setBufferTextureWrap(u, v);

		pipelineState = new PipelineState();

		capturing = false;
		hasCaptured = false;
		enabled = true;
		this.useDepth = useDepth;
		if (useDepth) {
			clearBits |= GL20.GL_DEPTH_BUFFER_BIT;
		}

		setViewport(null);
	}

	/** Creates and returns a managed PingPongBuffer buffer, just create and forget. If rebind() is called on context loss, managed
	 * PingPongBuffers will be rebound for you.
	 *
	 * This is a drop-in replacement for the same-signature PingPongBuffer's constructor. */
	public static PingPongBuffer newPingPongBuffer (int width, int height, Format frameBufferFormat, boolean hasDepth) {
		PingPongBuffer buffer = new PingPongBuffer(width, height, frameBufferFormat, hasDepth);
		buffers.add(buffer);
		return buffer;
	}

	/** Provides a way to query the pipeline for the most used states */
	public static boolean isStateEnabled (int pname) {
		if (EnableQueryStates) {
			// Gdx.app.log( "PipelineState", "Querying blending" );
			return pipelineState.isEnabled(pname);
		}

		// Gdx.app.log( "PipelineState", "(not querying)" );
		return false;
	}

	/** Sets the viewport to be restored, if null is specified then the viewport will NOT be restored at all.
	 *
	 * The predefined effects will restore the viewport settings at the final blitting stage (render to screen) by invoking the
	 * restoreViewport static method. */
	public void setViewport (Rectangle viewport) {
		PostProcessor.hasViewport = (viewport != null);
		if (hasViewport) {
			PostProcessor.viewport.set(viewport);
		}
	}

	/** Frees owned resources. */
	@Override
	public void dispose () {
		effectsManager.dispose();

		// cleanup managed buffers, if any
		for (int i = 0; i < buffers.size; i++) {
			buffers.get(i).dispose();
		}

		buffers.clear();

		if (enabledEffects != null) {
			enabledEffects.clear();
		}

		pipelineState.dispose();
	}

	/** Whether or not the post-processor is enabled */
	public boolean isEnabled () {
		return enabled;
	}

	/** If called before capturing it will indicate if the next capture call will succeeds or not. */
	public boolean isReady () {
		boolean hasEffects = false;

		for (PostProcessorEffect e : effectsManager) {
			if (e.isEnabled()) {
				hasEffects = true;
				break;
			}
		}

		return (enabled && !capturing && hasEffects);
	}

	/** Sets whether or not the post-processor should be enabled */
	public void setEnabled (boolean enabled) {
		this.enabled = enabled;
	}

	/** Returns the number of the currently enabled effects */
	public int getEnabledEffectsCount () {
		return enabledEffects.size;
	}

	/** Sets the listener that will receive events triggered by the PostProcessor rendering pipeline. */
	public void setListener (PostProcessorListener listener) {
		this.listener = listener;
	}

	/** Adds the specified effect to the effect chain and transfer ownership to the PostProcessor, it will manage cleaning it up for
	 * you. The order of the inserted effects IS important, since effects will be applied in a FIFO fashion, the first added is the
	 * first being applied. */
	public void addEffect (PostProcessorEffect effect) {
		effectsManager.add(effect);
	}

	/** Removes the specified effect from the effect chain. */
	public void removeEffect (PostProcessorEffect effect) {
		effectsManager.remove(effect);
	}

	/** Returns the internal framebuffer format, computed from the parameters specified during construction. NOTE: the returned
	 * Format will be valid after construction and NOT early! */
	public static Format getFramebufferFormat () {
		return fbFormat;
	}

	/** Sets the color that will be used to clear the buffer. */
	public void setClearColor (Color color) {
		clearColor.set(color);
	}

	/** Sets the color that will be used to clear the buffer. */
	public void setClearColor (float r, float g, float b, float a) {
		clearColor.set(r, g, b, a);
	}

	/** Sets the clear bit for when glClear is invoked. */
	public void setClearBits (int bits) {
		clearBits = bits;
	}

	/** Sets the depth value with which to clear the depth buffer when needed. */
	public void setClearDepth (float depth) {
		clearDepth = depth;
	}

	public void setBufferTextureWrap (TextureWrap u, TextureWrap v) {
		compositeWrapU = u;
		compositeWrapV = v;

		composite.texture1.setWrap(compositeWrapU, compositeWrapV);
		composite.texture2.setWrap(compositeWrapU, compositeWrapV);
	}

	/** Starts capturing the scene, clears the buffer with the clear color specified by {@link #setClearColor(Color)} or
	 * {@link #setClearColor(float r, float g, float b, float a)}.
	 *
	 * @return true or false, whether or not capturing has been initiated. Capturing will fail in case there are no enabled effects
	 *         in the chain or this instance is not enabled or capturing is already started. */
	public boolean capture () {
		hasCaptured = false;

		if (enabled && !capturing) {
			if (buildEnabledEffectsList() == 0) {
				// no enabled effects
				// Gdx.app.log( "PostProcessor::capture()",
				// "No post-processor effects enabled" );
				return false;
			}

			capturing = true;
			composite.begin();
			composite.capture();

			if (useDepth) {
				Gdx.gl.glClearDepthf(clearDepth);
			}

			Gdx.gl.glClearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a);
			Gdx.gl.glClear(clearBits);
			return true;
		}

		return false;
	}

	/** Starts capturing the scene as {@link #capture()}, but without clearing the screen.
	 *
	 * @return true or false, whether or not capturing has been initiated. */
	public boolean captureNoClear () {
		hasCaptured = false;

		if (enabled && !capturing) {
			if (buildEnabledEffectsList() == 0) {
				// no enabled effects
				// Gdx.app.log( "PostProcessor::captureNoClear",
				// "No post-processor effects enabled" );
				return false;
			}

			capturing = true;
			composite.begin();
			composite.capture();
			return true;
		}

		return false;
	}

	/** Stops capturing the scene and returns the result, or null if nothing was captured. */
	public FrameBuffer captureEnd () {
		if (enabled && capturing) {
			capturing = false;
			hasCaptured = true;
			composite.end();
			return composite.getResultBuffer();
		}

		return null;
	}

	/** After a capture/captureEnd action, returns the just captured buffer */
	public FrameBuffer captured () {
		if (enabled && hasCaptured) {
			return composite.getResultBuffer();
		}

		return null;
	}

	/** Regenerates and/or rebinds owned resources when needed, eg. when the OpenGL context is lost. */
	public void rebind () {
		composite.texture1.setWrap(compositeWrapU, compositeWrapV);
		composite.texture2.setWrap(compositeWrapU, compositeWrapV);

		for (int i = 0; i < buffers.size; i++) {
			buffers.get(i).rebind();
		}

		for (PostProcessorEffect e : effectsManager) {
			e.rebind();
		}
	}

	/** Stops capturing the scene and apply the effect chain, if there is one. If the specified output framebuffer is NULL, then the
	 * rendering will be performed to screen. */
	public void render (FrameBuffer dest) {
		captureEnd();

		if (!hasCaptured) {
			return;
		}

		// Array<PostProcessorEffect> items = manager.items;
		Array<PostProcessorEffect> items = enabledEffects;

		int count = items.size;
		if (count > 0) {

			Gdx.gl.glDisable(GL20.GL_CULL_FACE);
			Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);

			// render effects chain, [0,n-1]
			if (count > 1) {
				for (int i = 0; i < count - 1; i++) {
					PostProcessorEffect e = items.get(i);

					composite.capture();
					{
						e.render(composite.getSourceBuffer(), composite.getResultBuffer());
					}
				}

				// complete
				composite.end();
			}

			if (listener != null && dest == null) {
				listener.beforeRenderToScreen();
			}

			// render with null dest (to screen)
			items.get(count - 1).render(composite.getResultBuffer(), dest);

			// ensure default texture unit #0 is active
			Gdx.gl.glActiveTexture(GL20.GL_TEXTURE0);
		} else {
			Gdx.app.log("PostProcessor", "No post-processor effects enabled, aborting render");
		}
	}

	/** Convenience method to render to screen. */
	public void render () {
		render(null);
	}

	private int buildEnabledEffectsList () {
		enabledEffects.clear();
		for (PostProcessorEffect e : effectsManager) {
			if (e.isEnabled()) {
				enabledEffects.add(e);
			}
		}

		return enabledEffects.size;
	}

	/** Restores the previously set viewport if one was specified earlier and the destination buffer is the screen */
	protected static void restoreViewport (FrameBuffer dest) {
		if (hasViewport && dest == null) {
			Gdx.gl.glViewport((int)viewport.x, (int)viewport.y, (int)viewport.width, (int)viewport.height);
		}
	}

}


text:
layout: page
title: Silicon Card Aerospace Seminar
date: 2016-05-24
author: Edward Miles
tags: weekly links, java
status: published
summary: Donec dapibus sem eget est tincidunt.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 10/25/2019
  endDate: 10/29/2019
  ctyhocn: APFTTHX
  groupCode: SCAS
published: true
---
Ut finibus sollicitudin feugiat. Maecenas iaculis bibendum sapien quis congue. Vivamus vitae ipsum nec mi ultricies lacinia ac nec orci. Mauris venenatis odio in enim vestibulum auctor. Vestibulum fringilla varius justo, quis volutpat justo maximus in. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a bibendum elit, vel mollis mi. Aenean vitae tempor urna. Aenean et tincidunt nisi. Sed pharetra porta enim, quis varius sapien vulputate ut. Sed dapibus est in egestas rhoncus. Pellentesque hendrerit augue eu hendrerit finibus. Proin sed fermentum lorem, nec semper velit. Donec et odio id tellus faucibus maximus. Fusce et nisl sed sem vestibulum fermentum. Maecenas vitae neque ac odio lacinia suscipit id id nisi.
Donec a sapien ultrices, bibendum sem at, luctus augue. Vestibulum sapien velit, euismod ut augue sollicitudin, viverra pellentesque dolor. Quisque laoreet porta ipsum, eu finibus lorem iaculis nec. Nullam aliquam consectetur purus, volutpat ultrices felis euismod sed. Nullam scelerisque tellus ac arcu dignissim, ac lobortis nisi venenatis. Donec fermentum ipsum turpis, sit amet aliquet purus rutrum non. Vivamus tincidunt nulla eu sem venenatis pretium. Proin enim massa, eleifend eu tellus non, molestie semper lorem. Nulla egestas rhoncus lectus et viverra. Quisque dapibus quis sem ut condimentum. Integer nibh nunc, tristique eget pretium id, finibus eu lorem.

1 Pellentesque quis nibh porttitor, posuere mauris sed, pulvinar nisl
1 Donec id nibh eleifend, lobortis tellus sed, fringilla elit
1 Phasellus non nisl congue, commodo eros in, pretium augue
1 Duis convallis neque id lectus luctus efficitur
1 Aenean in est ut mi elementum gravida.

In tristique ante sed maximus vestibulum. Vivamus finibus leo a enim hendrerit tincidunt. Duis magna sapien, placerat ut facilisis tincidunt, dictum vitae metus. Donec vulputate nibh sit amet malesuada gravida. Cras ante dui, congue vitae nulla in, tempor auctor nunc. Donec euismod a nibh sit amet condimentum. Integer lectus odio, semper at mattis in, rutrum id enim. Ut nisl lorem, tincidunt non ante eget, lacinia volutpat arcu.


text:
//==============================================================================
// SUNDIALS plugin
//==============================================================================

#include "sundialsplugin.h"

//==============================================================================

namespace OpenCOR {
namespace SUNDIALS {

//==============================================================================

PLUGININFO_FUNC SUNDIALSPluginInfo()
{
    Descriptions descriptions;

    descriptions.insert("en", QString::fromUtf8("a plugin to access the CVODE, IDA and KINSOL solvers from SUNDIALS 2.6.2."));
    descriptions.insert("fr", QString::fromUtf8("une extension pour accéder les solveurs CVODE, IDA et KINSOL de SUNDIALS 2.6.2."));

    return new PluginInfo("Third-party", false, false,
                          QStringList(),
                          descriptions);
}

//==============================================================================

}   // namespace SUNDIALS
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================


text:
from django.db import models

class Player(models.Model):
    handle = models.CharField(max_length=20)


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\VirtualProperty;

/**
 * PerfilLegislador
 * @ORM\Entity
 */
class PerfilLegislador extends Perfil
{
    //---------------------------------atributos de la clase--------------------------------------

    /**
     * @var \AppBundle\Entity\Bloque
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Bloque", inversedBy="concejales")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="idBloque", referencedColumnName="idBloque")
     * })
     */
    private $bloque;

    /**
     * @var string
     *
     * @ORM\Column(name="oficina", type="string", length=50, nullable=true)
     */
    private $oficina;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="desde", type="datetime", nullable=false)
     */
    private $desde;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="hasta", type="datetime", nullable=false)
     */
    private $hasta;

    //--------------------------------------getters y setters-------------------------------------

    /**
     * Set bloque
     *
     * @param \AppBundle\Entity\Bloque $bloque
     *
     * @return PerfilLegislador
     */
    public function setBloque($bloque)
    {
        $this->bloque = $bloque;

        return $this;
    }

    /**
     * Get bloque
     *
     * @return \AppBundle\Entity\Bloque
     */
    public function getBloque()
    {
        return $this->bloque;
    }

      /**
     * Set oficina
     *
     * @param string $oficina
     *
     * @return PerfilLegislador
     */
    public function setOficina($oficina)
    {
        $this->oficina = $oficina;

        return $this;
    }

    /**
     * Get oficina
     *
     * @return string
     */
    public function getOficina()
    {
        return $this->oficina;
    }

    /**
     * Set desde
     *
     * @param \DateTime $desde
     *
     * @return PerfilLegislador
     */
    public function setDesde($desde)
    {
        $this->desde = $desde;

        return $this;
    }

    /**
     * Get desde
     *
     * @return \DateTime
     */
    public function getDesde()
    {
        return $this->desde;
    }

    /**
     * Set hasta
     *
     * @param \DateTime $hasta
     *
     * @return PerfilLegislador
     */
    public function setHasta($hasta)
    {
        $this->hasta = $hasta;

        return $this;
    }

    /**
     * Get hasta
     *
     * @return \DateTime
     */
    public function getHasta()
    {
        return $this->hasta;
    }

    //-------------------------------propiedades virtuales-----------------------------------------

    /**
     * Get tipoPerfil
     *
     * @return string
     *
     * @VirtualProperty
     */
    public function getTipoPerfil()
    {
        return "legislador";
    }

    /**
     * Get fechaDesdeFormateada
     *
     * @return string
     *
     * @VirtualProperty
     */
    public function getFechaDesdeFormateada()
    {
        return (is_null($this->getDesde())?'':$this->getDesde()->format('d/m/Y'));
    }

    /**
     * Get fechaHastaFormateada
     *
     * @return string
     *
     * @VirtualProperty
     */
    public function getFechaHastaFormateada()
    {
        return (is_null($this->getDesde())?'':$this->getHasta()->format('d/m/Y'));
    }

     /**
     * Get descripcion
     *
     * @return string
     *
     * @VirtualProperty
     */
    public function getDescripcion()
    {
        return parent::getNombreCompleto().' - ('.$this->bloque->getAbreviacion().')';
    }
}


text:
package pl.matisoft.soy.ajax.process;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;

/**
 * Created with IntelliJ IDEA.
 * User: mszczap
 * Date: 16.10.13
 * Time: 18:11
 *
 * An implementation of an output processor that will prependText and appendText something
 * once a compilation of JavaScript completed.
 *
 * A good example for the reason this class may be needed is requirejs, one may prependText
 * a requirejs module definition and appendText closing, such that a JavaScript response can be wrapped.
 *
 * It is up to a frontend developer to work with a backend developer to define what exactly could be in "prependText"
 * and "appendText" configuration.
 */
public class PrependAppendOutputProcessor implements OutputProcessor {

    /** text to prepend before a compiled JavaScript template */
    private String prependText = "";

    /** whether to add a new line in prepend case */
    private boolean prependNewLine = true;

    /** text to append after a compiled JavaScript template */
    private String appendText = "";

    /** whether to add a new line in append case */
    private boolean appendNewLine = true;

    @Override
    public void process(final Reader reader, final Writer writer) throws IOException {
        final StringBuilder builder = new StringBuilder();

        final String content = IOUtils.toString(reader);

        if (!StringUtils.isEmpty(prependText)) {
            builder.append(prependText);
            if (prependNewLine) {
                builder.append("\n");
            }
        }
        builder.append(content);
        if (!StringUtils.isEmpty(appendText)) {
            if (appendNewLine) {
                builder.append("\n");
            }
            builder.append(appendText);
        }

        writer.write(builder.toString());
    }

    public void setPrependText(String prependText) {
        this.prependText = prependText;
    }

    public void setAppendText(String appendText) {
        this.appendText = appendText;
    }

    public void setPrependNewLine(boolean prependNewLine) {
        this.prependNewLine = prependNewLine;
    }

    public void setAppendNewLine(boolean appendNewLine) {
        this.appendNewLine = appendNewLine;
    }

}


text:
"""
tar vcs support.

The implementation uses the "version" argument to indicate a subfolder
within a tarfile.  Hence one can organize sources by creating one
tarfile with a folder inside for each version.
"""

from __future__ import absolute_import, print_function, unicode_literals
import os
import tempfile
import shutil
import tarfile
import sys
import yaml
from vcstools.vcs_base import VcsClientBase, VcsError
from vcstools.common import urlretrieve_netrc, ensure_dir_notexists

__pychecker__ = 'unusednames=spec'

_METADATA_FILENAME = ".tar"

class TarClient(VcsClientBase):

    def __init__(self, path):
        """
        @raise VcsError if tar not detected
        """
        VcsClientBase.__init__(self, 'tar', path)
        self.metadata_path = os.path.join(self._path, _METADATA_FILENAME)

    @staticmethod
    def get_environment_metadata():
        metadict = {}
        metadict["version"] = 'tarfile version: %s' % tarfile.version
        return metadict

    def get_url(self):
        """
        :returns: TAR URL of the directory path (output of tar info
        command), or None if it cannot be determined
        """
        if self.detect_presence():
            with open(self.metadata_path, 'r') as metadata_file:
                metadata = yaml.load(metadata_file.read())
                if 'url' in metadata:
                    return metadata['url']
        return None

    def detect_presence(self):
        return self.path_exists() and os.path.exists(self.metadata_path)

    def checkout(self, url, version='', verbose=False,
                 shallow=False, timeout=None):
        """
        untars tar at url to self.path.
        If version was given, only the subdirectory 'version' of the
        tar will end up in self.path.  Also creates a file next to the
        checkout named *.tar which is a yaml file listing origin url
        and version arguments.
        """
        if not ensure_dir_notexists(self.get_path()):
            self.logger.error("Can't remove %s" % self.get_path())
            return False
        tempdir = None
        result = False
        try:
            tempdir = tempfile.mkdtemp()
            if os.path.isfile(url):
                filename = url
            else:
                (filename, _) = urlretrieve_netrc(url)
                # print "filename", filename
            temp_tarfile = tarfile.open(filename, 'r:*')
            members = None  # means all members in extractall
            if version == '' or version is None:
                self.logger.warn("No tar subdirectory chosen via the 'version' argument for url: %s" % url)
            else:
                # getmembers lists all files contained in tar with
                # relative path
                subdirs = []
                members = []
                for m in temp_tarfile.getmembers():
                    if m.name.startswith(version + '/'):
                        members.append(m)
                    if m.name.split('/')[0] not in subdirs:
                        subdirs.append(m.name.split('/')[0])
                if not members:
                    raise VcsError("%s is not a subdirectory with contents in members %s" % (version, subdirs))
            temp_tarfile.extractall(path=tempdir, members=members)

            subdir = os.path.join(tempdir, version)
            if not os.path.isdir(subdir):
                raise VcsError("%s is not a subdirectory\n" % subdir)

            try:
                # os.makedirs(os.path.dirname(self._path))
                shutil.move(subdir, self._path)
            except Exception as ex:
                raise VcsError("%s failed to move %s to %s" % (ex, subdir, self._path))
            metadata = yaml.dump({'url': url, 'version': version})
            with open(self.metadata_path, 'w') as mdat:
                mdat.write(metadata)
            result = True

        except Exception as exc:
            self.logger.error("Tarball download unpack failed: %s" % str(exc))
        finally:
            if tempdir is not None and os.path.exists(tempdir):
                shutil.rmtree(tempdir)
        return result

    def update(self, version='', verbose=False, timeout=None):
        """
        Does nothing except returning true if tar exists in same
        "version" as checked out with vcstools.
        """
        if not self.detect_presence():
            return False

        if version != self.get_version():
            sys.stderr.write("Tarball Client does not support updating with different version.\n")
            return False

        return True

    def get_version(self, spec=None):

        if self.detect_presence():
            with open(self.metadata_path, 'r') as metadata_file:
                metadata = yaml.load(metadata_file.read())
                if 'version' in metadata:
                    return metadata['version']
        return None

    def get_diff(self, basepath=None):
        return ''

    def get_status(self, basepath=None, untracked=False):
        return ''

    def export_repository(self, version, basepath):
        raise VcsError('export repository not implemented for extracted tars')

# backwards compatibility
TARClient = TarClient


text:
package org.gearvrf;

import android.view.View;

import org.gearvrf.scene_objects.GVRViewSceneObject;

/**
 * This interface defines the callback interface of an Android {@code View}
 * that is inflated by a {@link GVRViewSceneObject}.
 */
public interface IViewEvents extends IEvents {
    void onInitView(GVRViewSceneObject sceneObject, View view);
    void onStartDraw(GVRViewSceneObject sceneObject, View view);
}


text:
package com.twu.biblioteca;

/**
 * Created by qiyuesong on 22/6/15.
 */
public class LibraryItem {
    protected String name;
    protected boolean checkOutStatus;

    public LibraryItem(String name) {
        this.name = name;
        this.checkOutStatus = false;
    }

    public String getName() {
        return this.name;
    }

    public boolean getCheckOutStatus() {
        return this.checkOutStatus;
    }

    public void checkOut() {
        this.checkOutStatus = true;
    }

    public void checkIn() {
        this.checkOutStatus = false;
    }

    @Override
    public String toString(){
        return this.name;
    }
}


text:
package org.apache.commons.jcs.utils.zip;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;

/** Compress / Decompress. */
public final class CompressionUtil
{
    /** The logger */
    private static final Log log = LogFactory.getLog( CompressionUtil.class );

    /**
     * no instances.
     */
    private CompressionUtil()
    {
        // NO OP
    }

    /**
     * Decompress the byte array passed using a default buffer length of 1024.
     *

     * @param input compressed byte array webservice response
     * @return uncompressed byte array
     */
    public static byte[] decompressByteArray( final byte[] input )
    {
        return decompressByteArray( input, 1024 );
    }

    /**
     * Decompress the byte array passed
     *

     * @param input compressed byte array webservice response
     * @param bufferLength buffer length
     * @return uncompressed byte array
     */
    public static byte[] decompressByteArray( final byte[] input, final int bufferLength )
    {
        if ( null == input )
        {
            throw new IllegalArgumentException( "Input was null" );
        }

        // Create the decompressor and give it the data to compress
        final Inflater decompressor = new Inflater();

        decompressor.setInput( input );

        // Create an expandable byte array to hold the decompressed data
        final ByteArrayOutputStream baos = new ByteArrayOutputStream( input.length );

        // Decompress the data
        final byte[] buf = new byte[bufferLength];

        try
        {
            while ( !decompressor.finished() )
            {
                int count = decompressor.inflate( buf );
                baos.write( buf, 0, count );
            }
        }
        catch ( DataFormatException ex )
        {
            log.error( "Problem decompressing.", ex );
        }

        decompressor.end();

        try
        {
            baos.close();
        }
        catch ( IOException ex )
        {
            log.error( "Problem closing stream.", ex );
        }

        return baos.toByteArray();
    }

    /**
     * Compress the byte array passed
     *

     * @param input byte array
     * @return compressed byte array
     * @throws IOException thrown if we can't close the output stream
     */
    public static byte[] compressByteArray( byte[] input )
        throws IOException
    {
        return compressByteArray( input, 1024 );
    }

    /**
     * Compress the byte array passed
     *

     * @param input byte array
     * @param bufferLength buffer length
     * @return compressed byte array
     * @throws IOException thrown if we can't close the output stream
     */
    public static byte[] compressByteArray( byte[] input, int bufferLength )
        throws IOException
    {
        // Compressor with highest level of compression
        Deflater compressor = new Deflater();
        compressor.setLevel( Deflater.BEST_COMPRESSION );

        // Give the compressor the data to compress
        compressor.setInput( input );
        compressor.finish();

        // Create an expandable byte array to hold the compressed data.
        // It is not necessary that the compressed data will be smaller than
        // the uncompressed data.
        ByteArrayOutputStream bos = new ByteArrayOutputStream( input.length );

        // Compress the data
        byte[] buf = new byte[bufferLength];
        while ( !compressor.finished() )
        {
            int count = compressor.deflate( buf );
            bos.write( buf, 0, count );
        }

        // JCS-136 ( Details here : http://www.devguli.com/blog/eng/java-deflater-and-outofmemoryerror/ )
        compressor.end();
        bos.close();

        // Get the compressed data
        return bos.toByteArray();

    }

    /**
     * decompress a gzip byte array, using a default buffer length of 1024
     *

     * @param compressedByteArray gzip-compressed byte array
     * @return decompressed byte array
     * @throws IOException thrown if there was a failure to construct the GzipInputStream
     */
    public static byte[] decompressGzipByteArray( byte[] compressedByteArray )
        throws IOException
    {
        return decompressGzipByteArray( compressedByteArray, 1024 );
    }

    /**
     * decompress a gzip byte array, using a default buffer length of 1024
     *

     * @param compressedByteArray gzip-compressed byte array
     * @param bufferlength size of the buffer in bytes
     * @return decompressed byte array
     * @throws IOException thrown if there was a failure to construct the GzipInputStream
     */
    public static byte[] decompressGzipByteArray( byte[] compressedByteArray, int bufferlength )
        throws IOException
    {
        ByteArrayOutputStream uncompressedStream = new ByteArrayOutputStream();

        GZIPInputStream compressedStream = new GZIPInputStream( new ByteArrayInputStream( compressedByteArray ) );

        byte[] buffer = new byte[bufferlength];

        int index = -1;

        while ( ( index = compressedStream.read( buffer ) ) != -1 )
        {
            uncompressedStream.write( buffer, 0, index );
        }

        return uncompressedStream.toByteArray();
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package p2pchat.mock;

import p2pchat.model.StatusType;
import p2pchat.model.User;
import p2pchat.model.peer.IOnlineUserManagerPeer;

/**
 *
 * @author USER
 */
public class OnlineUserManagerPeerMock implements IOnlineUserManagerPeer {

    public boolean online;
    public StatusType status;
    public StatusType setStatus;
    public int getOnlineUsersNumber;
    public User[] getUsers;
    public String findOnlineUser;
    public User findOnlineUserUser;
    public String getCurrentUser;
    public String addOnlineUserUsername;
    public String addOnlineUserAddress;
    public int addOnlineUserPort;
    public String[] getOnlineUserNames;
    public String removeOnlineUser;
    public String setUserUsername;
    public String setUserPhoto;

    @Override
    public boolean isOnline() {
        return online;
    }

    @Override
    public boolean addOnlineUser(String username, String address, int port) {
        addOnlineUserUsername = username;
        addOnlineUserAddress = address;
        addOnlineUserPort = port;
        return true;
    }

    @Override
    public String getCurrentUser() {
        return getCurrentUser;
    }

    @Override
    public User findOnlineUser(String username) {
        findOnlineUser = username;
        User ret = null;
        if (findOnlineUserUser != null && findOnlineUserUser.getUsername().equals(username)) {
            ret = findOnlineUserUser;
        }

        return ret;
    }

    @Override
    public boolean removeOnlineUser(String username) {
        removeOnlineUser = username;
        return true;
    }

    @Override
    public StatusType getStatus() {
        return status;
    }

    @Override
    public String[] getOnlineUserNames() {
        return getOnlineUserNames;
    }

    @Override
    public void setStatus(StatusType statusType) {
        setStatus = statusType;;
    }

    @Override
    public void setUser(String username, String photo) {
        setUserUsername = username;
        setUserPhoto = photo;
    }

    @Override
    public int getOnlineUsersNumber() {
        return getOnlineUsersNumber;
    }

    @Override
    public User[] getUsers() {
        return getUsers;
    }
}


text:
package org.etl.spi.flink.reducer.aggregator;

import org.etl.api.Record;
import org.etl.api.transform.Aggregator;

/**
 *
 */
public interface AggregatorReducer {

    Record reduceFirst(Aggregator aggregator,Record currentRecord, Record result);

    Record reduceNext(Aggregator aggregator,Record currentRecord, Record result);

}


text:
title: Data Analysis with Python
author: David Kraemer & Caleb Leedy
date: March 01, 2015
layout: page
urls: python
permalink: courses/python/
...

## Course description

Python is a general-purpose programming language with a wonderful
community of open-source support, allowing it to solve a whole host of
problems from application development to data analysis. No prior
knowledge of Python is required for this course. This course will follow
"Python for Data Analysis" by Wes McKinney, which gives a great overview
of the tools that Python provides for sophisticated modeling, analysis,
and visualization. This course will introduce you to the IPython
environment, a powerful and robust tool for general scripting purposes.
It will also cover important aspects of Python's numerical computation
and data analysis libraries and will use several case studies to
illustrate important concepts.

## Why use Python?

Python has a number of qualities making it more attractive than its
competitors. First, Python is free. It only takes an idea and some
perseverance to do sophisticated data analysis, not a hefty subscription
to proprietary software. Second, Python is user-friendly. Python's code
is clear, concise, and powerful; it doesn't take a degree in computer
science to learn it! Finally, Python is professional. For researchers,
analysts, hobbyists, and anyone in between, Python provides a host of
tools that allow you to acquire, clean, analyze, and visualize data fit
for publication or presentation.

## What will I gain from this class?

By taking this class you can expect to gain proficiency in Python's
NumPy and Pandas libraries, as well as the ability to use Matplotlib for
data visualization. The IPython notebook is the primary development
environment that this class will use, so you will learn how to use the
tools it provides to improve their efficiency as programmers. Data
analysis is emerging as the lingua franca of diverse professions ranging
from scientific research to business enterprise, and Python is a
powerful but programmer-friendly alternative to closed-source programs
like MATLAB and Excel.

## Will this class teach me Python basics?

We want this ExCo to focus on the scientific computation and data
analysis libraries built in Python, so we will not spend much time
covering Python syntax and language features. However, there are a
plethora of good resources online to pick up a "conversational" level of
Python in order to make sense of the material that we cover. Above, we
have listed a selection of sites that we have personally found useful.
For those of you interested in a brief overview of syntax, check out
[CodeAcademy's Python
Tutorial](http://www.codecademy.com/en/tracks/python). Here you can get
a good working knowledge of the core Python we will rely on for the
class. The entire tutorial is estimated at 13 hours, but for the
material we cover, you probably can do the first 5 hours of it to be
comfortable.

If you know basic Python syntax and want to see it in action on a small
scale, you should check out [CodingBat's Python
exercises.](http://www.codingbat.com/python) They provide simple, but
thought-provoking problems that force you to test your knowledge of
Python syntax in order to solve them. If you're an experienced computer
scientist or have dealt with Python before, advanced problems can be
found at [CodeWars' Python problems.](http://www.codewars.com) These
questions range from trivial to exceptionally difficult, and often will
require you to consider not only solving the problem at hand, but doing
so efficiently.

## Data analysis libraries and resources

This class will explore the core data analysis libraries in Python:

-   NumPy: fast, vectorized array computation. This is the bread and
    butter of all advanced data analysis programming.
-   pandas: a software library useful for large-scale analysis and
    Excel-like computation.
-   matplotlib: robust graphical visualization, compatible with NumPy
    and pandas.

These libraries are extensive, and we can't possibly go through them
all. Instead, we'll show you simple applications of these tools to get
you acquainted with them. Consulting the documentation for each of the
respective libraries is the best way to learn more about them, but
documentation is difficult to read, so this class will also help you get
used to extracting the important information from the documentation.

We will be using *Python for Data Analysis* by Wes McKinney to build
lesson plans on the topics covered in this class. The book can be found
[on Amazon,
here](http://www.amazon.com/%0A%20%20%20%20%20%20%20%20%20%20Python-Data-Analysis-Wrangling-IPython/dp/1449319793/ref=sr_1_1?ie=UTF8&qid=1425167167&sr=8-1&keywords=%0A%20%20%20%20%20%20%20%20%20%20python+for+data+analysis),
but unless you fall in love with Python and want to have it as a
reference, we don't recommend that you purchase it. This is because
there are a multitude of great, free resources available online. We will
probably borrow shamelessly from a number of online sources as well as
the text, and we will do our best to site them (if you spot an
oversight, please tell us!).

While NumPy, pandas, and matplotlib form the core data analysis tools in
Python, there are other libraries we will not cover. That does not mean
you should not check them out! Here are a few notable projects:

-   [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/): easy
    web scraping tools
-   [SciPy](scipy.org): the parent project of NumPy; contains a huge
    repository of useful scientific functions
-   [SymPy](http://www.sympy.org/en/index.html): symbolic algebra
    computation in Python (i.e. open-source Mathematica)
-   [scikit-learn](http://scikit-learn.org/stable/): extensive
    statistics and machine learning libraries
-   [seaborn](http://stanford.edu/~mwaskom/software/seaborn/): beautiful
    statistical plotting
-   [prettyplotlib](https://github.com/olgabot/prettyplotlib): aesthetic
    wrapper for matplotlib
-   [Quandl](https://www.quandl.com/): fantastic database of free (and
    premium) economic and financial data

## Useful links

* [Python](https://www.python.org/), the Python website, which links to
  documentation, downloads, news, and other community events in the Python world
* [Python 2.7 documentation](https://docs.python.org/2.7/), the Python 2.7
  official documentation
* [SciPy](http://docs.scipy.org/doc/scipy/reference/index.html), official SciPy
  documentation
* [NumPy](http://docs.scipy.org/doc/numpy/reference/index.html), official NumPy
  documentation
* [pandas](http://pandas.pydata.org/), official Pandas documentation
* [Matplotlib](http://matplotlib.org/), official Matplotlib documentation
* [Code Academy](http://www.codecademy.com/en/tracks/python), a good tutorial on
  learning the basics of Python syntax
* [CodingBat](http://codingbat.com/python), short exercises that help solidify
  your grasp on Python syntax and programming basics
* [Code Wars](http://www.codewars.com/dashboard), more advanced programming
  exercises, and some are essentially interview-level problems

## And, from xkcd

![](http://imgs.xkcd.com/comics/python.png)


text:
<?xml version="1.0"?>
<!--

    Copyright (c) 1997, 2021 Oracle and/or its affiliates. All rights reserved.

    This program and the accompanying materials are made available under the
    terms of the Eclipse Distribution License v. 1.0, which is available at
    http://www.eclipse.org/org/documents/edl-v10.php.

    SPDX-License-Identifier: BSD-3-Clause

-->

<project name="XJC Servlet" default="deploy" basedir="../..">

    <!-- import build properties -->
    <property file="${basedir}/build.properties" />

    <property name="servlet.root" value="${jaxb.root}/tools/servlet"/>
    <property name="commons.root" value="${servlet.root}/../webapp-commons" />
<!--
  deploy.home          The name of the directory into which the
                       deployment hierarchy will be created, and into
                       which the build directory will be copied.
                       Defaults to "${catalina.home}/webapps/${app.name}".
-->
    <!-- this property needs to be defined externally -->
    <!--property name="catalina.home" value="${servlet.root}/catalina"/-->
    <property name="deploy.home"   value="${catalina.home}/webapps/xjc"/>

    <!-- determine the behavior of the servlet -->
    <property name="mode" value="jwsdp" /><!-- or "standalone" -->

    <!-- when deployed to JWSDP1.0_01, we can't have Xerces in our classpath. -->
    <property name="exclusion.lib" value="xercesImpl.jar" />

    <!-- libraries that are referenced when compiling Java source files -->
    <path id="javac.classpath">
      <pathelement path="${codemodel.classes}" />
      <pathelement path="${runtime.classes}" />
      <pathelement path="${xjc.classes}" />
      <pathelement path="${commons.root}/jaxb-webapp-commons.jar"/>
      <fileset dir="${jaxb.libs.redist}" includes="*.jar"/>
      <fileset dir="${jaxb.libs.rebundle}" includes="**/*.jar"/>
      <fileset dir="${jaxb.libs.util}" includes="*.jar"/>
    </path>

  <target name="all" depends="clean,compile"
   description="Clean build and dist, then compile"/>

  <target name="clean">
    <delete dir="${servlet.root}/build"/>
    <delete dir="${servlet.root}/boxed.jar"/>
    <delete dir="${deploy.home}"/>
  </target>

  <target name="compile">
    <ant target="jar" antfile="${commons.root}/build.xml" />

    <!-- Compile Java classes as necessary -->
    <mkdir    dir="${servlet.root}/build/classes"/>
    <javac srcdir="${servlet.root}/src" destdir="${servlet.root}/build/classes"
           debug="${compile.debug}" optimize="${compile.optimize}"
    	   source="1.6" target="1.6"
           deprecation="${compile.deprecation}" >
      <classpath refid="javac.classpath"/>
    </javac>

    <!-- Copy associated resource files -->
    <copy  todir="${servlet.root}/build/classes">
      <fileset dir="${servlet.root}/src" includes="**/*.properties"/>
    </copy>

    <!-- make boxed jar file -->
    <jar destfile="${servlet.root}/boxed.jar">
      <fileset dir="${servlet.root}/build/classes" includes="**/boxed/**/*" />
    </jar>

    <!-- make setting file -->
    <echo file="${servlet.root}/build/classes/com/sun/tools/xjc/servlet/Mode.properties">mode=${mode}</echo>
  </target>

  <target name="war" description="build a war file from jaxb-ri/dist" depends="compile">
    <delete file="${servlet.root}/xjc.war" />
    <war destfile="${servlet.root}/xjc.war" webxml="${servlet.root}/web.xml">
      <classes dir="${servlet.root}/build/classes"/>
      <classes dir="${servlet.root}/src" includes="**/package-list" />

      <lib dir="${jaxb.root}/dist/lib" includes="*.jar" excludes="${exclusion.lib}" />
      <lib dir="${jaxb.libs.util}" includes="mailapi.jar, smtp.jar, gsc.jar, antlr.jar"/>
      <lib dir="${servlet.root}" includes="boxed.jar"/>
      <lib dir="${commons.root}" includes="jaxb-webapp-commons.jar"/>

      <webinf dir="${servlet.root}" includes="taglib.tld"/>

      <!-- static contents -->
      <fileset dir="${servlet.root}/web"/>
    </war>
  </target>

  <target name="war-jwsdp" description="build a war file for JWSDP" depends="compile">
    <delete file="${servlet.root}/xjc.war" />
    <war destfile="${servlet.root}/xjc.war" webxml="${servlet.root}/web.xml">
      <classes dir="${servlet.root}/build/classes"/>
      <classes dir="${servlet.root}/src" includes="**/package-list" />

      <lib dir="${jaxb.libs.util}" includes="mailapi.jar, smtp.jar, gsc.jar, antlr.jar"/>
      <lib dir="${servlet.root}" includes="boxed.jar"/>
      <lib dir="${commons.root}" includes="jaxb-webapp-commons.jar"/>

      <webinf dir="${servlet.root}" includes="taglib.tld"/>

      <!-- static contents -->
      <fileset dir="${servlet.root}/web"/>
    </war>
  </target>

  <!-- make sure the deployment directory is available -->
  <target name="init-prepare">
    <available property="deploy.dir.available" file="${catalina.home}"/>
  </target>
  <target name="init" depends="init-prepare" unless="deploy.dir.available">
    <fail>
      Directory ${catalina.home} doesn't exist. Set the property
      catalina.home before launching ant.

      e.g.,  ant -Dcatalina.home=xxxxx
    </fail>
  </target>

  <target name="deploy" depends="init,compile"
   description="Deploy application to servlet container">

    <!-- Copy the contents of the build directory -->
    <mkdir     dir="${deploy.home}/WEB-INF/classes"/>
    <copy    todir="${deploy.home}/WEB-INF/classes">
      <fileset dir="${servlet.root}/build/classes"/>
      <fileset dir="${servlet.root}/src" includes="**/package-list" />
    </copy>

    <!-- Copy external dependencies as required -->
    <mkdir  dir="${deploy.home}/WEB-INF/lib"/>
    <copy todir="${deploy.home}/WEB-INF/lib">
      <fileset dir="${jaxb.root}/dist/lib" includes="*.jar" excludes="${exclusion.lib}"/>
      <fileset dir="${jaxb.libs.util}" includes="mailapi.jar, smtp.jar, gsc.jar, antlr.jar"/>
      <fileset dir="${commons.root}" includes="jaxb-webapp-commons.jar"/>
      <fileset dir="${servlet.root}" includes="boxed.jar"/>
    </copy>

    <copy todir="${deploy.home}/WEB-INF">
      <fileset dir="${servlet.root}" includes="web.xml, taglib.tld" />
    </copy>

    <!-- Copy static content -->
    <copy todir="${deploy.home}">
      <fileset dir="${servlet.root}/web"/>
    </copy>
  </target>

  <target name="reload" depends="init,deploy" description="Deploy and reload Tomcat">
    <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask">
      <classpath path="${catalina.home}/server/lib/catalina-ant.jar" />
    </taskdef>
    <reload url="http://localhost:8080/manager" username="tomcat" password="tomcat" path="/xjc" />
  </target>

</project>


text:
package com.xhh.demo.http.factory.enumfactory;

import com.xhh.demo.http.factory.Car;

/**
 * CarAbstractFactory
 *
 * @author tiger
 * @version 1.0.0 createTime: 14-4-3
 * @since 1.6
 */
public enum CarAbstractFactory {

    BenzCar {
        public Car create() {
            return new com.xhh.demo.http.factory.BenzCar();
        }
    },
    FordCar {
        public Car create() {
            return new com.xhh.demo.http.factory.FordCar();
        }
    };

    public abstract Car create();
}


text:
from collections import namedtuple
from typing import List

import graphene
from django.core.exceptions import ValidationError
from graphql_relay import from_global_id

from ...menu import models
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..page.types import Page
from ..product.types import Category, Collection
from .enums import NavigationType
from .types import Menu, MenuItem, MenuItemMoveInput

class MenuItemInput(graphene.InputObjectType):
    name = graphene.String(description='Name of the menu item.')
    url = graphene.String(description='URL of the pointed item.')
    category = graphene.ID(
        description='Category to which item points.', name='category')
    collection = graphene.ID(
        description='Collection to which item points.', name='collection')
    page = graphene.ID(
        description='Page to which item points.', name='page')

class MenuItemCreateInput(MenuItemInput):
    menu = graphene.ID(
        description='Menu to which item belongs to.', name='menu',
        required=True)
    parent = graphene.ID(
        description='''
        ID of the parent menu. If empty, menu will be top level
        menu.''',
        name='parent')

class MenuInput(graphene.InputObjectType):
    name = graphene.String(description='Name of the menu.')

class MenuCreateInput(MenuInput):
    items = graphene.List(
        MenuItemInput, description='List of menu items.')

class MenuCreate(ModelMutation):
    class Arguments:
        input = MenuCreateInput(
            required=True,
            description='Fields required to create a menu.')

    class Meta:
        description = 'Creates a new Menu'
        model = models.Menu
        permissions = ('menu.manage_menus', )

    @classmethod
    def clean_input(cls, info, instance, data):
        cleaned_input = super().clean_input(info, instance, data)
        items = []
        for item in cleaned_input.get('items', []):
            category = item.get('category')
            collection = item.get('collection')
            page = item.get('page')
            url = item.get('url')
            if len([i for i in [category, collection, page, url] if i]) > 1:
                raise ValidationError(
                    {'items': 'More than one item provided.'})

            if category:
                category = cls.get_node_or_error(
                    info, category, field='items', only_type=Category)
                item['category'] = category
            elif collection:
                collection = cls.get_node_or_error(
                    info, collection, field='items', only_type=Collection)
                item['collection'] = collection
            elif page:
                page = cls.get_node_or_error(
                    info, page, field='items', only_type=Page)
                item['page'] = page
            elif not url:
                raise ValidationError({'items': 'No menu item provided.'})
            items.append(item)

        cleaned_input['items'] = items
        return cleaned_input

    @classmethod
    def _save_m2m(cls, info, instance, cleaned_data):
        super()._save_m2m(info, instance, cleaned_data)
        items = cleaned_data.get('items', [])
        for item in items:
            instance.items.create(**item)

class MenuUpdate(ModelMutation):
    class Arguments:
        id = graphene.ID(
            required=True, description='ID of a menu to update.')
        input = MenuInput(
            required=True,
            description='Fields required to update a menu.')

    class Meta:
        description = 'Updates a menu.'
        model = models.Menu
        permissions = ('menu.manage_menus', )

class MenuDelete(ModelDeleteMutation):
    class Arguments:
        id = graphene.ID(
            required=True, description='ID of a menu to delete.')

    class Meta:
        description = 'Deletes a menu.'
        model = models.Menu
        permissions = ('menu.manage_menus', )

class MenuItemCreate(ModelMutation):
    class Arguments:
        input = MenuItemCreateInput(
            required=True,
            description="""Fields required to update a menu item.
            Only one of 'url', 'category', 'page', 'collection' is allowed
            per item""")

    class Meta:
        description = 'Creates a new Menu'
        model = models.MenuItem
        permissions = ('menu.manage_menus', )

    @classmethod
    def clean_input(cls, info, instance, data):
        cleaned_input = super().clean_input(info, instance, data)
        items = [
            cleaned_input.get('page'), cleaned_input.get('collection'),
            cleaned_input.get('url'), cleaned_input.get('category')]
        items = [item for item in items if item is not None]
        if len(items) > 1:
            raise ValidationError({'items': 'More than one item provided.'})
        return cleaned_input

class MenuItemUpdate(MenuItemCreate):
    class Arguments:
        id = graphene.ID(
            required=True, description='ID of a menu item to update.')
        input = MenuItemInput(
            required=True,
            description="""Fields required to update a menu item.
            Only one of 'url', 'category', 'page', 'collection' is allowed
            per item""")

    class Meta:
        description = 'Updates a menu item.'
        model = models.MenuItem
        permissions = ('menu.manage_menus', )

    @classmethod
    def construct_instance(cls, instance, cleaned_data):
        # Only one item can be assigned per menu item
        instance.page = None
        instance.collection = None
        instance.category = None
        instance.url = None
        return super().construct_instance(instance, cleaned_data)

class MenuItemDelete(ModelDeleteMutation):
    class Arguments:
        id = graphene.ID(
            required=True, description='ID of a menu item to delete.')

    class Meta:
        description = 'Deletes a menu item.'
        model = models.MenuItem
        permissions = ('menu.manage_menus', )

_MenuMoveOperation = namedtuple(
    '_MenuMoveOperation', ('menu_item', 'parent', 'sort_order'))

class MenuItemMove(BaseMutation):
    menu = graphene.Field(
        Menu, description='Assigned menu to move within.')

    class Arguments:
        menu = graphene.ID(
            required=True, description='ID of the menu.')
        moves = graphene.List(
            MenuItemMoveInput,
            required=True, description='The menu position data')

    class Meta:
        description = 'Moves items of menus'
        permissions = ('menu.manage_menus', )

    @staticmethod
    def clean_move(move):
        """Validate if the given move could be possibly possible."""
        if move.parent_id:
            if move.item_id == move.parent_id:
                raise ValidationError({
                    'parent': 'Cannot assign a node to itself.'})

    @staticmethod
    def clean_operation(operation: _MenuMoveOperation):
        """Validate if the given move will be actually possible."""

        if operation.parent:
            if operation.menu_item.is_ancestor_of(operation.parent):
                raise ValidationError({
                    'parent': (
                        'Cannot assign a node as child of '
                        'one of its descendants.')})

    @classmethod
    def get_operation(
            cls, info, menu_id: int, move) -> _MenuMoveOperation:
        parent_node = None

        _type, menu_item_id = from_global_id(move.item_id)  # type: str, int
        assert _type == 'MenuItem', \
            'The menu item node must be of type MenuItem.'

        menu_item = models.MenuItem.objects.get(
            pk=menu_item_id, menu_id=menu_id)

        if move.parent_id is not None:
            parent_node = cls.get_node_or_error(
                info, move.parent_id,
                field='parent_id', only_type=MenuItem)

        return _MenuMoveOperation(
            menu_item=menu_item,
            parent=parent_node,
            sort_order=move.sort_order)

    @classmethod
    def clean_moves(
            cls,
            info,
            menu_id: int,
            move_operations: List) -> List[_MenuMoveOperation]:

        operations = []
        for move in move_operations:
            cls.clean_move(move)
            operation = cls.get_operation(info, menu_id, move)
            cls.clean_operation(operation)
            operations.append(operation)
        return operations

    @staticmethod
    def perform_operation(operation: _MenuMoveOperation):
        menu_item = operation.menu_item  # type: models.MenuItem

        # Move the parent if provided
        if operation.parent:
            menu_item.move_to(operation.parent)
        # Remove the menu item's parent if was set to none (root node)
        elif menu_item.parent_id:
            menu_item.parent_id = None

        # Move the menu item
        if operation.sort_order is not None:
            menu_item.sort_order = operation.sort_order

        menu_item.save()

    @classmethod
    def perform_mutation(cls, root, info, menu, moves):
        _type, menu_id = from_global_id(menu)  # type: str, int
        assert _type == 'Menu', 'Expected a menu of type Menu'

        operations = cls.clean_moves(info, menu_id, moves)

        for operation in operations:
            cls.perform_operation(operation)

        return cls(menu=models.Menu.objects.get(pk=menu_id))

class AssignNavigation(BaseMutation):
    menu = graphene.Field(Menu, description='Assigned navigation menu.')

    class Arguments:
        menu = graphene.ID(description='ID of the menu.')
        navigation_type = NavigationType(
            description='Type of the navigation bar to assign the menu to.',
            required=True)

    class Meta:
        description = 'Assigns storefront\'s navigation menus.'
        permissions = ('menu.manage_menus', 'site.manage_settings')

    @classmethod
    def perform_mutation(cls, _root, info, navigation_type, menu=None):
        site_settings = info.context.site.settings
        if menu is not None:
            menu = cls.get_node_or_error(info, menu, field='menu')

        if navigation_type == NavigationType.MAIN:
            site_settings.top_menu = menu
            site_settings.save(update_fields=['top_menu'])
        elif navigation_type == NavigationType.SECONDARY:
            site_settings.bottom_menu = menu
            site_settings.save(update_fields=['bottom_menu'])

        return AssignNavigation(menu=menu)