text:
package org.sakaiproject.gradebookng.business.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.sakaiproject.gradebookng.business.exception.GbImportCommentMissingItemException;
import org.sakaiproject.gradebookng.business.exception.GbImportExportInvalidColumnException;
import org.sakaiproject.gradebookng.business.exception.GbImportExportInvalidFileTypeException;
import org.sakaiproject.gradebookng.business.model.GbGradeInfo;
import org.sakaiproject.gradebookng.business.model.GbStudentGradeInfo;
import org.sakaiproject.gradebookng.business.model.ImportColumn;
import org.sakaiproject.gradebookng.business.model.ImportedGrade;
import org.sakaiproject.gradebookng.business.model.ImportedGradeItem;
import org.sakaiproject.gradebookng.business.model.ImportedGradeWrapper;
import org.sakaiproject.gradebookng.business.model.ProcessedGradeItem;
import org.sakaiproject.gradebookng.business.model.ProcessedGradeItemDetail;
import org.sakaiproject.gradebookng.business.model.ProcessedGradeItemStatus;
import org.sakaiproject.gradebookng.tool.model.AssignmentStudentGradeInfo;
import org.sakaiproject.service.gradebook.shared.Assignment;

import au.com.bytecode.opencsv.CSVReader;
import lombok.extern.slf4j.Slf4j;

/**
 * Helper to handling parsing and processing of an imported gradebook file
 */
@Slf4j
public class ImportGradesHelper {

	// column names we know about
	public final static String IMPORT_USER_ID = "Student ID";
	public final static String IMPORT_USER_NAME = "Student Name";

	// patterns for detecting column headers and their types
	final static Pattern ASSIGNMENT_WITH_POINTS_PATTERN = Pattern.compile("([\\w ]+ \\[[0-9]+(\\.[0-9][0-9]?)?\\])");
	final static Pattern ASSIGNMENT_COMMENT_PATTERN = Pattern.compile("(\\* [\\w ]+)");
	final static Pattern STANDARD_HEADER_PATTERN = Pattern.compile("([\\w ]+)");
	final static Pattern POINTS_PATTERN = Pattern.compile("(\\d+)(?=]$)");
	final static Pattern IGNORE_PATTERN = Pattern.compile("(\\#.+)");

	// list of mimetypes for each category. Must be compatible with the parser
	private static final String[] XLS_MIME_TYPES = { "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" };
	private static final String[] CSV_MIME_TYPES = { "text/csv", "text/plain", "text/comma-separated-values", "application/csv" };

	/**
	 * Helper to parse the imported file into an {@link ImportedGradeWrapper} depending on its type
	 * @param is
	 * @param mimetype
	 * @param userMap
	 * @return
	 * @throws GbImportExportInvalidColumnException
	 * @throws GbImportExportInvalidFileTypeException
	 * @throws IOException
	 * @throws InvalidFormatException
	 */
	public static ImportedGradeWrapper parseImportedGradeFile(final InputStream is, final String mimetype, final Map<String, String> userMap) throws GbImportExportInvalidColumnException, GbImportExportInvalidFileTypeException, IOException, InvalidFormatException {

		ImportedGradeWrapper rval = null;

		// determine file type and delegate
		if (ArrayUtils.contains(CSV_MIME_TYPES, mimetype)) {
			rval = ImportGradesHelper.parseCsv(is, userMap);
		} else if (ArrayUtils.contains(XLS_MIME_TYPES, mimetype)) {
			rval = ImportGradesHelper.parseXls(is, userMap);
		} else {
			throw new GbImportExportInvalidFileTypeException("Invalid file type for grade import: " + mimetype);
		}
		return rval;
	}

	/**
	 * Parse a CSV into a list of ImportedGrade objects. Returns list if ok, or null if error
	 *
	 * @param is InputStream of the data to parse
	 * @return
	 * @throws IOException
	 * @throws GbImportExportInvalidColumnException
	 */
	private static ImportedGradeWrapper parseCsv(final InputStream is, final Map<String, String> userMap) throws GbImportExportInvalidColumnException, IOException {

		// manually parse method so we can support arbitrary columns
		final CSVReader reader = new CSVReader(new InputStreamReader(is));
		String[] nextLine;
		int lineCount = 0;
		final List<ImportedGrade> list = new ArrayList<ImportedGrade>();
		Map<Integer, ImportColumn> mapping = null;

		try {
			while ((nextLine = reader.readNext()) != null) {

				if (lineCount == 0) {
					// header row, capture it
					mapping = mapHeaderRow(nextLine);
				} else {
					// map the fields into the object
					list.add(mapLine(nextLine, mapping, userMap));
				}
				lineCount++;
			}
		} finally {
			try {
				reader.close();
			} catch (final IOException e) {
				e.printStackTrace();
			}
		}

		final ImportedGradeWrapper importedGradeWrapper = new ImportedGradeWrapper();
		importedGradeWrapper.setColumns(mapping.values());
		importedGradeWrapper.setImportedGrades(list);

		return importedGradeWrapper;
	}

	/**
	 * Parse an XLS into a list of ImportedGrade objects Note that only the first sheet of the Excel file is supported.
	 *
	 * @param is InputStream of the data to parse
	 * @return
	 * @throws IOException
	 * @throws InvalidFormatException
	 * @throws GbImportExportInvalidColumnException
	 */
	private static ImportedGradeWrapper parseXls(final InputStream is, final Map<String, String> userMap) throws GbImportExportInvalidColumnException, InvalidFormatException, IOException {

		int lineCount = 0;
		final List<ImportedGrade> list = new ArrayList<ImportedGrade>();
		Map<Integer, ImportColumn> mapping = null;

		final Workbook wb = WorkbookFactory.create(is);
		final Sheet sheet = wb.getSheetAt(0);
		for (final Row row : sheet) {

			final String[] r = convertRow(row);

			if (lineCount == 0) {
				// header row, capture it
				mapping = mapHeaderRow(r);
			} else {
				// map the fields into the object
				list.add(mapLine(r, mapping, userMap));
			}
			lineCount++;
		}

		final ImportedGradeWrapper importedGradeWrapper = new ImportedGradeWrapper();
		importedGradeWrapper.setColumns(mapping.values());
		importedGradeWrapper.setImportedGrades(list);
		return importedGradeWrapper;
	}

	/**
	 * Takes a row of data and maps it into the appropriate ImportedGrade pieces
	 *
	 * @param line
	 * @param mapping
	 * @return
	 */
	private static ImportedGrade mapLine(final String[] line, final Map<Integer, ImportColumn> mapping, final Map<String, String> userMap) {

		final ImportedGrade grade = new ImportedGrade();

		for (final Map.Entry<Integer, ImportColumn> entry : mapping.entrySet()) {

			final int i = entry.getKey();
			final ImportColumn importColumn = entry.getValue();

			// In case there aren't enough data fields in the line to match up with the number of columns needed
			String lineVal = null;
			if (i < line.length) {
				lineVal = trim(line[i]);
			}

			final String columnTitle = importColumn.getColumnTitle();

			// process user id column
			if (StringUtils.equals(columnTitle, IMPORT_USER_ID)) {
				grade.setStudentEid(lineVal);
				grade.setStudentUuid(userMap.get(lineVal));

			// process user name column
			} else if (StringUtils.equals(columnTitle, IMPORT_USER_NAME)) {
				grade.setStudentName(lineVal);

			//process item with points column
			} else if (importColumn.getType() == ImportColumn.Type.GB_ITEM_WITH_POINTS) {
				ImportedGradeItem importedGradeItem = grade.getGradeItemMap().get(columnTitle);
				if (importedGradeItem == null) {
					importedGradeItem = new ImportedGradeItem(columnTitle);
				}
				importedGradeItem.setGradeItemScore(lineVal);
				grade.getGradeItemMap().put(columnTitle, importedGradeItem);

			//process comments
			} else if (importColumn.getType() == ImportColumn.Type.COMMENTS) {
				ImportedGradeItem importedGradeItem = grade.getGradeItemMap().get(columnTitle);
				if (importedGradeItem == null) {
					importedGradeItem = new ImportedGradeItem(columnTitle);
				}
				importedGradeItem.setGradeItemComment(lineVal);
				grade.getGradeItemMap().put(columnTitle, importedGradeItem);

			// process any left overs. These will be gb items without points
			} else if (importColumn.getType() == ImportColumn.Type.GB_ITEM_WITHOUT_POINTS) {
				ImportedGradeItem importedGradeItem = grade.getGradeItemMap().get(columnTitle);
				if (importedGradeItem == null) {
					importedGradeItem = new ImportedGradeItem(columnTitle);
				}
				grade.getGradeItemMap().put(columnTitle, importedGradeItem);
			}
		}

		return grade;
	}

	/**
	 * Process the data.
	 *
	 * TODO enhance this to have better returns ie GbExceptions
	 *
	 * @param importedGradeWrapper
	 * @param assignments
	 * @param currentGrades
	 *
	 * @return
	 */
	public static List<ProcessedGradeItem> processImportedGrades(final ImportedGradeWrapper importedGradeWrapper,
			final List<Assignment> assignments, final List<GbStudentGradeInfo> currentGrades) {

		// setup
		// TODO this will ensure dupes can't be added. Provide a report to the user that dupes were added. There would need to be a step before this though
		final Map<String, ProcessedGradeItem> assignmentProcessedGradeItemMap = new HashMap<>();

		// process grades
		final Map<Long, AssignmentStudentGradeInfo> transformedGradeMap = transformCurrentGrades(currentGrades);

		// Map assignment name to assignment
		final Map<String, Assignment> assignmentNameMap = assignments.stream().collect(Collectors.toMap(Assignment::getName, a -> a));

		//for every column, setup the data
		for (final ImportColumn column : importedGradeWrapper.getColumns()) {
			boolean needsToBeAdded = false;

			final String columnTitle = StringUtils.trim(column.getColumnTitle()); // trim whitespace so we can match properly

			//setup a new one unless it already exists (ie there were duplicate columns)
			ProcessedGradeItem processedGradeItem = assignmentProcessedGradeItemMap.get(columnTitle);
			if (processedGradeItem == null) {
				processedGradeItem = new ProcessedGradeItem();
				needsToBeAdded = true;

				//default to gb_item
				//overridden if a comment type
				processedGradeItem.setType(ProcessedGradeItem.Type.GB_ITEM);
			}

			final Assignment assignment = assignmentNameMap.get(columnTitle);
			final ProcessedGradeItemStatus status = determineStatus(column, assignment, importedGradeWrapper, transformedGradeMap);

			// skip the student columns
			if(StringUtils.equals(column.getColumnTitle(), IMPORT_USER_ID) ||
					StringUtils.equals(column.getColumnTitle(), IMPORT_USER_NAME)) {
				continue;
			}

			if (column.getType() == ImportColumn.Type.GB_ITEM_WITH_POINTS) {
				log.debug("GB Item: " + columnTitle + ", status: " + status.getStatusCode());
				processedGradeItem.setItemTitle(columnTitle);
				processedGradeItem.setItemPointValue(column.getPoints());
				processedGradeItem.setStatus(status);
			} else if (column.getType() == ImportColumn.Type.COMMENTS) {
				log.debug("Comments: " + columnTitle + ", status: " + status.getStatusCode());
				processedGradeItem.setType(ProcessedGradeItem.Type.COMMENT);
				processedGradeItem.setCommentStatus(status);
			} else if (column.getType() == ImportColumn.Type.GB_ITEM_WITHOUT_POINTS) {
				log.debug("Regular: " + columnTitle + ", status: " + status.getStatusCode());
				processedGradeItem.setItemTitle(columnTitle);
				processedGradeItem.setStatus(status);
			} else {
				// skip
				//TODO could return this but as a skip status?
				log.warn("Bad column. Type: " + column.getType() + ", header: " + columnTitle + ".  Skipping.");
				continue;
			}

			if (assignment != null) {
				processedGradeItem.setItemId(assignment.getId());
			}

			final List<ProcessedGradeItemDetail> processedGradeItemDetails = new ArrayList<>();
			for (final ImportedGrade importedGrade : importedGradeWrapper.getImportedGrades()) {
				final ImportedGradeItem importedGradeItem = importedGrade.getGradeItemMap().get(columnTitle);
				if (importedGradeItem != null) {
					final ProcessedGradeItemDetail processedGradeItemDetail = new ProcessedGradeItemDetail();
					processedGradeItemDetail.setStudentEid(importedGrade.getStudentEid());
					processedGradeItemDetail.setStudentUuid(importedGrade.getStudentUuid());
					processedGradeItemDetail.setGrade(importedGradeItem.getGradeItemScore());
					processedGradeItemDetail.setComment(importedGradeItem.getGradeItemComment());
					processedGradeItemDetails.add(processedGradeItemDetail);
				}

			}
			processedGradeItem.setProcessedGradeItemDetails(processedGradeItemDetails);

			// add to list
			if (needsToBeAdded) {
				assignmentProcessedGradeItemMap.put(columnTitle, processedGradeItem);
			}
		}

		// get just a list
		final List<ProcessedGradeItem> processedGradeItems = new ArrayList<>(assignmentProcessedGradeItemMap.values());

		// comment columns must have an associated gb item column
		// this ensures we have a processed grade item for each one
		final List<ProcessedGradeItem> commentColumns = processedGradeItems.stream().filter(p -> p.getType() == ProcessedGradeItem.Type.COMMENT).collect(Collectors.toList());

		commentColumns.forEach(c -> {
			final boolean matchingItemExists = processedGradeItems.stream().filter(p -> StringUtils.equals(c.getItemTitle(), p.getItemTitle())).findFirst().isPresent();
			if(!matchingItemExists) {
				throw new GbImportCommentMissingItemException("The comment column '" + c + "' does not have a corresponding gradebook item.");
			}
		});

		return processedGradeItems;

	}

	/**
	 * Determine the status of a column
	 * @param column
	 * @param assignment
	 * @param importedGradeWrapper
	 * @param transformedGradeMap
	 * @return
	 */
	private static ProcessedGradeItemStatus determineStatus(final ImportColumn column, final Assignment assignment,
			final ImportedGradeWrapper importedGradeWrapper,
			final Map<Long, AssignmentStudentGradeInfo> transformedGradeMap) {

		//TODO - really? an arbitrary value? How about null... Remove this
		ProcessedGradeItemStatus status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_UNKNOWN);

		if (assignment == null) {
			status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_NEW);
		} else if (assignment.getExternalId() != null) {
			status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_EXTERNAL, assignment.getExternalAppName());
		} else if (column.getType() == ImportColumn.Type.GB_ITEM_WITH_POINTS && assignment.getPoints().compareTo(NumberUtils.toDouble(column.getPoints())) != 0) {
			status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_MODIFIED);
		} else {
			for (final ImportedGrade importedGrade : importedGradeWrapper.getImportedGrades()) {
				final AssignmentStudentGradeInfo assignmentStudentGradeInfo = transformedGradeMap.get(assignment.getId());
				final ImportedGradeItem importedGradeItem = importedGrade.getGradeItemMap().get(column.getColumnTitle());

				String actualScore = null;
				String actualComment = null;

				if (assignmentStudentGradeInfo != null) {
					final GbGradeInfo actualGradeInfo = assignmentStudentGradeInfo.getStudentGrades().get(importedGrade.getStudentEid());

					if (actualGradeInfo != null) {
						actualScore = actualGradeInfo.getGrade();
						actualComment = actualGradeInfo.getGradeComment();
					}
				}
				String importedScore = null;
				String importedComment = null;

				if (importedGradeItem != null) {
					importedScore = importedGradeItem.getGradeItemScore();
					importedComment = importedGradeItem.getGradeItemComment();
				}

				if (column.getType() == ImportColumn.Type.GB_ITEM_WITH_POINTS) {
					final String trimmedImportedScore = StringUtils.removeEnd(importedScore, ".0");
					final String trimmedActualScore = StringUtils.removeEnd(actualScore, ".0");
					if (trimmedImportedScore != null && !trimmedImportedScore.equals(trimmedActualScore)) {
						status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_UPDATE);
						break;
					}
				} else if (column.getType() == ImportColumn.Type.COMMENTS) {
					if (importedComment != null && !importedComment.equals(actualComment)) {
						status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_UPDATE);
						break;
					}
				} else if (column.getType() == ImportColumn.Type.GB_ITEM_WITHOUT_POINTS) {
					//must be NA if it isn't new
					status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_NA);
					break;
				}

			}
			// If we get here, must not have been any changes
			if (status.getStatusCode() == ProcessedGradeItemStatus.STATUS_UNKNOWN) {
				status = new ProcessedGradeItemStatus(ProcessedGradeItemStatus.STATUS_NA);
			}

			// TODO - What about if a user was added to the import file?
			// That probably means that actualGradeInfo from up above is null...but what do I do?

		}
		return status;
	}

	private static Map<Long, AssignmentStudentGradeInfo> transformCurrentGrades(final List<GbStudentGradeInfo> currentGrades) {
		final Map<Long, AssignmentStudentGradeInfo> assignmentMap = new HashMap<Long, AssignmentStudentGradeInfo>();

		for (final GbStudentGradeInfo studentGradeInfo : currentGrades) {
			for (final Map.Entry<Long, GbGradeInfo> entry : studentGradeInfo.getGrades().entrySet()) {
				final Long assignmentId = entry.getKey();
				AssignmentStudentGradeInfo assignmentStudentGradeInfo = assignmentMap.get(assignmentId);
				if (assignmentStudentGradeInfo == null) {
					assignmentStudentGradeInfo = new AssignmentStudentGradeInfo();
					assignmentStudentGradeInfo.setAssignmemtId(assignmentId);
					assignmentMap.put(assignmentId, assignmentStudentGradeInfo);
				}
				assignmentStudentGradeInfo.addGrade(studentGradeInfo.getStudentEid(), entry.getValue());
			}

		}

		return assignmentMap;
	}

	/**
	 * Takes a row of String[] data to determine the position of the columns so that we can correctly parse any arbitrary delimited file.
	 * This is required because when we iterate over the rest of the lines, we need to know what the column header is, so we can take the appropriate action.
	 *
	 * @param line the already split line
	 * @return
	 */
	private static Map<Integer, ImportColumn> mapHeaderRow(final String[] line) throws GbImportExportInvalidColumnException {
		final Map<Integer, ImportColumn> mapping = new LinkedHashMap<Integer, ImportColumn>();
		for (int i = 0; i < line.length; i++) {

			final ImportColumn column = parseHeaderForImportColumn(trim(line[i]));
			if (column != null) {
				mapping.put(i, column);
			}
		}

		return mapping;
	}

	/**
	 * Helper to parse the header row into an {@link ImportColumn}
	 * @param headerValue
	 * @return the mapped column or null if ignoring.
	 * @throws GbImportExportInvalidColumnException if columns didn't match any known pattern
	 */
	private static ImportColumn parseHeaderForImportColumn(final String headerValue) throws GbImportExportInvalidColumnException {
		final ImportColumn importColumn = new ImportColumn();

		// assignment with points header
		final Matcher m1 = ASSIGNMENT_WITH_POINTS_PATTERN.matcher(headerValue);
		if (m1.matches()) {

			// extract title and score
			final Matcher titleMatcher = STANDARD_HEADER_PATTERN.matcher(headerValue);
			final Matcher pointsMatcher = POINTS_PATTERN.matcher(headerValue);

			if (titleMatcher.find()) {
				importColumn.setColumnTitle(trim(titleMatcher.group()));
			}
			if (pointsMatcher.find()) {
				importColumn.setPoints(pointsMatcher.group());
			}

			importColumn.setType(ImportColumn.Type.GB_ITEM_WITH_POINTS);

			return importColumn;
		}

		final Matcher m2 = ASSIGNMENT_COMMENT_PATTERN.matcher(headerValue);
		if (m2.matches()) {

			// extract title
			final Matcher titleMatcher = STANDARD_HEADER_PATTERN.matcher(headerValue);

			if (titleMatcher.find()) {
				importColumn.setColumnTitle(trim(titleMatcher.group()));
			}
			importColumn.setType(ImportColumn.Type.COMMENTS);

			return importColumn;
		}

		final Matcher m3 = STANDARD_HEADER_PATTERN.matcher(headerValue);
		if (m3.matches()) {

			importColumn.setColumnTitle(headerValue);
			importColumn.setType(ImportColumn.Type.GB_ITEM_WITHOUT_POINTS);

			return importColumn;
		}

		final Matcher m4 = IGNORE_PATTERN.matcher(headerValue);
		if (m4.matches()) {
			log.info("Found header: " + headerValue + " but ignoring it as it is prefixed with a #.");
			return null;
		}

		// if we got here, couldn't parse the column header, throw an error
		throw new GbImportExportInvalidColumnException("Invalid column header, skipping: " + headerValue);

	}

	/**
	 * Helper to map an Excel {@link Row} to a String[] so we can use the same methods to process it as the CSV
	 *
	 * @param row
	 * @return
	 */
	private static String[] convertRow(final Row row) {

		final int numCells = row.getPhysicalNumberOfCells();
		final String[] s = new String[numCells];

		int i = 0;
		for (final Cell cell : row) {
			// force cell to String
			cell.setCellType(Cell.CELL_TYPE_STRING);
			s[i] = trim(cell.getStringCellValue());
			i++;
		}

		return s;
	}

	/**
	 * Helper to trim a string to null
	 *
	 * @param s
	 * @return
	 */
	private static String trim(final String s) {
		return StringUtils.trimToNull(s);
	}
}


text:
package com.wakeup.qcloud.request;

import static com.google.common.collect.Maps.newHashMap;

import java.util.List;
import java.util.Map;

import com.wakeup.qcloud.domain.UserAttrDO;
import com.wakeup.qcloud.response.QCloudIMResponse;

/**
 * 管理员给用户设置属性。每次最多只能给500个用户设置属性。注意使用前请先定义应用的用户属性。
 * https://www.qcloud.com/document/product/269/4126
 * @since 2017年2月20日
 * @author kalman03
 */
public class IMSetAttrRequest extends AbstractQCloudIMRequest<QCloudIMResponse> {

	private static final long serialVersionUID = -7973614575899011644L;

	private List<UserAttrDO> userAttrs;

	@Override
	public String getApiName() {
		return "openim/im_set_attr";
	}

	@Override
	public Map<String, Object> getTextParams() {
		Map<String, Object> map = newHashMap();
		map.put("UserAttrs", userAttrs);
		return map;
	}

	@Override
	public Class<QCloudIMResponse> getResponseClass() {
		return QCloudIMResponse.class;
	}

}

redpajama_set_name: RedPajamaGithub


text:
using MarginTrading.DataReader.Settings;

namespace MarginTrading.DataReader.Middleware.Validator
{
    public interface IApiKeyValidator
    {
        bool Validate(string apiKey);
    }

    public class ApiKeyValidator : IApiKeyValidator
    {
        private readonly DataReaderSettings _settings;

        public ApiKeyValidator(DataReaderSettings settings)
        {
            _settings = settings;
        }

        public bool Validate(string apiKey)
        {
            return apiKey == _settings.ApiKey;
        }
    }
}


text:
   using System;

public class Program
    {
       public static void Main()
        {
            Spy spy = new Spy();
            string result = spy.StealFieldInfo("Hacker", "username", "password");
            Console.WriteLine(result);
        }
    }


text:
package com.esotericsoftware.yamlbeans.parser;

/**
 * @author Nathan Sweet
 * @author Ola Bini
 */
public class AliasEvent extends NodeEvent {
	public AliasEvent (String anchor) {
		super(EventType.ALIAS, anchor);
	}

	public String toString () {
		return "<" + type + " anchor='" + anchor + "'>";
	}
}


text:
  <form (ngSubmit)="onSubmit()" #harvestForm="ngForm">

      Add Bundles (-ve for remove)
      <input type="number" #editor (keydown)="escape($event)"
          id="editor" class="form-control" required autofocus
          [placeholder]="0" [(ngModel)]="quantity">

    <button type="submit" class="btn btn-default" [disabled]="!harvestForm.form.valid">Save</button>
    <button type="reset" (click)="close()"
        class="btn btn-default">Cancel</button>

  </form>

{{ timeMode() }} Mode

        {{farm.code}}

      +

      Totals

        {{all.farmTotals[farm.code]}}

        {{all.allTotal.quantity}}

        {{plant.code}}

        {{ bundle(farm.code, plant.code) }}

        {{all.plantTotals[plant.code]}}

      +

        {{all.farmTotals[farm.code]}}

        {{all.allTotal.quantity}}


text:
Stacks and Queues, Part 4
=========================

Checking Validity
-----------------

We can also use a stack to check the validity of a math expression.
For this, we want to know: are the parenthesis balanced.
For example, is :code:`(5+5`  balanced?  What about :code:`3 / (4 * (2+4))`

These are easy to check with a stack.  The procedure is as follows:

1. Start a :code:`for` loop over the input string
2. Every time you see a left parentheses, '(', push it onto the stack.
3. Every time you see a right parentheses, ')', pop it from the stack.
4. If the loop ends and there are items left on the stack, that means it's not valid! (there are too many left parentheses)
5. If you see a right parentheses and the stack is empty, it means it's not valid! (there are too many right parentheses)

Finish the function below to accomplish this.  We will use indexing again.

.. code-block:: python
    :linenos:

    from collections import deque

    def validity_checking(in_string):

        stack = queue()

        num_characters = len(in_string)

        for index in range(num_characters):
            current_character = in_string[index]

    assert validity_checking("(x)") == True
    assert validity_checking("((y)") == False
    assert validity_checking("(z))") == False

    assert validity_checking("((a))") == True
    assert validity_checking("((a+b)))") == False
    assert validity_checking("(((42)") == False

When you have finished with this, go on to :doc:`Part 5 <week6_stacksqueues5>`.


text:
var Bot = require('node-telegram-bot');
config = require('./config/config.js'),
CronJob = require('cron').CronJob,
mongoose = require('./config/mongoose'),
Twitter = require('twitter');

db = mongoose();
console.log('Starting app');
var twitter = new Twitter(config.twitter);
var SteamChat = db.model('SteamChat');

var getLatestSales = function(sinceId, maxId, latestTweetId, sales, onFinished){
	var initialRun = false;
	var twitterParams = { "count": config.tweetCount, "screen_name": 'steam_games', "exclude_replies": true, "trim_user": true, "include_rts": false};
	if(sinceId !== null)
	{
		twitterParams.since_id = sinceId;
	} else
	{
		initialRun = true;
		twitterParams.count = 5;
	}
	if(maxId !== null)
	{
		twitterParams.max_id = maxId;
	}

	twitter.get('statuses/user_timeline', twitterParams, function(error, tweets, response){
		if (!error)
		{
			var minId = Infinity;
			saleTweets = tweets.filter(function(tweet){
				if(tweet.id < minId)
				{
					minId = tweet.id;
				}
				if(tweet.id > latestTweetId)
				{
					latestTweetId = tweet.id;
				}
				if(tweet.text.indexOf('sale') !== -1 ||
					tweet.text.indexOf('Sale') !== -1 ||
					tweet.text.indexOf('SALE') !== -1 ||
					tweet.text.indexOf('% off') !== -1 ||
					tweet.text.indexOf('% Off') !== -1 ||
					tweet.text.indexOf('% OFF') !== -1)
				{
					return true;
				} else
				{
					return false;
				}
			});
			if(saleTweets.length === 0 || minId === maxId)
			{
				onFinished(sales);
	} else
	{
		//add tweets and get the next batch
		saleTweets.forEach(function(tweet,ind,arr){
			sales.tweets.push(tweet);
		});

		if(initialRun)
		{

			onFinished(sales);
		} else
		{
			getLatestSales(sinceId,minId-1,latestTweetId,sales,onFinished);
		}
	}

} else {
	console.log(error);
  	//TODO: retry a number of times before giving up
  }
});

};

var checkSteamJob = new CronJob('00 00 */2 * * *', function(){

	console.log('entering job');
	SteamChat.find({}, function(err,docs){

	var latestTweetId = 0;
	var sinceId = Infinity;
	docs.forEach(function(steamChat,ind,arr){
		if(steamChat.latestTweetId < sinceId && steamChat.latestTweetId > 0)
		{
			sinceId = steamChat.latestTweetId;
		}
	});
	maxId = null;
	latestTweetId = sinceId;
	console.log(sinceId);
	var sales = {
			tweets: []
		};

	getLatestSales(sinceId,maxId,latestTweetId,sales,function(sales){
		console.log(sales);
		SteamChat.find({}, function(err,docs){
			docs.forEach(function(steamChat,ind,arr){
				console.log("Sending sales to:");
				console.log(steamChat);
				userTweets = sales.tweets.filter(function(tweet){
					if(tweet.id > steamChat.latestTweetId) return true;
				});
				var userSales = sales;
				userSales.tweets = userTweets;

				userSales.tweets.forEach(function(tweet,ind,arr){
					bot.sendMessage({"chat_id" : steamChat.id , "text" : tweet.text},function(nodifiedPromise){});
					SteamChat.update({"id": steamChat.id}, {$set: {"latestTweetId": tweet.id}}, {"upsert": true}, function(err,result){});
				});

			});
		});

	});

});

}
,function(){
	console.log('job done');
}
,true);

var bot = new Bot({
	token: config.telegram.token
})
.on('message', function (message) {
	console.log(message);
	if(message.hasOwnProperty("text")){
		splitStr = message.text.split(" ");

		if(splitStr[0] === "/steamsale")
		{
			if(splitStr.length === 2)
			{
				if(splitStr[1] === "start")
				{
					var startCallback = function(err,steamChat){

						if(err)
						{
							console.log(err)
							return
						}
						if(steamChat === null)
						{

							SteamChat.update({"id": message.chat.id}, {$set: {"id": message.chat.id, "latestTweetId": 0}}, {"upsert": true, "new": true}, function(err,result){

								bot.sendMessage({"chat_id" : message.chat.id , "text" : "Posting Steam sales to this chat"},function(nodifiedPromise){});
								sinceId = null;
								maxId = null;
								latestTweetId = 0;
								var sales = {
									tweets: [],
									message: message
								};
								getLatestSales(sinceId,maxId,latestTweetId,sales,function(salesResult){
									var maxId = 0;
									salesResult.tweets.forEach(function(tweet,ind,arr){
										bot.sendMessage({"chat_id" : salesResult.message.chat.id , "text" : tweet.text},function(nodifiedPromise){});
										if(tweet.id > maxId){
											maxId = tweet.id;
										}
									});

									SteamChat.update({"id": salesResult.message.chat.id}, {$set: {"latestTweetId": maxId}}, {"upsert": true}, function(err,result){});
								});

							});

						} else
						{
							bot.sendMessage({"chat_id" : message.chat.id , "text" : "This chat is already receiving Steam sales"},function(nodifiedPromise){});
						}

					};
					startCallback.message = message;
					SteamChat.findOne({"id" : message.chat.id},startCallback);
				} else if (splitStr[1] === "stop")
				{
					var stopCallback = function(err,steamChat){
						if(err)
						{
							console.log(err)
							return
						}
						if(steamChat === null)
						{
							bot.sendMessage({"chat_id" : message.chat.id , "text" : "This chat does not receive Steam sales"},function(nodifiedPromise){});
						} else
						{
							bot.sendMessage({"chat_id" : message.chat.id , "text" : "This chat is no longer receiving Steam sales"},function(nodifiedPromise){});
						}
					};
					stopCallback.message = message;
					SteamChat.findOneAndRemove({"id" : message.chat.id},stopCallback);
				}
			}

		}

		if(splitStr[0] === "/start")
		{
			bot.sendMessage({"chat_id" : message.chat.id , "text" : "This bot keeps you posted on latest Steam sales. You can use it individually or add to a group chat.\nUsage:\n/steamsale start : The user or group chat will start receiving Steam sale news. The bot will post some recent sales to kick things off\n/steamsale stop : The user or group chat will stop receiving updates"},function(nodifiedPromise){});
		}

	}
})
.start();


text:
int width = 1024, height = 768;
int FIXED_CURSOR_X = width / 2, FIXED_CURSOR_Y = height / 2;

GLFWwindow *gWindow;
CCamera *gCamera;
CRenderer *gRenderer;
bool gPaused = false;

void UpdateCamera (float deltaTime)
{
    double xpos, ypos;
    glfwGetCursorPos(gWindow, &xpos, &ypos);
    glfwSetCursorPos(gWindow, FIXED_CURSOR_X, FIXED_CURSOR_Y);

    float offsetH = 0, offsetV = 0;

    if (glfwGetKey (gWindow, GLFW_KEY_D) == GLFW_PRESS)
    {
		offsetH = 1;
	}
	else if (glfwGetKey (gWindow, GLFW_KEY_A) == GLFW_PRESS)
    {
		offsetH = -1;
	}

    if (glfwGetKey (gWindow, GLFW_KEY_W) == GLFW_PRESS)
    {
		offsetV = 1;
	}
	else if (glfwGetKey (gWindow, GLFW_KEY_S) == GLFW_PRESS)
    {
		offsetV = -1;
	}
    float rotateH = (float)(FIXED_CURSOR_X - xpos);
    float rotateV = (float)(FIXED_CURSOR_Y - ypos);

	gCamera->Update (deltaTime, CCamera::SUpdateParams (offsetH, offsetV, rotateH, rotateV, glfwGetKey (gWindow, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS));
}

void HandleRenderInput (GLFWwindow *, int key, int , int state, int)
{
	if (state != GLFW_PRESS)
		return;

	switch (key)
	{
	case (GLFW_KEY_P):
	{
		gPaused = !gPaused;
		break;
	}
	case (GLFW_KEY_L):
	{
		gRenderer->DebugSave ("ocean");
		break;
	}
	}
}

int main ()
{
	if (!glfwInit ()) return -1;
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	GLFWwindow *window = glfwCreateWindow (width, height, "miura", nullptr, nullptr);
	if (!window) return -2;
	gWindow = window;

    // with retina display, width/height might change
    glfwGetFramebufferSize (window, &width, &height);
    FIXED_CURSOR_X = width / 2;
    FIXED_CURSOR_Y = height / 2;

	glfwMakeContextCurrent (window);
    glfwSetKeyCallback (window, HandleRenderInput);
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwPollEvents();
    glfwSetCursorPos(window, FIXED_CURSOR_X, FIXED_CURSOR_Y);

    glewExperimental = true;
	if (glewInit () != GLEW_OK) return -3;

    CCamera camera (Math::Degree2Radians(60.0f), float (width) / float (height), 0.1f, 10000.0f);
	gCamera = &camera;
	CRenderer renderer (width, height, camera);
	gRenderer = &renderer;

    double pausedTime = 0;
    double lastTime = glfwGetTime();
	while (!glfwWindowShouldClose (window) && glfwGetKey (window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
	{
        double currentTime = glfwGetTime();
        float deltaTime = float(currentTime - lastTime);
        lastTime = currentTime;

        if (gPaused)
        {
            pausedTime += deltaTime;
        }

        UpdateCamera (deltaTime);
        renderer.Draw ((float)(currentTime - pausedTime), gPaused);

		glfwSwapBuffers (window);
		glfwPollEvents ();
	}

	glfwTerminate ();
	return 0;
}


text:
from __future__ import unicode_literals
import tempfile
import logging

logger = logging.getLogger(__name__)

def demo(test_str='blabla'):

    res =  None
    try:

        logger.info("****** tempfiles *******")

        temp = tempfile.TemporaryFile()
        temp.write(test_str.encode('utf-8'))
        temp.seek(0)
        res = temp.read()
        res = res.decode('utf-8')
        logger.info(res)

    except Exception:
        logger.exception("tempfiles demo failed")
        raise

    finally:
        temp.close()
        return res


text:
package io.druid.segment.realtime.appenderator;

import io.druid.timeline.DataSegment;

import java.io.IOException;
import java.util.Set;

public interface UsedSegmentChecker
{
  /**
   * For any identifiers that exist and are actually used, returns the corresponding DataSegment objects.
   *
   * @param identifiers identifiers to search for
   *
   * @return used DataSegments
   */
  Set<DataSegment> findUsedSegments(Set<SegmentIdentifier> identifiers) throws IOException;
}


text:
import argparse
import pandas as pd
import os
import sumpy
import sumpy.eval

def load_docsets(duc_dir):

    docset_paths = [os.path.join(duc_dir, fname)
                    for fname in os.listdir(duc_dir)]
    docset_paths = [path for path in docset_paths if os.path.isdir(path)]
    docsets = {}
    for docset_path in docset_paths:
        docset_id, docs, models = load_docset(docset_path)
        docsets[docset_id] = {u"docs": docs, u"models": models}
    return docsets

def load_docset(docset_path):
    docset_id = os.path.split(docset_path)[1]
    docs_path = os.path.join(docset_path, u"docs")
    docs = sumpy.io.load_duc_docset(docs_path)
    models = []
    for fname in os.listdir(docset_path):
        if docset_id in fname:
            model_paths = [os.path.join(docset_path, fname, length)
                           for length in [u"200", u"400"]]
            model_sums = sumpy.io.load_duc_abstractive_summaries(model_paths)
            models.extend(model_sums)
    return docset_id, docs, models

def generate_summaries(systems, docsets):
    rouge = sumpy.eval.ROUGE(max_ngrams=2, limit=100, limit_type=u"word")
    results = []
    for docset_id in docsets.keys():
        #print docset_id
        docs = docsets[docset_id][u"docs"]
        models = docsets[docset_id][u"models"]
        sys_sums = [(system_name, unicode(sum_func(docs)))
                    for system_name, sum_func in systems]
        df = rouge.evaluate(sys_sums, models)
        results.append(df)
    return pd.concat(results).groupby(level=0).mean()

def main(duc_dir):
    print u"Loading DUC document sets from:", duc_dir
    docsets = load_docsets(duc_dir)

    lede = lambda x: sumpy.lede(x)
    centroid = lambda x: sumpy.centroid(x)
    lexrank = lambda x: sumpy.lexrank(x)
    systems = [(u"lede", lede), (u"centroid", centroid),
               (u"lexrank", lexrank)]
    print generate_summaries(systems, docsets)

if __name__ == u"__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(u"-d", u"--duc-dir", required=True, type=unicode,
                        help=u"path to DUC document set directory")
    args = parser.parse_args()
    duc_dir = args.duc_dir
    main(duc_dir)


text:
package life.catalogue.api.model;

import java.net.URI;
import java.time.LocalDate;
import java.util.Objects;

import life.catalogue.api.vocab.License;
import life.catalogue.api.vocab.MediaType;

public class Media extends DatasetScopedEntity<Integer> implements Referenced, VerbatimEntity {

  private Integer verbatimKey;
  private URI url;
  private MediaType type;
  private String format;
  private String title;
  private LocalDate captured;
  private String capturedBy;
  private License license;
  private URI link;
  private String referenceId;

  @Override
  public Integer getVerbatimKey() {
    return verbatimKey;
  }

  @Override
  public void setVerbatimKey(Integer verbatimKey) {
    this.verbatimKey = verbatimKey;
  }

  public URI getUrl() {
    return url;
  }

  public void setUrl(URI url) {
    this.url = url;
  }

  public MediaType getType() {
    return type;
  }

  public void setType(MediaType type) {
    this.type = type;
  }

  public String getFormat() {
    return format;
  }

  public void setFormat(String format) {
    this.format = format;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public LocalDate getCaptured() {
    return captured;
  }

  public void setCaptured(LocalDate captured) {
    this.captured = captured;
  }

  public String getCapturedBy() {
    return capturedBy;
  }

  public void setCapturedBy(String capturedBy) {
    this.capturedBy = capturedBy;
  }

  public License getLicense() {
    return license;
  }

  public void setLicense(License license) {
    this.license = license;
  }

  public URI getLink() {
    return link;
  }

  public void setLink(URI link) {
    this.link = link;
  }

  @Override
  public String getReferenceId() {
    return referenceId;
  }

  @Override
  public void setReferenceId(String referenceId) {
    this.referenceId = referenceId;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    if (!super.equals(o)) return false;
    Media media = (Media) o;
    return Objects.equals(verbatimKey, media.verbatimKey) &&
        Objects.equals(url, media.url) &&
        type == media.type &&
        Objects.equals(format, media.format) &&
        Objects.equals(title, media.title) &&
        Objects.equals(captured, media.captured) &&
        Objects.equals(capturedBy, media.capturedBy) &&
        license == media.license &&
        Objects.equals(link, media.link) &&
        Objects.equals(referenceId, media.referenceId);
  }

  @Override
  public int hashCode() {
    return Objects.hash(super.hashCode(), verbatimKey, url, type, format, title, captured, capturedBy, license, link, referenceId);
  }
}


text:
Simulates and represents some of the traditional sequential sorting algorithms. Developed some contributed algorithms by merging two or more algorithms, or by applying parallel programming concepts by dividing the sorting task into small tasks and distributing them between available processors equally without any conflict between them to get better results.

The base class of all sorting algorithm has set of methods that help counting the comparisons and swaps operations, in addition to calculate the time complexity of each step by adding time unit(s) to the algorithm complexity.

Applet interfaces are used to clarify and demonstrate each algorithm sorting mechanism, also more than one Applet can be used in a single page to compare different algorithms.

•	Use Applet to simulate sorts algorithms.
•	Implements a multi-threaded algorithm, that calculate the time and space complexity.

## Bugtracker ##
Issued and bugs are tracked on [github.com].

### Todos
Waiting for your contributions

### License

	Apache License

	Copyright (C) 2013 Hudhaifa Shatnawi

	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.

   [github.com]: <http://github.com/hudhaifas/sort-framework/issues>


text:
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
import {UserService} from '../../services/user.service';
import {Location} from '@angular/common';
import 'rxjs/add/operator/switchMap';

@Component({
    selector: 'app-user-detail',
    templateUrl: './user-detail.component.html',
    styleUrls: ['./user-detail.component.css']
})
export class UserDetailComponent implements OnInit {

    user: any;
    constructor(
        private route: ActivatedRoute,
        private location: Location,
        private userService: UserService
    ) {}

    ngOnInit() {
        //Find User detail by user-id
        this.findUserByUserId();
    }

    //Function load a user infomation whare match parameter id
    //Function for view page
    findUserByUserId() {
        this.route.params
            .switchMap((params: Params) => this.userService.findUserByUserId(+params['user-id']))
            .subscribe(info => this.user = info);
    }

    /**
     *
     * Function go back when click the back button
     * @author sarawutt.b
     */
    goBack() {
        this.location.back();
    }

}


text:
#include <aws/mediaconvert/model/XavcSettings.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace MediaConvert
{
namespace Model
{

XavcSettings::XavcSettings() :
    m_adaptiveQuantization(XavcAdaptiveQuantization::NOT_SET),
    m_adaptiveQuantizationHasBeenSet(false),
    m_entropyEncoding(XavcEntropyEncoding::NOT_SET),
    m_entropyEncodingHasBeenSet(false),
    m_framerateControl(XavcFramerateControl::NOT_SET),
    m_framerateControlHasBeenSet(false),
    m_framerateConversionAlgorithm(XavcFramerateConversionAlgorithm::NOT_SET),
    m_framerateConversionAlgorithmHasBeenSet(false),
    m_framerateDenominator(0),
    m_framerateDenominatorHasBeenSet(false),
    m_framerateNumerator(0),
    m_framerateNumeratorHasBeenSet(false),
    m_profile(XavcProfile::NOT_SET),
    m_profileHasBeenSet(false),
    m_slowPal(XavcSlowPal::NOT_SET),
    m_slowPalHasBeenSet(false),
    m_softness(0),
    m_softnessHasBeenSet(false),
    m_spatialAdaptiveQuantization(XavcSpatialAdaptiveQuantization::NOT_SET),
    m_spatialAdaptiveQuantizationHasBeenSet(false),
    m_temporalAdaptiveQuantization(XavcTemporalAdaptiveQuantization::NOT_SET),
    m_temporalAdaptiveQuantizationHasBeenSet(false),
    m_xavc4kIntraCbgProfileSettingsHasBeenSet(false),
    m_xavc4kIntraVbrProfileSettingsHasBeenSet(false),
    m_xavc4kProfileSettingsHasBeenSet(false),
    m_xavcHdIntraCbgProfileSettingsHasBeenSet(false),
    m_xavcHdProfileSettingsHasBeenSet(false)
{
}

XavcSettings::XavcSettings(JsonView jsonValue) :
    m_adaptiveQuantization(XavcAdaptiveQuantization::NOT_SET),
    m_adaptiveQuantizationHasBeenSet(false),
    m_entropyEncoding(XavcEntropyEncoding::NOT_SET),
    m_entropyEncodingHasBeenSet(false),
    m_framerateControl(XavcFramerateControl::NOT_SET),
    m_framerateControlHasBeenSet(false),
    m_framerateConversionAlgorithm(XavcFramerateConversionAlgorithm::NOT_SET),
    m_framerateConversionAlgorithmHasBeenSet(false),
    m_framerateDenominator(0),
    m_framerateDenominatorHasBeenSet(false),
    m_framerateNumerator(0),
    m_framerateNumeratorHasBeenSet(false),
    m_profile(XavcProfile::NOT_SET),
    m_profileHasBeenSet(false),
    m_slowPal(XavcSlowPal::NOT_SET),
    m_slowPalHasBeenSet(false),
    m_softness(0),
    m_softnessHasBeenSet(false),
    m_spatialAdaptiveQuantization(XavcSpatialAdaptiveQuantization::NOT_SET),
    m_spatialAdaptiveQuantizationHasBeenSet(false),
    m_temporalAdaptiveQuantization(XavcTemporalAdaptiveQuantization::NOT_SET),
    m_temporalAdaptiveQuantizationHasBeenSet(false),
    m_xavc4kIntraCbgProfileSettingsHasBeenSet(false),
    m_xavc4kIntraVbrProfileSettingsHasBeenSet(false),
    m_xavc4kProfileSettingsHasBeenSet(false),
    m_xavcHdIntraCbgProfileSettingsHasBeenSet(false),
    m_xavcHdProfileSettingsHasBeenSet(false)
{
  *this = jsonValue;
}

XavcSettings& XavcSettings::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("adaptiveQuantization"))
  {
    m_adaptiveQuantization = XavcAdaptiveQuantizationMapper::GetXavcAdaptiveQuantizationForName(jsonValue.GetString("adaptiveQuantization"));

    m_adaptiveQuantizationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("entropyEncoding"))
  {
    m_entropyEncoding = XavcEntropyEncodingMapper::GetXavcEntropyEncodingForName(jsonValue.GetString("entropyEncoding"));

    m_entropyEncodingHasBeenSet = true;
  }

  if(jsonValue.ValueExists("framerateControl"))
  {
    m_framerateControl = XavcFramerateControlMapper::GetXavcFramerateControlForName(jsonValue.GetString("framerateControl"));

    m_framerateControlHasBeenSet = true;
  }

  if(jsonValue.ValueExists("framerateConversionAlgorithm"))
  {
    m_framerateConversionAlgorithm = XavcFramerateConversionAlgorithmMapper::GetXavcFramerateConversionAlgorithmForName(jsonValue.GetString("framerateConversionAlgorithm"));

    m_framerateConversionAlgorithmHasBeenSet = true;
  }

  if(jsonValue.ValueExists("framerateDenominator"))
  {
    m_framerateDenominator = jsonValue.GetInteger("framerateDenominator");

    m_framerateDenominatorHasBeenSet = true;
  }

  if(jsonValue.ValueExists("framerateNumerator"))
  {
    m_framerateNumerator = jsonValue.GetInteger("framerateNumerator");

    m_framerateNumeratorHasBeenSet = true;
  }

  if(jsonValue.ValueExists("profile"))
  {
    m_profile = XavcProfileMapper::GetXavcProfileForName(jsonValue.GetString("profile"));

    m_profileHasBeenSet = true;
  }

  if(jsonValue.ValueExists("slowPal"))
  {
    m_slowPal = XavcSlowPalMapper::GetXavcSlowPalForName(jsonValue.GetString("slowPal"));

    m_slowPalHasBeenSet = true;
  }

  if(jsonValue.ValueExists("softness"))
  {
    m_softness = jsonValue.GetInteger("softness");

    m_softnessHasBeenSet = true;
  }

  if(jsonValue.ValueExists("spatialAdaptiveQuantization"))
  {
    m_spatialAdaptiveQuantization = XavcSpatialAdaptiveQuantizationMapper::GetXavcSpatialAdaptiveQuantizationForName(jsonValue.GetString("spatialAdaptiveQuantization"));

    m_spatialAdaptiveQuantizationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("temporalAdaptiveQuantization"))
  {
    m_temporalAdaptiveQuantization = XavcTemporalAdaptiveQuantizationMapper::GetXavcTemporalAdaptiveQuantizationForName(jsonValue.GetString("temporalAdaptiveQuantization"));

    m_temporalAdaptiveQuantizationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("xavc4kIntraCbgProfileSettings"))
  {
    m_xavc4kIntraCbgProfileSettings = jsonValue.GetObject("xavc4kIntraCbgProfileSettings");

    m_xavc4kIntraCbgProfileSettingsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("xavc4kIntraVbrProfileSettings"))
  {
    m_xavc4kIntraVbrProfileSettings = jsonValue.GetObject("xavc4kIntraVbrProfileSettings");

    m_xavc4kIntraVbrProfileSettingsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("xavc4kProfileSettings"))
  {
    m_xavc4kProfileSettings = jsonValue.GetObject("xavc4kProfileSettings");

    m_xavc4kProfileSettingsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("xavcHdIntraCbgProfileSettings"))
  {
    m_xavcHdIntraCbgProfileSettings = jsonValue.GetObject("xavcHdIntraCbgProfileSettings");

    m_xavcHdIntraCbgProfileSettingsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("xavcHdProfileSettings"))
  {
    m_xavcHdProfileSettings = jsonValue.GetObject("xavcHdProfileSettings");

    m_xavcHdProfileSettingsHasBeenSet = true;
  }

  return *this;
}

JsonValue XavcSettings::Jsonize() const
{
  JsonValue payload;

  if(m_adaptiveQuantizationHasBeenSet)
  {
   payload.WithString("adaptiveQuantization", XavcAdaptiveQuantizationMapper::GetNameForXavcAdaptiveQuantization(m_adaptiveQuantization));
  }

  if(m_entropyEncodingHasBeenSet)
  {
   payload.WithString("entropyEncoding", XavcEntropyEncodingMapper::GetNameForXavcEntropyEncoding(m_entropyEncoding));
  }

  if(m_framerateControlHasBeenSet)
  {
   payload.WithString("framerateControl", XavcFramerateControlMapper::GetNameForXavcFramerateControl(m_framerateControl));
  }

  if(m_framerateConversionAlgorithmHasBeenSet)
  {
   payload.WithString("framerateConversionAlgorithm", XavcFramerateConversionAlgorithmMapper::GetNameForXavcFramerateConversionAlgorithm(m_framerateConversionAlgorithm));
  }

  if(m_framerateDenominatorHasBeenSet)
  {
   payload.WithInteger("framerateDenominator", m_framerateDenominator);

  }

  if(m_framerateNumeratorHasBeenSet)
  {
   payload.WithInteger("framerateNumerator", m_framerateNumerator);

  }

  if(m_profileHasBeenSet)
  {
   payload.WithString("profile", XavcProfileMapper::GetNameForXavcProfile(m_profile));
  }

  if(m_slowPalHasBeenSet)
  {
   payload.WithString("slowPal", XavcSlowPalMapper::GetNameForXavcSlowPal(m_slowPal));
  }

  if(m_softnessHasBeenSet)
  {
   payload.WithInteger("softness", m_softness);

  }

  if(m_spatialAdaptiveQuantizationHasBeenSet)
  {
   payload.WithString("spatialAdaptiveQuantization", XavcSpatialAdaptiveQuantizationMapper::GetNameForXavcSpatialAdaptiveQuantization(m_spatialAdaptiveQuantization));
  }

  if(m_temporalAdaptiveQuantizationHasBeenSet)
  {
   payload.WithString("temporalAdaptiveQuantization", XavcTemporalAdaptiveQuantizationMapper::GetNameForXavcTemporalAdaptiveQuantization(m_temporalAdaptiveQuantization));
  }

  if(m_xavc4kIntraCbgProfileSettingsHasBeenSet)
  {
   payload.WithObject("xavc4kIntraCbgProfileSettings", m_xavc4kIntraCbgProfileSettings.Jsonize());

  }

  if(m_xavc4kIntraVbrProfileSettingsHasBeenSet)
  {
   payload.WithObject("xavc4kIntraVbrProfileSettings", m_xavc4kIntraVbrProfileSettings.Jsonize());

  }

  if(m_xavc4kProfileSettingsHasBeenSet)
  {
   payload.WithObject("xavc4kProfileSettings", m_xavc4kProfileSettings.Jsonize());

  }

  if(m_xavcHdIntraCbgProfileSettingsHasBeenSet)
  {
   payload.WithObject("xavcHdIntraCbgProfileSettings", m_xavcHdIntraCbgProfileSettings.Jsonize());

  }

  if(m_xavcHdProfileSettingsHasBeenSet)
  {
   payload.WithObject("xavcHdProfileSettings", m_xavcHdProfileSettings.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace MediaConvert
} // namespace Aws


text:
.. _diagram:

dj-webmachine decision flow
---------------------------

This diagram is illustrative of the flow of processing that a :ref:`webmachine resource <resources>`
goes through from inception to response.

Original com from `webmachine site <http://webmachine.basho.com/diagram.html>`_.

.. image:: _static/http-headers-status-v3.png


text:
#ifndef ALIANALYSISTASKEVENTSELECTIONREF_H
#define ALIANALYSISTASKEVENTSELECTIONREF_H

#include "AliAnalysisTaskSE.h"

class TArrayD;
class TClonesArray;
class THistManager;
class TObjArray;
class TString;

class AliAnalysisUtils;
class AliAODTrack;
class AliESDtrack;
class AliESDtrackCuts;
class AliEMCALTriggerPatchInfo;
class AliEMCALGeometry;
class AliVCluster;
class AliVTrack;

namespace PWGJE {

namespace EMCALJetTasks {

class AliEmcalTriggerOfflineSelection;

class AliAnalysisTaskEventSelectionRef : public AliAnalysisTaskSE {
public:
  AliAnalysisTaskEventSelectionRef();
  AliAnalysisTaskEventSelectionRef(const char *name);
  virtual ~AliAnalysisTaskEventSelectionRef();

  virtual void UserCreateOutputObjects();
  virtual void UserExec(Option_t *);

  void SetOfflineTriggerSelection(AliEmcalTriggerOfflineSelection *sel) { fTriggerSelection = sel; }
  void SetClusterContainer(TString name) { fClusterContainerName = name; }

protected:
  void FillEventCounterHists(const char *triggerclass, double vtxz, bool isSelected, bool isOfflineSelected);

  void ProcessTrack(const char *triggerclass, const AliVTrack * track, bool isOfflineSelected);
  void ProcessCluster(const char *triggerclass, const AliVCluster *clust, bool isOfflineSelected);
  void ProcessOfflinePatch(const char * triggerclass, const AliEMCALTriggerPatchInfo * patch, bool isOfflineSelected);

  Bool_t TrackSelectionESD(AliESDtrack* track) ;
  Bool_t TrackSelectionAOD(AliAODTrack* track);

  void CreatePtBinning(TArrayD& binning) const;
  void CreateEnergyBinning(TArrayD& binning) const;

  TString                       fClusterContainerName;
  AliAnalysisUtils              *fAnalysisUtils;
  AliEmcalTriggerOfflineSelection *fTriggerSelection;
  AliESDtrackCuts               *fTrackCuts;
  THistManager                  *fHistos;                   //!
  AliEMCALGeometry              *fGeometry;                 //!
  TClonesArray                  *fTriggerPatchContainer;    //!
  TClonesArray                  *fClusterContainer;         //!
  TObjArray                     *fTrackContainer;           //!

private:

  AliAnalysisTaskEventSelectionRef(const AliAnalysisTaskEventSelectionRef &);
  AliAnalysisTaskEventSelectionRef &operator=(const AliAnalysisTaskEventSelectionRef &);

  ClassDef(AliAnalysisTaskEventSelectionRef, 1);
};

} /* namespace EMCALTriggerJets */

} /* namespace PWGJE */

#endif


text:
from cms.extensions import PageExtension, TitleExtension
from cms.extensions.extension_pool import extension_pool
from cms.models import Page, Title
from django.core.cache import cache
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _
from taggit_autosuggest.managers import TaggableManager

from .utils import get_cache_key

@extension_pool.register
class PageTags(PageExtension):
    tags = TaggableManager()

    def copy_relations(self, oldinstance, language):
        """Copy relation data on page publishc."""
        self.tags.set(oldinstance.tags.all())

    class Meta:
        verbose_name = _("Page tags (all languages)")

@extension_pool.register
class TitleTags(TitleExtension):
    tags = TaggableManager()

    def copy_relations(self, oldinstance, language):
        """Copy relation data on page publish."""
        self.tags.set(oldinstance.tags.all())

    class Meta:
        verbose_name = _("Page tags (language-dependent)")

# Cache cleanup when deleting pages / editing page extensions
@receiver(pre_delete, sender=Page)
def cleanup_page(sender, instance, **kwargs):
    site_id = instance.node.site_id
    key = get_cache_key(None, instance, "", site_id, False)
    cache.delete(key)

@receiver(pre_delete, sender=Title)
def cleanup_title(sender, instance, **kwargs):
    site_id = instance.page.node.site_id
    key = get_cache_key(None, instance.page, instance.language, site_id, True)
    cache.delete(key)

@receiver(post_save, sender=PageTags)
def cleanup_pagetags(sender, instance, **kwargs):
    site_id = instance.extended_object.node.site_id
    key = get_cache_key(None, instance.extended_object, "", site_id, False)
    cache.delete(key)

@receiver(post_save, sender=TitleTags)
def cleanup_titletags(sender, instance, **kwargs):
    site_id = instance.extended_object.page.node.site_id
    key = get_cache_key(None, instance.extended_object.page, instance.extended_object.language, site_id, True)
    cache.delete(key)


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE124_Buffer_Underwrite__CWE839_fgets_53b.c
Label Definition File: CWE124_Buffer_Underwrite__CWE839.label.xml
Template File: sources-sinks-53b.tmpl.c
*/
/*
 * @description
 * CWE: 124 Buffer Underwrite
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: Non-negative but less than 10
 * Sinks:
 *    GoodSink: Ensure the array index is valid
 *    BadSink : Improperly check the array index by not checking the lower bound
 * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
 *
 * */

#include "std_testcase.h"

#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)

#ifndef OMITBAD

/* bad function declaration */
void CWE124_Buffer_Underwrite__CWE839_fgets_53c_badSink(int data);

void CWE124_Buffer_Underwrite__CWE839_fgets_53b_badSink(int data)
{
    CWE124_Buffer_Underwrite__CWE839_fgets_53c_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE124_Buffer_Underwrite__CWE839_fgets_53c_goodG2BSink(int data);

void CWE124_Buffer_Underwrite__CWE839_fgets_53b_goodG2BSink(int data)
{
    CWE124_Buffer_Underwrite__CWE839_fgets_53c_goodG2BSink(data);
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE124_Buffer_Underwrite__CWE839_fgets_53c_goodB2GSink(int data);

void CWE124_Buffer_Underwrite__CWE839_fgets_53b_goodB2GSink(int data)
{
    CWE124_Buffer_Underwrite__CWE839_fgets_53c_goodB2GSink(data);
}

#endif /* OMITGOOD */


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveSupport::Notifications</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.0.0

            Module
            ActiveSupport::Notifications

/usr/local/rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/notifications.rb

/usr/local/rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/notifications/fanout.rb

/usr/local/rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/notifications/instrumenter.rb

Notifications

ActiveSupport::Notifications provides an instrumentation API
for Ruby.

Instrumenters

To instrument an event you just need to do:

ActiveSupport::Notifications.instrument('render', extra: :information) do
  render text: 'Foo'
end

That executes the block first and notifies all subscribers once done.

In the example above render is the name of the event, and the
rest is called the payload. The payload is a mechanism that allows
instrumenters to pass extra information to subscribers. Payloads consist of
a hash whose contents are arbitrary and generally depend on the event.

Subscribers

You can consume those events and the information they provide by
registering a subscriber.

ActiveSupport::Notifications.subscribe('render') do |name, start, finish, id, payload|
  name    # => String, name of the event (such as 'render' from above)
  start   # => Time, when the instrumented block started execution
  finish  # => Time, when the instrumented block ended execution
  id      # => String, unique ID for this notification
  payload # => Hash, the payload
end

For instance, let's store all "render" events in an array:

events = []

ActiveSupport::Notifications.subscribe('render') do |*args|
  events << ActiveSupport::Notifications::Event.new(*args)
end

That code returns right away, you are just subscribing to "render" events.
The block is saved and will be called whenever someone instruments
"render":

ActiveSupport::Notifications.instrument('render', extra: :information) do
  render text: 'Foo'
end

event = events.first
event.name      # => "render"
event.duration  # => 10 (in milliseconds)
event.payload   # => { extra: :information }

The block in the subscribe call gets the name of the event,
start timestamp, end timestamp, a string with a unique identifier for that
event (something like "535801666f04d0298cd6"), and a hash with the payload,
in that order.

If an exception happens during that particular instrumentation the payload
will have a key :exception with an array of two elements as
value: a string with the name of the exception class, and the exception
message.

As the previous example depicts, the class
ActiveSupport::Notifications::Event is able to take the
arguments as they come and provide an object-oriented interface to that
data.

It is also possible to pass an object as the second parameter passed to the
subscribe method instead of a block:

module ActionController
  class PageRequest
    def call(name, started, finished, unique_id, payload)
      Rails.logger.debug ['notification:', name, started, finished, unique_id, payload].join(' ')
    end
  end
end

ActiveSupport::Notifications.subscribe('process_action.action_controller', ActionController::PageRequest.new)

resulting in the following output within the logs including a hash with the
payload:

notification: process_action.action_controller 2012-04-13 01:08:35 +0300 2012-04-13 01:08:35 +0300 af358ed7fab884532ec7 {
   controller: "Devise::SessionsController",
   action: "new",
   params: {"action"=>"new", "controller"=>"devise/sessions"},
   format: :html,
   method: "GET",
   path: "/login/sign_in",
   status: 200,
   view_runtime: 279.3080806732178,
   db_runtime: 40.053
 }

You can also subscribe to all events whose name matches a certain regexp:

ActiveSupport::Notifications.subscribe(/render/) do |*args|
  ...
end

and even pass no argument to subscribe, in which case you are
subscribing to all events.

Temporary Subscriptions

Sometimes you do not want to subscribe to an event for the entire life of
the application. There are two ways to unsubscribe.

WARNING: The instrumentation framework is designed for long-running
subscribers, use this feature sparingly because it wipes some internal
caches and that has a negative impact on performance.

Subscribe While a Block Runs

You can subscribe to some event temporarily while some block runs. For
example, in

callback = lambda {|*args| ... }
ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do
  ...
end

the callback will be called for all "sql.active_record" events instrumented
during the execution of the block. The callback is unsubscribed
automatically after that.

Manual Unsubscription

The subscribe method returns a subscriber object:

subscriber = ActiveSupport::Notifications.subscribe("render") do |*args|
  ...
end

To prevent that block from being called anymore, just unsubscribe passing
that reference:

ActiveSupport::Notifications.unsubscribe(subscriber)

Default Queue

Notifications ships with a queue
implementation that consumes and publish events to log subscribers in a
thread. You can use any queue implementation you want.

Namespace

          CLASS
          ActiveSupport::Notifications::Event

          CLASS
          ActiveSupport::Notifications::Fanout

          CLASS
          ActiveSupport::Notifications::Instrumenter

Methods

I

                instrument,

                instrumenter

P

                publish

S

                subscribe,

                subscribed

U

                unsubscribe

Attributes

              [RW]

            notifier

Class Public methods

              instrument(name, payload = {})

            Link

                Source:
                show

# File /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/notifications.rb, line 157
def instrument(name, payload = {})
  if notifier.listening?(name)
    instrumenter.instrument(name, payload) { yield payload if block_given? }
  else
    yield payload if block_given?
  end
end

              instrumenter()

            Link

                Source:
                show

# File /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/notifications.rb, line 180
def instrumenter
  InstrumentationRegistry.instrumenter_for(notifier)
end

              publish(name, *args)

            Link

                Source:
                show

# File /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/notifications.rb, line 153
def publish(name, *args)
  notifier.publish(name, *args)
end

              subscribe(*args, &block)

            Link

                Source:
                show

# File /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/notifications.rb, line 165
def subscribe(*args, &block)
  notifier.subscribe(*args, &block)
end

              subscribed(callback, *args, &block)

            Link

                Source:
                show

# File /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/notifications.rb, line 169
def subscribed(callback, *args, &block)
  subscriber = subscribe(*args, &callback)
  yield
ensure
  unsubscribe(subscriber)
end

              unsubscribe(args)

            Link

                Source:
                show

# File /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activesupport-4.0.0/lib/active_support/notifications.rb, line 176
def unsubscribe(args)
  notifier.unsubscribe(args)
end


text:
<!DOCTYPE html>

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

    <meta charset="utf-8">

AWS Elastic Beanstalk Application MaxCountRule

The
                        MaxCountRule property type specifies a lifecycle rule that deletes the oldest application version
                        when the maximum count is exceeded for an AWS Elastic Beanstalk application.

                        MaxCountRule is a property of the ApplicationVersionLifecycleConfig property type.

Syntax

To declare this entity in your AWS CloudFormation template, use the following syntax:

JSON

{
  "DeleteSourceFromS3" : Boolean,
  "Enabled" : Boolean,
  "MaxCount" : Integer
}

YAML

DeleteSourceFromS3: Boolean
Enabled: Boolean
MaxCount: Integer

Properties

DeleteSourceFromS3

Set to true to delete a version's source bundle from Amazon S3 when Elastic Beanstalk deletes
                                 the application version.

                                 Required: No

                                 Type: Boolean

                                 Update requires:

                                 No interruption

Enabled

Specify true to apply the rule, or false to disable it.

                                 Required: No

                                 Type: Boolean

                                 Update requires:

                                 No interruption

MaxCount

Specify the maximum number of application versions to retain.

                                 Required: No

                                 Type: Integer

                                 Update requires:

                                 No interruption


text:
package cz.startnet.utils.pgdiff.parsers;

import cz.startnet.utils.pgdiff.Resources;
import cz.startnet.utils.pgdiff.schema.PgDatabase;
import cz.startnet.utils.pgdiff.schema.PgSchema;
import cz.startnet.utils.pgdiff.schema.PgSequence;
import java.text.MessageFormat;

/**
 * Parses CREATE SEQUENCE statements.
 *
 * @author fordfrog
 */
public class CreateSequenceParser {

    /**
     * Parses CREATE SEQUENCE statement.
     *
     * @param database  database
     * @param statement CREATE SEQUENCE statement
     */
    public static void parse(final PgDatabase database,
            final String statement) {
        final Parser parser = new Parser(statement);
        parser.expect("CREATE", "SEQUENCE");
        parser.expectOptional("IF", "NOT", "EXISTS");

        final String sequenceName = parser.parseIdentifier();
        final PgSequence sequence =
                new PgSequence(ParserUtils.getObjectName(sequenceName));
        final String schemaName =
                ParserUtils.getSchemaName(sequenceName, database);
        final PgSchema schema = database.getSchema(schemaName);

        if (schema == null) {
            throw new RuntimeException(MessageFormat.format(
                    Resources.getString("CannotFindSchema"), schemaName,
                    statement));
        }

        schema.addSequence(sequence);

        while (!parser.expectOptional(";")) {
            if (parser.expectOptional("AS")) {
                sequence.setDataType(parser.parseString());
            } else if (parser.expectOptional("INCREMENT")) {
                parser.expectOptional("BY");
                sequence.setIncrement(parser.parseString());
            } else if (parser.expectOptional("MINVALUE")) {
                sequence.setMinValue(parser.parseString());
            } else if (parser.expectOptional("MAXVALUE")) {
                sequence.setMaxValue(parser.parseString());
            } else if (parser.expectOptional("START")) {
                parser.expectOptional("WITH");
                sequence.setStartWith(parser.parseString());
            } else if (parser.expectOptional("CACHE")) {
                sequence.setCache(parser.parseString());
            } else if (parser.expectOptional("CYCLE")) {
                sequence.setCycle(true);
            } else if (parser.expectOptional("OWNED", "BY")) {
                if (parser.expectOptional("NONE")) {
                    sequence.setOwnedBy(null);
                } else {
                    sequence.setOwnedBy(ParserUtils.getObjectName(
                            parser.parseIdentifier()));
                }
            } else if (parser.expectOptional("NO")) {
                if (parser.expectOptional("MINVALUE")) {
                    sequence.setMinValue(null);
                } else if (parser.expectOptional("MAXVALUE")) {
                    sequence.setMaxValue(null);
                } else if (parser.expectOptional("CYCLE")) {
                    sequence.setCycle(false);
                } else {
                    parser.throwUnsupportedCommand();
                }
            } else {
                parser.throwUnsupportedCommand();
            }
        }
    }

    /**
     * Creates a new instance of CreateSequenceParser.
     */
    private CreateSequenceParser() {
    }
}


text:
use std::fmt;

use graphql_ir::Argument;
use graphql_ir::ConstantValue;
use graphql_ir::Value;
use intern::Lookup;

use crate::murmurhash::murmurhash;

pub fn hash_arguments(args: &[Argument]) -> Option<String> {
    if args.is_empty() {
        None
    } else {
        let mut converted_args: Vec<_> = args
            .iter()
            .map(|arg| HashArgument {
                name: arg.name.item.0.lookup(),
                value: identifier_for_argument_value(&arg.value.item),
            })
            .collect();
        converted_args.sort_by(|a, b| a.name.cmp(b.name));

        let args_string = format!(
            "[{}]",
            converted_args
                .iter()
                .map(|item| item.to_string())
                .collect::<Vec<String>>()
                .join(",")
        );
        Some(murmurhash(&args_string))
    }
}

#[derive(Debug)]
struct HashArgument {
    name: &'static str,
    value: IdentiferValue,
}

impl fmt::Display for HashArgument {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{{\"name\":\"{}\",\"value\":{}}}", self.name, self.value)
    }
}

#[derive(Debug)]
enum IdentiferValue {
    Variable(&'static str),
    Value(String),
    List(Vec<IdentiferValue>),
    Object(Vec<IdentiferObjectProperty>),
}

impl fmt::Display for IdentiferValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self {
            IdentiferValue::Variable(var) => write!(f, "{{\"variable\":\"{}\"}}", var),
            IdentiferValue::Value(val) => write!(f, "{{\"value\":{}}}", val),
            IdentiferValue::Object(obj) => write!(
                f,
                "{{\"object\":{{{}}}}}",
                obj.iter()
                    .map(|item| item.to_string())
                    .collect::<Vec<String>>()
                    .join(",")
            ),
            IdentiferValue::List(list) => write!(
                f,
                "{{\"list\":[{}]}}",
                list.iter()
                    .map(|item| item.to_string())
                    .collect::<Vec<String>>()
                    .join(",")
            ),
        }
    }
}

#[derive(Debug)]
struct IdentiferObjectProperty {
    name: &'static str,
    value: IdentiferValue,
}

impl fmt::Display for IdentiferObjectProperty {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{{\"name\":\"{}\",\"value\":{}}}", self.name, self.value)
    }
}

fn build_constant_value_string(value: &ConstantValue) -> String {
    match value {
        ConstantValue::Int(val) => val.to_string(),
        ConstantValue::Float(val) => val.to_string(),
        ConstantValue::String(val) => format!("\"{}\"", val),
        ConstantValue::Boolean(val) => val.to_string(),
        ConstantValue::Null() => "null".to_string(),
        ConstantValue::Enum(val) => format!("\"{}\"", val),
        ConstantValue::List(val_list) => {
            let json_values = val_list
                .iter()
                .map(|val| build_constant_value_string(val))
                .collect::<Vec<_>>();

            format!("[{}]", json_values.join(","))
        }
        ConstantValue::Object(val_object) => {
            let mut rows: Vec<String> = Vec::with_capacity(val_object.len());
            for arg in val_object.iter() {
                let field_name = arg.name.item;
                rows.push(format!(
                    "\"{}\":{}",
                    field_name,
                    build_constant_value_string(&arg.value.item)
                ));
            }
            format!("{{{}}}", rows.join(","))
        }
    }
}

fn identifier_for_argument_value(value: &Value) -> IdentiferValue {
    match value {
        Value::Constant(value) => IdentiferValue::Value(build_constant_value_string(value)),
        Value::Variable(variable) => IdentiferValue::Variable(variable.name.item.0.lookup()),
        Value::List(items) => {
            IdentiferValue::List(items.iter().map(identifier_for_argument_value).collect())
        }
        Value::Object(entries) => IdentiferValue::Object(
            entries
                .iter()
                .map(|entry| IdentiferObjectProperty {
                    name: entry.name.item.0.lookup(),
                    value: identifier_for_argument_value(&entry.value.item),
                })
                .collect(),
        ),
    }
}


text:
SYNONYM

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

#### Published in
Comm. Soc. crittog. Ital. 1: 175 (1862)

#### Original name
Hydnum omasum Panizzi, 1862

### Remarks
null


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AnsiDecorationProvider (Airline - IO Library 2.9.0 API)</title>
<meta name="date" content="2022-08-03">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.github.rvesse.airline.io.decorations

Interface AnsiDecorationProvider

All Known Implementing Classes:

BasicDecoration

public interface AnsiDecorationProvider

Interface for classes that provide ANSI decorations

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

String
getAnsiDecorationDisabledControlCode()

Gets the ANSI control code for disabling a decoration

String
getAnsiDecorationEnabledControlCode()

Gets the ANSI control code for enabling a decoration

Method Detail

getAnsiDecorationEnabledControlCode

String getAnsiDecorationEnabledControlCode()

Gets the ANSI control code for enabling a decoration

Returns:

Control code

getAnsiDecorationDisabledControlCode

String getAnsiDecorationDisabledControlCode()

Gets the ANSI control code for disabling a decoration

Returns:

Control Code

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2012–2022. All rights reserved.


text:
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using MonoDevelop.Core;

namespace Olo.BuildTools
{
	class SystemInfo : IApplication
	{
		public Task<int> Run(string[] arguments)
		{
			var systemInformationSummary = SystemInformation.GetTextDescription();

			if (!arguments.Any())
				printHelp();

			foreach (var argument in arguments)
			{
				if (argument == "-c")
					Console.WriteLine(systemInformationSummary);
				else if (argument == "-h")
					printHelp();
				else if (argument.StartsWith("-f:"))
					File.WriteAllText(argument.Substring(3), systemInformationSummary);
			}

            return Task.FromResult(0);
		}

		private void printHelp()
		{
			Console.WriteLine();
			Console.WriteLine("System Info Tool");
			Console.WriteLine("Usage: mdtool systeminfo [-c] [-f:file-path]");
			Console.WriteLine();

			Console.WriteLine("Options");
			Console.WriteLine("  -h                Print this message");
			Console.WriteLine("  -c                Output system information to the console");
			Console.WriteLine("  -f:file-path      Output system information into the specifed file");
			Console.WriteLine();
		}
    }
}


text:
<?php

namespace Symfony\Component\DependencyInjection\Tests\Fixtures;

class FooClassWithEnumAttribute
{
    private FooUnitEnum $bar;

    public function __construct(FooUnitEnum $bar)
    {
        $this->bar = $bar;
    }

    public function getBar(): FooUnitEnum
    {
        return $this->bar;
    }
}


text:
namespace ash {
namespace {

static base::LazyInstance<CupsPrintJobManagerFactory>::DestructorAtExit
    g_cups_print_job_manager_factory = LAZY_INSTANCE_INITIALIZER;

}  // namespace

// static
CupsPrintJobManagerFactory* CupsPrintJobManagerFactory::GetInstance() {
  return g_cups_print_job_manager_factory.Pointer();
}

// static
CupsPrintJobManager* CupsPrintJobManagerFactory::GetForBrowserContext(
    content::BrowserContext* context) {
  return static_cast<CupsPrintJobManager*>(
      GetInstance()->GetServiceForBrowserContext(context, true));
}

CupsPrintJobManagerFactory::CupsPrintJobManagerFactory()
    : ProfileKeyedServiceFactory(
          "CupsPrintJobManagerFactory",
          ProfileSelections::BuildRedirectedInIncognito()) {
  DependsOn(SyncedPrintersManagerFactory::GetInstance());
  DependsOn(CupsPrintersManagerFactory::GetInstance());
}

CupsPrintJobManagerFactory::~CupsPrintJobManagerFactory() = default;

KeyedService* CupsPrintJobManagerFactory::BuildServiceInstanceFor(
    content::BrowserContext* context) const {
  return CupsPrintJobManager::CreateInstance(
      Profile::FromBrowserContext(context));
}

}  // namespace ash


text:
module Compute
  module HypervisorsHelper
    def accumulated_hypervisors(hypervisors)
      hypervisors.each_with_object({}) do |hv, map|
        map[hv.availability_zone] ||= {
          availability_zone: hv.availability_zone,
          vcpus_used: 0,
          vcpus_total: 0,
          memory_used: 0,
          memory_total: 0,
          local_storage_used: 0,
          local_storage_total: 0,
          running_vms: 0,
          items: []
        }

        map[hv.availability_zone][:vcpus_used] += hv.attributes['vcpus_used'].to_i
        map[hv.availability_zone][:vcpus_total] += hv.attributes['vcpus'].to_i
        map[hv.availability_zone][:memory_used] += hv.attributes['memory_mb_used'].to_f
        map[hv.availability_zone][:memory_total] += hv.attributes['memory_mb'].to_f
        map[hv.availability_zone][:local_storage_used] += hv.attributes['local_gb_used'].to_f
        map[hv.availability_zone][:local_storage_total] += hv.attributes['local_gb'].to_f
        map[hv.availability_zone][:running_vms] += hv.attributes['running_vms'].to_i
        map[hv.availability_zone][:items] << hv
      end.values.sort_by! { |data| data[:availability_zone] }.each do |data|
        data[:vcpus_used] = Core::DataType.new(:number).format(data[:vcpus_used])
        data[:vcpus_total] = Core::DataType.new(:number).format(CPU_OVERCOMMIT*data[:vcpus_total])
        data[:memory_used] = Core::DataType.new(:bytes, :mega).format(data[:memory_used])
        data[:memory_total] = Core::DataType.new(:bytes, :mega).format(data[:memory_total])
        data[:local_storage_used] = Core::DataType.new(:bytes, :giga).format(data[:local_storage_used])
        data[:local_storage_total] = Core::DataType.new(:bytes, :giga).format(data[:local_storage_total])
      end
    end

    def vcpus_of(hypervisor)
      "#{hypervisor.vcpus_used} of #{hypervisor.vcpus_total}"
    end

    def memory_of(hypervisor)
      "#{hypervisor.memory_used} of #{hypervisor.memory_total}"
    end

    def local_storage_of(hypervisor)
      "#{hypervisor.local_storage_used} of #{hypervisor.local_storage_total}"
    end
  end
end


text:
#if !defined(BOOST_SPIRIT_PARSE_APRIL_16_2006_0442PM)
#define BOOST_SPIRIT_PARSE_APRIL_16_2006_0442PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/qi/detail/parse.hpp>
#include <boost/concept_check.hpp>

namespace boost { namespace spirit { namespace qi
{
    ///////////////////////////////////////////////////////////////////////////
    template <typename Iterator, typename Expr>
    inline bool
    parse(
        Iterator& first
      , Iterator last
      , Expr const& expr)
    {
        // Make sure the iterator is at least a forward_iterator. If you got a
        // compilation error here, then you are using an input_iterator while
        // calling this function, you need to supply at least a
        // forward_iterator instead.
        BOOST_CONCEPT_ASSERT((ForwardIterator<Iterator>));

        return detail::parse_impl<Expr>::call(first, last, expr);
    }

    template <typename Iterator, typename Expr>
    inline bool
    parse(
        Iterator const& first_
      , Iterator last
      , Expr const& expr)
    {
        Iterator first = first_;
        return parse(first, last, expr);
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename Iterator, typename Expr, typename Attr>
    inline bool
    parse(
        Iterator& first
      , Iterator last
      , Expr const& expr
      , Attr& attr)
    {
        // Make sure the iterator is at least a forward_iterator. If you got a
        // compilation error here, then you are using an input_iterator while
        // calling this function, you need to supply at least a
        // forward_iterator instead.
        BOOST_CONCEPT_ASSERT((ForwardIterator<Iterator>));

        // Report invalid expression error as early as possible.
        // If you got an error_invalid_expression error message here,
        // then the expression (expr) is not a valid spirit qi expression.
        BOOST_SPIRIT_ASSERT_MATCH(qi::domain, Expr);

        return compile<qi::domain>(expr).parse(first, last, unused, unused, attr);
    }

    template <typename Iterator, typename Expr, typename Attr>
    inline bool
    parse(
        Iterator const& first_
      , Iterator last
      , Expr const& expr
      , Attr& attr)
    {
        Iterator first = first_;
        return parse(first, last, expr, attr);
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename Iterator, typename Expr, typename Skipper>
    inline bool
    phrase_parse(
        Iterator& first
      , Iterator last
      , Expr const& expr
      , Skipper const& skipper
      , BOOST_SCOPED_ENUM(skip_flag) post_skip = skip_flag::postskip)
    {
        // Make sure the iterator is at least a forward_iterator. If you got a
        // compilation error here, then you are using an input_iterator while
        // calling this function, you need to supply at least a
        // forward_iterator instead.
        BOOST_CONCEPT_ASSERT((ForwardIterator<Iterator>));

        return detail::phrase_parse_impl<Expr>::call(
            first, last, expr, skipper, post_skip);
    }

    template <typename Iterator, typename Expr, typename Skipper>
    inline bool
    phrase_parse(
        Iterator const& first_
      , Iterator last
      , Expr const& expr
      , Skipper const& skipper
      , BOOST_SCOPED_ENUM(skip_flag) post_skip = skip_flag::postskip)
    {
        Iterator first = first_;
        return phrase_parse(first, last, expr, skipper, post_skip);
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename Iterator, typename Expr, typename Skipper, typename Attr>
    inline bool
    phrase_parse(
        Iterator& first
      , Iterator last
      , Expr const& expr
      , Skipper const& skipper
      , BOOST_SCOPED_ENUM(skip_flag) post_skip
      , Attr& attr)
    {
        // Make sure the iterator is at least a forward_iterator. If you got a
        // compilation error here, then you are using an input_iterator while
        // calling this function, you need to supply at least a
        // forward_iterator instead.
        BOOST_CONCEPT_ASSERT((ForwardIterator<Iterator>));

        // Report invalid expression error as early as possible.
        // If you got an error_invalid_expression error message here,
        // then either the expression (expr) or skipper is not a valid
        // spirit qi expression.
        BOOST_SPIRIT_ASSERT_MATCH(qi::domain, Expr);
        BOOST_SPIRIT_ASSERT_MATCH(qi::domain, Skipper);

        typedef
            typename result_of::compile<qi::domain, Skipper>::type
        skipper_type;
        skipper_type const skipper_ = compile<qi::domain>(skipper);

        if (!compile<qi::domain>(expr).parse(
                first, last, unused, skipper_, attr))
            return false;

        if (post_skip == skip_flag::postskip)
            qi::skip_over(first, last, skipper_);
        return true;
    }

    template <typename Iterator, typename Expr, typename Skipper, typename Attr>
    inline bool
    phrase_parse(
        Iterator const& first_
      , Iterator last
      , Expr const& expr
      , Skipper const& skipper
      , BOOST_SCOPED_ENUM(skip_flag) post_skip
      , Attr& attr)
    {
        Iterator first = first_;
        return phrase_parse(first, last, expr, skipper, post_skip, attr);
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename Iterator, typename Expr, typename Skipper, typename Attr>
    inline bool
    phrase_parse(
        Iterator& first
      , Iterator last
      , Expr const& expr
      , Skipper const& skipper
      , Attr& attr)
    {
        return phrase_parse(first, last, expr, skipper, skip_flag::postskip, attr);
    }

    template <typename Iterator, typename Expr, typename Skipper, typename Attr>
    inline bool
    phrase_parse(
        Iterator const& first_
      , Iterator last
      , Expr const& expr
      , Skipper const& skipper
      , Attr& attr)
    {
        Iterator first = first_;
        return phrase_parse(first, last, expr, skipper, skip_flag::postskip, attr);
    }

}}}

#endif


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

#ifndef VMGROUP_POOL_H_
#define VMGROUP_POOL_H_

#include "PoolSQL.h"
#include "VMGroup.h"

class AuthRequest;

class VMGroupPool : public PoolSQL
{
public:
    VMGroupPool(SqlDB * db):PoolSQL(db, VMGroup::table){};

    ~VMGroupPool(){};

    /* ---------------------------------------------------------------------- */
    /* Methods for DB management                                              */
    /* ---------------------------------------------------------------------- */
    /**
     * Allocates a new VMGroup, writing it in the pool database. No memory is
     * allocated for the object.
     *
     *   @param uid user identifier
     *   @param gid the id of the group this object is assigned to
     *   @param uname user name
     *   @param gname group name
     *   @param umask permissions umask
     *   @param vmgroup_template a Template object
     *   @param oid the id assigned to the new VMGroup
     *   @param error_str Returns the error reason, if any
     *
     *   @return the oid assigned to the object, -1 in case of failure
     */
    int allocate(int uid, int gid, const std::string& uname,
        const std::string& gname, int umask, Template * vmgrp_tmpl, int * oid,
        std::string& error_str);

    /**
     *  Function to get a VMGroup from the pool, if the object is not in memory
     *  it is loaded from the DB
     *    @param oid VMGroup unique id
     *    @param lock locks the VMGroup mutex
     *    @return a pointer to the VMGroup, 0 if the VMGroup could not be loaded
     */
    VMGroup * get(int oid, bool lock)
    {
        return static_cast<VMGroup *>(PoolSQL::get(oid, lock));
    };

    /**
     *  Gets an object from the pool (if needed the object is loaded from the
     *  database).
     *   @param name of the object
     *   @param uid id of owner
     *   @param lock locks the object if true
     *
     *   @return a pointer to the object, 0 in case of failure
     */
    VMGroup * get(const std::string& name, int uid, bool lock)
    {
        return static_cast<VMGroup *>(PoolSQL::get(name, uid, lock));
    };

    /** Update a VMGroup
     *    @param vmgroup pointer to VMGroup
     *    @return 0 on success
     */
    int update(VMGroup * vmgroup)
    {
        return vmgroup->update(db);
    };

    /**
     *  Bootstraps the database table(s) associated to the VMGroup pool
     *    @return 0 on success
     */
    static int bootstrap(SqlDB * _db)
    {
        return VMGroup::bootstrap(_db);
    };

    /**
     *  Dumps the VMGroup pool in XML format. A filter can be added to the query
     *  @param os the output stream to dump the pool contents
     *  @param where filter for the objects, defaults to all
     *  @param limit parameters used for pagination
     *
     *  @return 0 on success
     */
    int dump(std::ostringstream& os, const std::string& where,
            const std::string& limit)
    {
        return PoolSQL::dump(os, "VM_GROUP_POOL", VMGroup::table, where, limit);
    };

    /**
     *  Parse the VMGROUP definition in a VM and fills the ROLE attributes. It
     *  also adds the VM to the role if found.
     *    @param va the vector attribute
     *    @param uid VM owner, used as default to look for the VMGroup
     *    @param vid of the VM
     *    @param err if any
     *
     *    @return 0 on success
     */
    int vmgroup_attribute(VectorAttribute * va, int uid, int vid, string& err);

    /**
     *  Removes VM from the VMGroup
     *    @param va with VMGROUP
     *    @param vid of the VM to be removed
     */
    void del_vm(const VectorAttribute * va, int vid);

    /**
     *  Builds the AuthRequest for the VMGroup
     *    @param va with the VMGROUP
     *    @param uid VM owber, used as default to look for the VMGroup
     *    @param ar the authrequest
     */
    void authorize(const VectorAttribute * va, int uid, AuthRequest* ar);

private:
    /**
     *  Factory method to produce objects
     *    @return a pointer to the new object
     */
    PoolObjectSQL * create()
    {
        return new VMGroup(-1,-1,"","",0,0);
    };

    /**
     *  Gest a VMGroup from its vector attribute description
     *    @param va the VectorAttribute
     *    @param _uid default uid to look for the VMGroup
     */
    VMGroup * get_from_attribute(const VectorAttribute *va, int _uid);
};

#endif /*VMGROUP_POOL_H_*/


text:
//---------------------------------------------------------------------
// <copyright file="JsonArrayElementSeparatorTextAnnocation.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.OData.Json.TextAnnotations
{
    #region Namespaces
    using Microsoft.Test.Taupo.Astoria.Contracts.Json;
    #endregion Namespaces

    /// <summary>
    /// Annotation for an element of an array. This stored the array seprator (comma) BEFORE the element in question.
    /// </summary>
    public class JsonArrayElementSeparatorTextAnnotation : JsonTextAnnotation
    {
        /// <summary>
        /// Returns the default text annotation for the array element.
        /// </summary>
        /// <param name="firstElement">True if this is for the first element in the array, otherwise false.</param>
        /// <returns>The default text representation of the array element.</returns>
        public static JsonArrayElementSeparatorTextAnnotation GetDefault(bool firstElement)
        {
            return new JsonArrayElementSeparatorTextAnnotation() { Text = firstElement ? "" : "," };
        }
    }
}


text:
package org.apache.flink.table.functions;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.TableException;
import org.apache.flink.table.catalog.DataTypeFactory;
import org.apache.flink.table.types.inference.TypeInference;
import org.apache.flink.util.Preconditions;

import java.util.Objects;
import java.util.Set;

/**
 * A "marker" function definition of a user-defined scalar function that uses the old type system
 * stack.
 *
 * <p>This class can be dropped once we introduce a new type inference.
 */
@Internal
public final class ScalarFunctionDefinition implements FunctionDefinition {

	private final String name;
	private final ScalarFunction scalarFunction;

	public ScalarFunctionDefinition(String name, ScalarFunction scalarFunction) {
		this.name = Preconditions.checkNotNull(name);
		this.scalarFunction = Preconditions.checkNotNull(scalarFunction);
	}

	public String getName() {
		return name;
	}

	public ScalarFunction getScalarFunction() {
		return scalarFunction;
	}

	@Override
	public FunctionKind getKind() {
		return FunctionKind.SCALAR;
	}

	@Override
	public TypeInference getTypeInference(DataTypeFactory factory) {
		throw new TableException("Functions implemented for the old type system are not supported.");
	}

	@Override
	public Set<FunctionRequirement> getRequirements() {
		return scalarFunction.getRequirements();
	}

	@Override
	public boolean isDeterministic() {
		return scalarFunction.isDeterministic();
	}

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

	@Override
	public int hashCode() {
		return Objects.hash(name);
	}

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