text:
#include "postgres.h"

#include "access/htup.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#include "optimizer/clauses.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "parser/parse_expr.h"

static bool IsTidEqualClause(OpExpr *node, int varno);
static bool IsTidEqualAnyClause(ScalarArrayOpExpr *node, int varno);
static List *TidQualFromExpr(Node *expr, int varno);
static List *TidQualFromRestrictinfo(List *restrictinfo, int varno);

/*
 * Check to see if an opclause is of the form
 *		CTID = pseudoconstant
 * or
 *		pseudoconstant = CTID
 *
 * We check that the CTID Var belongs to relation "varno".	That is probably
 * redundant considering this is only applied to restriction clauses, but
 * let's be safe.
 */
static bool
IsTidEqualClause(OpExpr *node, int varno)
{
	Node	   *arg1,
			   *arg2,
			   *other;
	Var		   *var;

	/* Operator must be tideq */
	if (node->opno != TIDEqualOperator)
		return false;
	if (list_length(node->args) != 2)
		return false;
	arg1 = linitial(node->args);
	arg2 = lsecond(node->args);

	/* Look for CTID as either argument */
	other = NULL;
	if (arg1 && IsA(arg1, Var))
	{
		var = (Var *) arg1;
		if (var->varattno == SelfItemPointerAttributeNumber &&
			var->vartype == TIDOID &&
			var->varno == varno &&
			var->varlevelsup == 0)
			other = arg2;
	}
	if (!other && arg2 && IsA(arg2, Var))
	{
		var = (Var *) arg2;
		if (var->varattno == SelfItemPointerAttributeNumber &&
			var->vartype == TIDOID &&
			var->varno == varno &&
			var->varlevelsup == 0)
			other = arg1;
	}
	if (!other)
		return false;
	if (exprType(other) != TIDOID)
		return false;			/* probably can't happen */

	/* The other argument must be a pseudoconstant */
	if (!is_pseudo_constant_clause(other))
		return false;

	return true;				/* success */
}

/*
 * Check to see if a clause is of the form
 *		CTID = ANY (pseudoconstant_array)
 */
static bool
IsTidEqualAnyClause(ScalarArrayOpExpr *node, int varno)
{
	Node	   *arg1,
			   *arg2;

	/* Operator must be tideq */
	if (node->opno != TIDEqualOperator)
		return false;
	if (!node->useOr)
		return false;
	Assert(list_length(node->args) == 2);
	arg1 = linitial(node->args);
	arg2 = lsecond(node->args);

	/* CTID must be first argument */
	if (arg1 && IsA(arg1, Var))
	{
		Var		   *var = (Var *) arg1;

		if (var->varattno == SelfItemPointerAttributeNumber &&
			var->vartype == TIDOID &&
			var->varno == varno &&
			var->varlevelsup == 0)
		{
			/* The other argument must be a pseudoconstant */
			if (is_pseudo_constant_clause(arg2))
				return true;	/* success */
		}
	}

	return false;
}

/*
 *	Extract a set of CTID conditions from the given qual expression
 *
 *	Returns a List of CTID qual expressions (with implicit OR semantics
 *	across the list), or NIL if there are no usable conditions.
 *
 *	If the expression is an AND clause, we can use a CTID condition
 *	from any sub-clause.  If it is an OR clause, we must be able to
 *	extract a CTID condition from every sub-clause, or we can't use it.
 *
 *	In theory, in the AND case we could get CTID conditions from different
 *	sub-clauses, in which case we could try to pick the most efficient one.
 *	In practice, such usage seems very unlikely, so we don't bother; we
 *	just exit as soon as we find the first candidate.
 */
static List *
TidQualFromExpr(Node *expr, int varno)
{
	List	   *rlst = NIL;
	ListCell   *l;

	if (is_opclause(expr))
	{
		/* base case: check for tideq opclause */
		if (IsTidEqualClause((OpExpr *) expr, varno))
			rlst = list_make1(expr);
	}
	else if (expr && IsA(expr, ScalarArrayOpExpr))
	{
		/* another base case: check for tid = ANY clause */
		if (IsTidEqualAnyClause((ScalarArrayOpExpr *) expr, varno))
			rlst = list_make1(expr);
	}
	else if (expr && IsA(expr, CurrentOfExpr))
	{
		/* another base case: check for CURRENT OF on this rel */
		if (((CurrentOfExpr *) expr)->cvarno == varno)
			rlst = list_make1(expr);
	}
	else if (and_clause(expr))
	{
		foreach(l, ((BoolExpr *) expr)->args)
		{
			rlst = TidQualFromExpr((Node *) lfirst(l), varno);
			if (rlst)
				break;
		}
	}
	else if (or_clause(expr))
	{
		foreach(l, ((BoolExpr *) expr)->args)
		{
			List	   *frtn = TidQualFromExpr((Node *) lfirst(l), varno);

			if (frtn)
				rlst = list_concat(rlst, frtn);
			else
			{
				if (rlst)
					list_free(rlst);
				rlst = NIL;
				break;
			}
		}
	}
	return rlst;
}

/*
 *	Extract a set of CTID conditions from the given restrictinfo list
 *
 *	This is essentially identical to the AND case of TidQualFromExpr,
 *	except for the format of the input.
 */
static List *
TidQualFromRestrictinfo(List *restrictinfo, int varno)
{
	List	   *rlst = NIL;
	ListCell   *l;

	foreach(l, restrictinfo)
	{
		RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);

		if (!IsA(rinfo, RestrictInfo))
			continue;			/* probably should never happen */
		rlst = TidQualFromExpr((Node *) rinfo->clause, varno);
		if (rlst)
			break;
	}
	return rlst;
}

/*
 * create_tidscan_paths
 *	  Create paths corresponding to direct TID scans of the given rel.
 *
 *	  Candidate paths are added to the rel's pathlist (using add_path).
 *
 * CDB: Instead of handing the paths to add_path(), we append them to a List
 * (*ppathlist) belonging to the caller.
 *
 * CDB TODO: Set rel->onerow if at most one tid is to be fetched.
 */
void
create_tidscan_paths(PlannerInfo *root, RelOptInfo *rel, List** ppathlist)
{
	List	   *tidquals;

	tidquals = TidQualFromRestrictinfo(rel->baserestrictinfo, rel->relid);

	if (tidquals)
		*ppathlist = lappend(*ppathlist, create_tidscan_path(root, rel, tidquals));
}


text:
--
-- image-user-index.sql
--
-- Add user/timestamp index to current image versions
--

ALTER TABLE /*$wgDBprefix*/image
   ADD INDEX img_usertext_timestamp (img_user_text,img_timestamp);

redpajama_set_name: RedPajamaGithub


text:
package org.openqa.selenium.server.browserlaunchers;

import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.common.io.ByteStreams;

import com.thoughtworks.selenium.CommandProcessor;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;

import static com.google.common.io.Closeables.closeQuietly;

public class ServerHttpChannel implements Runnable {
  private final static Logger log = Logger.getLogger(ServerHttpChannel.class.getName());

  private final String serverUrl;
  private final String sessionId;
  private final CommandProcessor processor;
  private final ProcessorCommands commands = new ProcessorCommands();
  private int sequenceNumber;
  private HttpURLConnection connection;
  private volatile boolean carryOn = true;

  public ServerHttpChannel(String sessionId, int serverPort,
      CommandProcessor processor) {
    this.sessionId = sessionId;
    this.processor = processor;
    serverUrl = String.format(
        "http://localhost:%d/selenium-server/driver/?localFrameAddress=top&seleniumWindowName=&uniqueId=%s",
        serverPort, UUID.randomUUID());
  }

  public void run() {
    try {
      send("OK," + sessionId, null);
      while (carryOn) {
        String raw = read();

        log.fine("read complete: " + raw);

        if (carryOn) {
          carryOn = execute(processor, raw);
        }
      }

      send("OK", null);
    } catch (ConnectException e) {
      log.warning("Unable to connect to server. Assuming shutdown.");
      // And fall out the bottom of the run method. Don't clean up, just in
      // case.
    } catch (IOException e) {
      Throwables.propagate(e);
    }
  }

  private boolean execute(CommandProcessor processor, String raw)
      throws IOException {
    Map<String, String> command = parse(raw);
    if (command == null) {
      return false;
    }

    String[] args;
    if (command.containsKey("value")) {
      args = new String[2];
      args[0] = command.get("target");
      args[1] = command.get("value");
    } else {
      args = new String[1];
      args[1] = command.get("target");
    }

    String commandName = command.get("command");

    if ("retryLast".equals(commandName)) {
      send("RETRY", "retry=true");
      return true;
    }

    StringBuilder value = new StringBuilder();
    try {
      String result = commands.execute(processor, commandName, args);
      value.append("OK");
      if (result != null) {
        value.append(",").append(result);
      }
    } catch (Throwable e) {
      value.append("ERROR,").append(e.getMessage());
    }

    send(value.toString(), null);

    return true;
  }

  private Map<String, String> parse(String raw) {
    if (!raw.startsWith("json=")) {
      return null;
    }
    try {
      JSONObject converted = new JSONObject(raw.substring("json=".length()));

      Map<String, String> toReturn = Maps.newHashMap();
      Iterator allKeys = converted.keys();

      while (allKeys.hasNext()) {
        String next = (String) allKeys.next();
        toReturn.put(next, converted.getString(next));
      }

      return toReturn;
    } catch (JSONException e) {
      throw Throwables.propagate(e);
    }
  }

  public void kill() {
    carryOn = false;
  }

  public void send(String postedData, String urlParams) throws IOException {
    log.fine("Sending a response: " + postedData);

    StringBuilder builder = new StringBuilder(serverUrl).append("&sessionId=").append(sessionId);
    if (sequenceNumber == 0) {
      builder.append("&seleniumStart=true");
    }
    builder.append("&sequenceNumber=").append(sequenceNumber++);
    if (urlParams != null) {
      builder.append("&").append(urlParams);
    }

    StringBuilder response = new StringBuilder("postedData=");
    response.append(postedData);

    byte[] toSend = response.toString().getBytes(Charsets.UTF_8);

    connection = (HttpURLConnection) new URL(builder.toString()).openConnection();
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF8");
    connection.setRequestProperty("Content-Length", String.valueOf(toSend.length));

    OutputStream out = connection.getOutputStream();
    try {
      out.write(toSend);
      out.flush();
    } finally {
      closeQuietly(out);
    }
  }

  public String read() throws IOException {
    InputStream input = connection.getInputStream();
    byte[] bytes = ByteStreams.toByteArray(input);
    closeQuietly(input);
    connection.disconnect();
    connection = null;
    return new String(bytes, Charsets.UTF_8);
  }
}


text:
import { Events, CheckboxChangedEvent } from "../events";
import { AgEvent } from '../events';
import { AgAbstractInputField, IInputField } from './agAbstractInputField';
import { LabelAlignment } from './agAbstractLabel';
import { addOrRemoveCssClass } from '../utils/dom';

export interface ChangeEvent extends AgEvent {
    selected: boolean;
}

export class AgCheckbox extends AgAbstractInputField<HTMLInputElement, boolean> {

    protected labelAlignment: LabelAlignment = 'right';

    private selected?: boolean = false;
    private readOnly = false;
    private passive = false;

    constructor(config?: IInputField, className = 'ag-checkbox', inputType = 'checkbox') {
        super(config, className, inputType);
    }

    protected addInputListeners() {
        this.addManagedListener(this.eInput, 'click', this.onCheckboxClick.bind(this));
        this.addManagedListener(this.eLabel, 'click', this.toggle.bind(this));
    }

    public getNextValue(): boolean {
        return this.selected === undefined ? true : !this.selected;
    }

    public setPassive(passive: boolean): void {
        this.passive = passive;
    }

    public isReadOnly(): boolean {
        return this.readOnly;
    }

    public setReadOnly(readOnly: boolean): void {
        addOrRemoveCssClass(this.eWrapper, 'ag-disabled', readOnly);
        this.eInput.disabled = readOnly;
        this.readOnly = readOnly;
    }

    public setDisabled(disabled: boolean): this {
        addOrRemoveCssClass(this.eWrapper, 'ag-disabled', disabled);

        return super.setDisabled(disabled);
    }

    public toggle(): void {
        const previousValue = this.isSelected();
        const nextValue = this.getNextValue();

        if (this.passive) {
            this.dispatchChange(nextValue, previousValue);
        } else {
            this.setValue(nextValue);
        }
    }

    public getValue(): boolean {
        return this.isSelected();
    }

    public setValue(value?: boolean, silent?: boolean): this {
        this.refreshSelectedClass(value);
        this.setSelected(value, silent);

        return this;
    }

    public setName(name: string): this {
        const input = this.getInputElement() as HTMLInputElement;
        input.name = name;

        return this;
    }

    protected isSelected(): boolean {
        return this.selected;
    }

    private setSelected(selected?: boolean, silent?: boolean): void {
        if (this.isSelected() === selected) {
            return;
        }

        this.previousValue = this.isSelected();

        selected = this.selected = typeof selected === 'boolean' ? selected : undefined;
        (this.eInput as HTMLInputElement).checked = selected;
        (this.eInput as HTMLInputElement).indeterminate = selected === undefined;

        if (!silent) {
            this.dispatchChange(this.selected, this.previousValue);
        }
    }

    private dispatchChange(selected: boolean | undefined, previousValue: boolean | undefined, event?: MouseEvent) {
        this.dispatchEvent({ type: AgCheckbox.EVENT_CHANGED, selected, previousValue, event });

        const input = this.getInputElement() as HTMLInputElement;
        const checkboxChangedEvent: CheckboxChangedEvent = {
            type: Events.EVENT_CHECKBOX_CHANGED,
            id: input.id,
            name: input.name,
            selected,
            previousValue
        };

        this.eventService.dispatchEvent(checkboxChangedEvent);
    }

    private onCheckboxClick(e: MouseEvent) {
        if (this.passive) { return; }
        const previousValue = this.isSelected();
        const selected = this.selected = (e.target as HTMLInputElement).checked;
        this.refreshSelectedClass(selected);
        this.dispatchChange(selected, previousValue, e);
    }

    private refreshSelectedClass(value?: boolean | null) {
        addOrRemoveCssClass(this.eWrapper, 'ag-checked', value === true);
        addOrRemoveCssClass(this.eWrapper, 'ag-indeterminate', value == null);
    }
}


text:
layout: page
title: "JavaScript ctype_alnum function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/ctype_alnum:751
- /functions/view/ctype_alnum
- /functions/view/751
- /functions/ctype_alnum:751
- /functions/751
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's ctype_alnum

{% codeblock ctype/ctype_alnum.js lang:js https://raw.github.com/kvz/phpjs/master/functions/ctype/ctype_alnum.js raw on github %}
function ctype_alnum(text) {
  //  discuss at: http://phpjs.org/functions/ctype_alnum/
  // original by: Brett Zamir (http://brett-zamir.me)
  //  depends on: setlocale
  //   example 1: ctype_alnum('AbC12');
  //   returns 1: true

  if (typeof text !== 'string') {
    return false;
  }
  // BEGIN REDUNDANT
  this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
  // END REDUNDANT
  return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.an) !== -1;
}
{% endcodeblock %}

 - [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/ctype/ctype_alnum.js)

Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.

Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:

 - [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/ctype/ctype_alnum.js)

### Other PHP functions in the ctype extension
{% render_partial _includes/custom/ctype.html %}


text:
package io.noties.markwon.test;

import androidx.annotation.NonNull;

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

class TestSpanSpan extends TestSpan.Span {

    private final String name;
    private final List<TestSpan> children;
    private final Map<String, Object> arguments;

    public TestSpanSpan(
            @NonNull String name,
            @NonNull List<TestSpan> children,
            @NonNull Map<String, Object> arguments) {
        this.name = name;
        this.children = children;
        this.arguments = arguments;
    }

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

    @NonNull
    @Override
    public Map<String, Object> arguments() {
        return arguments;
    }

    @NonNull
    @Override
    public List<TestSpan> children() {
        return children;
    }

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

        TestSpanSpan that = (TestSpanSpan) o;

        if (!name.equals(that.name)) return false;
        return arguments.equals(that.arguments);
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + arguments.hashCode();
        return result;
    }
}


text:
module Octopolo
  class Week
    attr_accessor :year
    attr_accessor :number

    DATE_STRING_FORMAT = "%Y-%m-%d"

    # Public: Instantiate a new Week
    #
    # year - Year the week occurs in
    # number - The number of the week in the given year
    def initialize year, number
      self.year = year
      self.number = number
    end

    # Public: Parse the date from a date-ish object
    #
    # dateish - A Date, Time, or String representing a date or time
    def self.parse dateish
      # TODO i'm not 100% happy with this implementation, but it does what i want and the tests pass
      if dateish.respond_to? :to_date
        date = dateish.to_date
        new date.year, date.cweek
      else
        date = Date.parse(dateish.to_s)
        new date.year, date.cweek
      end
    rescue ArgumentError
      raise InvalidType
    end

    # Public: Instantiate a Week for the current week
    #
    # Returns an instance of Week
    def self.current
      today = Date.today
      Week.new today.cwyear, today.cweek
    end

    # Public: Instantiate a Week for the prior week
    #
    # Returns an instance of Week
    def self.prior
      current.previous
    end

    # Public: A list of the last N weeks, excluding the current week
    #
    # count - An integer listing the number of weeks to return
    #
    # Returns an Array of Week instances
    def self.last count
      # holy hell this is gnarly
      #
      # essentially, create an array with the current week in it, then loop
      # through and tack on the previous week for whichever week is last; this
      # way, we keep tacking on ever more previous weeks as many times as is
      # asked for.
      out = [prior]
      (count - 1).times do
        out << out.last.previous
      end
      out
    end

    # Public: Friendly string representation of the week
    #
    # Returns a String of the start date
    def to_s
      start_date.strftime(DATE_STRING_FORMAT)
    end

    # Public: Programmer-friendly representation of the week
    #
    # Returns a String containing object details
    def inspect
      "#<#{self.class} #{to_s} (year=#{year} number=#{number})>"
    end

    # Public: Whether the week is the same as another week
    #
    # Returns a Boolean
    def == other
      year == other.year && number == other.number
    rescue
      false
    end

    # Public: The previous week
    #
    # Returns an instance of Week
    def previous
      if number == 1
        # carry the 1
        Week.new year - 1, 52
      else
        Week.new year, number - 1
      end
    end

    # Public: The next week
    #
    # Returns an instance of Week
    def next
      if number == 52
        # carry the 1
        Week.new year + 1, 1
      else
        Week.new year, number + 1
      end
    end

    # Public: Monday that starts the week
    #
    # Returns an instance of Date
    def start_date
      Date.commercial year, number
    end

    # Public:  Sunday that ends the week
    #
    # Returns an instance of Date
    def end_date
      Date.commercial year, number, 7
    end

    InvalidType = Class.new(StandardError)
  end
end


text:
 <app-nav></app-nav>

        <router-outlet></router-outlet>
        What up?

  <app-spinner></app-spinner>
  <app-toast></app-toast>
  <app-modal></app-modal>


text:
namespace Dropbox.Api.Files
{
    using sys = System;
    using col = System.Collections.Generic;
    using re = System.Text.RegularExpressions;

    using enc = Dropbox.Api.Stone;

    /// <summary>
    /// <para>The lock file batch result object</para>
    /// </summary>
    /// <seealso cref="Global::Dropbox.Api.Files.FileOpsResult" />
    public class LockFileBatchResult : FileOpsResult
    {
        #pragma warning disable 108

        /// <summary>
        /// <para>The encoder instance.</para>
        /// </summary>
        internal static enc.StructEncoder<LockFileBatchResult> Encoder = new LockFileBatchResultEncoder();

        /// <summary>
        /// <para>The decoder instance.</para>
        /// </summary>
        internal static enc.StructDecoder<LockFileBatchResult> Decoder = new LockFileBatchResultDecoder();

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="LockFileBatchResult" />
        /// class.</para>
        /// </summary>
        /// <param name="entries">Each Entry in the 'entries' will have '.tag' with the
        /// operation status (e.g. success), the metadata for the file and the lock state after
        /// the operation.</param>
        public LockFileBatchResult(col.IEnumerable<LockFileResultEntry> entries)
        {
            var entriesList = enc.Util.ToList(entries);

            if (entries == null)
            {
                throw new sys.ArgumentNullException("entries");
            }

            this.Entries = entriesList;
        }

        /// <summary>
        /// <para>Initializes a new instance of the <see cref="LockFileBatchResult" />
        /// class.</para>
        /// </summary>
        /// <remarks>This is to construct an instance of the object when
        /// deserializing.</remarks>
        [sys.ComponentModel.EditorBrowsable(sys.ComponentModel.EditorBrowsableState.Never)]
        public LockFileBatchResult()
        {
        }

        /// <summary>
        /// <para>Each Entry in the 'entries' will have '.tag' with the operation status (e.g.
        /// success), the metadata for the file and the lock state after the operation.</para>
        /// </summary>
        public col.IList<LockFileResultEntry> Entries { get; protected set; }

        #region Encoder class

        /// <summary>
        /// <para>Encoder for  <see cref="LockFileBatchResult" />.</para>
        /// </summary>
        private class LockFileBatchResultEncoder : enc.StructEncoder<LockFileBatchResult>
        {
            /// <summary>
            /// <para>Encode fields of given value.</para>
            /// </summary>
            /// <param name="value">The value.</param>
            /// <param name="writer">The writer.</param>
            public override void EncodeFields(LockFileBatchResult value, enc.IJsonWriter writer)
            {
                WriteListProperty("entries", value.Entries, writer, global::Dropbox.Api.Files.LockFileResultEntry.Encoder);
            }
        }

        #endregion

        #region Decoder class

        /// <summary>
        /// <para>Decoder for  <see cref="LockFileBatchResult" />.</para>
        /// </summary>
        private class LockFileBatchResultDecoder : enc.StructDecoder<LockFileBatchResult>
        {
            /// <summary>
            /// <para>Create a new instance of type <see cref="LockFileBatchResult" />.</para>
            /// </summary>
            /// <returns>The struct instance.</returns>
            protected override LockFileBatchResult Create()
            {
                return new LockFileBatchResult();
            }

            /// <summary>
            /// <para>Set given field.</para>
            /// </summary>
            /// <param name="value">The field value.</param>
            /// <param name="fieldName">The field name.</param>
            /// <param name="reader">The json reader.</param>
            protected override void SetField(LockFileBatchResult value, string fieldName, enc.IJsonReader reader)
            {
                switch (fieldName)
                {
                    case "entries":
                        value.Entries = ReadList<LockFileResultEntry>(reader, global::Dropbox.Api.Files.LockFileResultEntry.Decoder);
                        break;
                    default:
                        reader.Skip();
                        break;
                }
            }
        }

        #endregion
    }
}


text:
using ave.DTO.Customers.Accounts.Types;
using ave.DTO.Customers.Profiles.Types;
using ave.Service.Customers.Data;
using ave.Service.Customers.Data.Entities;
using ave.Service.Customers.Access.Repositories.Interfaces;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Text;

namespace ave.Service.Customers.Access.Repositories
{
	public class UserRepository : IUserRepository
	{
		private static Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
		private readonly EFServiceRepository_Helpers.IUnitOfWork unitOfWork = null;

		/// <summary>
		/// Конструктор класса по умочанию
		/// </summary>
		/// <param name="context"></param>
		public UserRepository(DatabaseContext context)
		{
			unitOfWork = new EFServiceRepository_Helpers.UnitOfWork(context);
		}

		#region Private methods

		/// <summary>
		/// Генерируем соль для пароля
		/// </summary>
		/// <returns></returns>
		public string GetPasswordSalt()
		{
			RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
			byte[] dataArray = new byte[32];
			crypto.GetBytes(dataArray);

			return Convert.ToBase64String(dataArray);
		}

		/// <summary>
		/// Формируем хэшированный пароль
		/// </summary>
		/// <param name="password">Пароль</param>
		/// <param name="passwordSalt">Соль</param>
		/// <returns></returns>
		public string GetPasswordHash(string password, string passwordSalt)
		{
			return string.Join("", SHA1CryptoServiceProvider.Create().ComputeHash(Encoding.UTF8.GetBytes(password)).Select(x => x.ToString("X2"))).ToLower();
		}

		#endregion

		/// <summary>
		/// Создает и добавляет в базу данных нового пользователя
		/// </summary>
		/// <param name="userId">Идентификатор пользователя</param>
		/// <param name="referrerId">Идентификатор пригласившего в систему реферера</param>
		/// <param name="username">Псевдоним пользователя</param>
		/// <param name="email">Адрес электронной почты</param>
		/// <param name="password">Пароль</param>
		/// <returns></returns>
		public void Create(Guid userId, Guid? referrerId, string username, string email, string password)
		{
			#region Role

			Role roleEntity = unitOfWork.RepositoryFor<Role>().Single(i => i.name == "guest");

			#endregion

			#region Account

			Account accountEntity = new Account();
			accountEntity.accountId = Guid.NewGuid();
			accountEntity.balance = 0.00M;
			accountEntity.currency = 0;
			accountEntity.activePlan = (int)AccountTypes.Free;

			unitOfWork.RepositoryFor<Account>().Add(accountEntity);

			#endregion

			#region Profile

			Profile profileEntity = new Profile();
			profileEntity.profileId = Guid.NewGuid();
			profileEntity.name = string.Empty;
			profileEntity.nameVisibility = (int)FieldVisibilityTypes.Everyone;
			profileEntity.gender = (int)GenderTypes.Unspecified;
			profileEntity.genderVisibility = (int)FieldVisibilityTypes.Everyone;
			profileEntity.birthdate = DateTime.Now;
			profileEntity.birthdateVisibility = (int)FieldVisibilityTypes.Everyone;
			profileEntity.avatar = "/Assets/Images/noavatar.gif";
			//profileEntity.Location = locationEntity;
			profileEntity.status = (int)ProfileTypes.Active;
			profileEntity.level = 0;
			profileEntity.karma = 0;

			unitOfWork.RepositoryFor<Profile>().Add(profileEntity);
			//m_unitOfWork.Commit();

			#endregion

			#region User

			User userEntity = new User();
			userEntity.userId = userId;
			userEntity.referrerId = referrerId;
			userEntity.userName = username;
			userEntity.email = email;
			userEntity.emailKey = Guid.NewGuid().ToString();
			userEntity.passwordSalt = GetPasswordSalt();
			userEntity.password = GetPasswordHash(password, userEntity.passwordSalt);
			userEntity.isLockedOut = false;
			userEntity.dateCreated = DateTime.Now;
			userEntity.lastDateLockout = DateTime.Now; /* Дата блокировки аккаута */
			userEntity.lastDateLogin = DateTime.Now; /* Дата последнего входа */
			userEntity.lastDateModified = DateTime.Now; /* Дата последнего редактировании профиля */
			userEntity.lastPasswordDateChanged = DateTime.Now; /* Дата смены пароля */
			userEntity.account = accountEntity;
			userEntity.profile = profileEntity;
			userEntity.role = roleEntity;

			unitOfWork.RepositoryFor<User>().Add(userEntity);
			unitOfWork.Commit();

			#endregion
		}

		/// <summary>
		/// Редактирует данные пользователя
		/// </summary>
		/// <param name="model">Модель данных</param>
		public void Edit(User model)
		{
			unitOfWork.RepositoryFor<User>().Update(model);
		}

		/// <summary>
		/// Удаляет из базы данных пользователя по псевданиму
		/// </summary>
		/// <param name="username">Псевдоним пользователя</param>
		public void Delete(string username)
		{
			var userEntity = unitOfWork.RepositoryFor<User>().Single(i => i.userName == username);

			//var roleEntity = userEntity.roles.ToList();
			//roleEntity.ForEach(i => userEntity.roles.Remove(i));

			//TODO:
			//userEntity.Roles.Clear();
			//m_unitOfWork.Commit();
		}

		/// <summary>
		/// Получает пользователя по идентификатору
		/// </summary>
		/// <param name="uid">Идентификатор пользователя</param>
		/// <returns></returns>
		public User GetUserById(Guid uid)
		{
			return unitOfWork.RepositoryFor<User>().First(i => i.userId == uid);
		}

		/// <summary>
		/// Получает пользователя по имени
		/// </summary>
		/// <param name="username">Псевдоним пользователя</param>
		/// <returns></returns>
		public User GetUserByName(string username)
		{
			return unitOfWork.RepositoryFor<User>().First(i => i.userName == username);
		}

		/// <summary>
		/// Получает пользователя по адресу электронной почты
		/// </summary>
		/// <param name="email">Адрес электронной почты</param>
		/// <returns></returns>
		public User GetUserByEmail(string email)
		{
			return unitOfWork.RepositoryFor<User>().First(i => i.email == email);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="pageNumber"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		public IEnumerable<User> GetUsers(int pageNumber, int pageSize)
		{
			return unitOfWork.RepositoryFor<User>().GetAll().OrderByDescending(i => i.userName).Skip(pageSize * pageNumber).Take(pageSize).ToList();
		}

		/// <summary>
		/// Получает всех пользователей
		/// </summary>
		/// <returns></returns>
		public IEnumerable<User> GetUsers()
		{
			return unitOfWork.RepositoryFor<User>().GetAll();
		}

		/// <summary>
		/// Получает общее количество пользователей
		/// </summary>
		/// <returns></returns>
		public int GetTotalCount()
		{
			return unitOfWork.RepositoryFor<User>().GetAll().Count();
		}

		/// <summary>
		/// Активация пользователя
		/// </summary>
		/// <param name="username">Псевдоним пользователя</param>
		/// <param name="key"></param>
		/// <returns></returns>
		public bool ActivateUser(string username, string key)
		{
			var requestLinq = unitOfWork.RepositoryFor<User>().First(i => i.userName == username);
			if (requestLinq.emailKey == key /*&& requestLinq.status == (int)PriorityLevel.Pending*/)
			{
				//requestLinq.status = (int)PriorityLevel.Inactive;
				requestLinq.lastDateModified = DateTime.Now;

				unitOfWork.Commit();
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// Проверяем на валидность входные данные
		/// </summary>
		/// <param name="username">Псевдоним пользователя</param>
		/// <param name="password">Пароль</param>
		/// <returns></returns>
		public bool ValidateUser(string username, string password)
		{
			var account = unitOfWork.RepositoryFor<User>().First(i => i.userName == username);
			if (account != null && account.password == GetPasswordHash(password, account.passwordSalt)/* && account.status != (int)PriorityLevel.Pending*/)
			{
				return true;
			}

			return false;
		}

		/// <summary>
		/// Изменяет старый пароль на новый
		/// </summary>
		/// <param name="username">Имя пользователя для которого следует изменить пароль</param>
		/// <param name="oldPassword">Старый пароль</param>
		/// <param name="newPassword">Новый пароль</param>
		/// <returns>true - если смена пороля прошла успешно, в противном случае false</returns>
		public bool ChangePassword(string username, string oldPassword, string newPassword)
		{
			if (ValidateUser(username, oldPassword) && !String.IsNullOrEmpty(newPassword.Trim()))
			{
				var user = unitOfWork.RepositoryFor<User>().First(i => i.userName == username);

				user.passwordSalt = GetPasswordSalt();
				user.password = GetPasswordHash(newPassword, user.passwordSalt);

				unitOfWork.RepositoryFor<User>().Update(user);
				unitOfWork.Commit();
				return true;
			}

			return false;
		}

		#region User providers

		/// <summary>
		///
		/// </summary>
		/// <param name="uid">Уникальный идентификатор пользователя</param>
		/// <param name="providerName">Имя поставщика</param>
		/// <param name="providerPageId">Уникальный идентификатор страницы пользователя в социальной сети</param>
		public void CreateUserProvider(Guid uid, string providerName, string providerPageId)
		{
			UserProvider providerEntity = new UserProvider();
			providerEntity.providerId = Guid.NewGuid();
			providerEntity.userId = uid;
			providerEntity.providerName = providerName;
			providerEntity.providerPageId = providerPageId;

			unitOfWork.RepositoryFor<UserProvider>().Add(providerEntity);
			unitOfWork.Commit();
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="uid"></param>
		/// <returns></returns>
		public IEnumerable<UserProvider> GetProvidersByUserId(Guid uid)
		{
			return unitOfWork.RepositoryFor<UserProvider>().Find(i => i.userId == uid);
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="providerName">Имя поставщика</param>
		/// <returns></returns>
		public IEnumerable<UserProvider> GetProvidersByName(string providerName)
		{
			return unitOfWork.RepositoryFor<UserProvider>().Find(i => i.providerName == providerName);
		}

		#endregion

		#region Friends

		///// <summary>
		///// Добавляет в друзья
		///// </summary>
		///// <param name="uid">Идентификатор пользователя</param>
		///// <param name="friendId">Идентификатор друга пользователя</param>
		//public void AddFriend(Guid uid, Guid friendId)
		//{
		//    TableUser user1 = m_unitOfWork.RepositoryFor<TableUser>().Single(i => i.ID == uid);
		//    TableUser user2 = m_unitOfWork.RepositoryFor<TableUser>().Single(i => i.ID == friendId);

		//    user1.Friends.Add(user2);
		//    m_unitOfWork.RepositoryFor<TableUser>().Attach(user1);

		//    user2.Friends.Add(user1);
		//    m_unitOfWork.RepositoryFor<TableUser>().Attach(user2);

		//    m_unitOfWork.Commit();
		//}

		///// <summary>
		///// Удаляет из друзей
		///// </summary>
		///// <param name="uid">Идентификатор пользователя</param>
		///// <param name="friendId">Идентификатор друга пользователя</param>
		//public void DeleteFriend(Guid uid, Guid friendId)
		//{
		//    TableUser user1 = m_unitOfWork.RepositoryFor<TableUser>().Single(i => i.ID == uid);
		//    TableUser user2 = m_unitOfWork.RepositoryFor<TableUser>().Single(i => i.ID == friendId);

		//    if (user1.Friends.Contains(user2))
		//    {
		//        user1.Friends.Remove(user2);
		//        m_unitOfWork.RepositoryFor<TableUser>().Delete(user1);
		//    }

		//    if (user2.Friends.Contains(user1))
		//    {
		//        user2.Friends.Remove(user1);
		//        m_unitOfWork.RepositoryFor<TableUser>().Delete(user2);
		//    }

		//    m_unitOfWork.Commit();
		//}

		///// <summary>
		///// Получает всех друзей
		///// </summary>
		///// <param name="uid">Идентификатор пользователя</param>
		///// <returns></returns>
		//public IQueryable<TableUser> GetFriends(Guid uid)
		//{
		//    return m_unitOfWork.RepositoryFor<TableUser>().Single(i => i.ID == uid).Friends.AsQueryable();
		//}

		#endregion

		#region Friend requests

		///// <summary>
		///// Создает новый запрос на дружбу
		///// </summary>
		///// <param name="from"></param>
		///// <param name="to"></param>
		//public void CreateFriendRequest(Guid from, Guid to)
		//{
		//    TableFriendRequest friendRequest = new TableFriendRequest();
		//    friendRequest.RequestId = Guid.NewGuid();
		//    friendRequest.SenderId = from;
		//    friendRequest.ReceiverId = to;

		//    m_unitOfWork.RepositoryFor<TableFriendRequest>().Add(friendRequest);
		//    m_unitOfWork.Commit();
		//}

		///// <summary>
		///// Удаляет существующий запрос
		///// </summary>
		///// <param name="friendRequest"></param>
		//public void DeleteFriendRequest(TableFriendRequest friendRequest)
		//{
		//    m_unitOfWork.RepositoryFor<TableFriendRequest>().Delete(friendRequest);
		//    m_unitOfWork.Commit();
		//}

		///// <summary>
		///// Получает все заявки в друзья (входящие и исходящие)
		///// </summary>
		///// <returns></returns>
		//public IQueryable<TableFriendRequest> GetAllRequestsToFriends()
		//{
		//    return m_unitOfWork.RepositoryFor<TableFriendRequest>().GetAll();
		//}

		///// <summary>
		///// Получает входящие заявки в Друзья
		///// </summary>
		///// <param name="uid"></param>
		///// <returns></returns>
		//public IQueryable<TableFriendRequest> GetIncomingRequestsToFriends(Guid uid)
		//{
		//    return m_unitOfWork.RepositoryFor<TableFriendRequest>().Find(i => i.ReceiverId == uid);
		//}

		///// <summary>
		///// Получает исходящие заявки в Друзья
		///// </summary>
		///// <param name="uid"></param>
		///// <returns></returns>
		//public IQueryable<TableFriendRequest> GetOutgoingRequestsToFriends(Guid uid)
		//{
		//    return m_unitOfWork.RepositoryFor<TableFriendRequest>().Find(i => i.SenderId == uid);
		//}

		///// <summary>
		///// Проверяет, отправил ли пользователь (from) пользователю (to) запрос на дружбу
		///// </summary>
		///// <param name="from"></param>
		///// <param name="to"></param>
		//public bool IsRequestToFriends(Guid from, Guid to)
		//{
		//    return m_unitOfWork.RepositoryFor<TableFriendRequest>().Find(i => i.SenderId == from).Count(i => i.ReceiverId == to) != 0;
		//}

		#endregion
	}
}


text:
**LNAMP笔记(Debian 11.5 + Nginx 1.14 + Apache 2.4 + MariaDB 10.3 + PHP 7.3 + Tomcat 9.0 + Python 3.7)**

~~/etc/apt/sources.list~~
```
deb https://mirrors.aliyun.com/debian           bullseye           main  contrib  non-free
deb https://mirrors.aliyun.com/debian           bullseye-updates   main  contrib  non-free
deb https://mirrors.aliyun.com/debian-security  bullseye-security  main  contrib  non-free
```
```
dpkg-reconfigure tzdata
apt update
apt upgrade
apt full-upgrade
```
```
apt install mariadb-server mariadb-client
mysql_secure_installation
```
```
mysql -u root -p
MariaDB> grant select,insert,update,delete on *.* to 'user123'@'%' Identified by 'pass123';
MariaDB> flush privileges;
```
```
apt install apache2 php libapache2-mod-php
apt install php-bcmath php-gd php-json php-mbstring php-mysql php-tokenizer php-xml php-zip
```
```
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
```
```
wget https://files.phpmyadmin.net/phpMyAdmin/5.2.0/phpMyAdmin-5.2.0-all-languages.tar.gz
tar -zxvf phpMyAdmin-5.2.0-all-languages.tar.gz
mv phpMyAdmin-5.2.0-all-languages /var/www/html/phpmyadmin
cp /var/www/html/phpmyadmin/config.sample.inc.php  /var/www/html/phpmyadmin/config.inc.php
```
/var/www/html/phpmyadmin/config.inc.php
```
$cfg['blowfish_secret'] = 'CHBj{O6P5]c8LE428ltUqpyp6xaJ2xN5';
```
```
mysql < /var/www/html/phpmyadmin/sql/create_tables.sql -u root -p
mkdir /var/www/html/phpmyadmin/tmp
chmod 777 /var/www/html/phpmyadmin/tmp
```
/etc/apache2/ports.conf
```
Listen 127.0.0.1:81
```
/etc/apache2/sites-available/000-default.conf
```
ServerName 127.0.0.1                         /etc/apache2/conf-available/security.conf
<VirtualHost *:81>                           ServerTokens Prod
    ServerAdmin xxx@xxx.net                  ServerSignature Off
    DocumentRoot /var/www
    …                                        /etc/php/7.3/apache2/php.ini
</VirtualHost>                               expose_php = off
                                             upload_max_filesize = 10M
a2enmod rewrite ssl                          date.timezone = Asia/Shanghai

/etc/apache2/apache2.conf                    /etc/nginx/nginx.conf
AllowOverride All                            server_tokens = off
```
```
apt install openjdk-11-jdk tomcat9 libmariadb-java
cp /usr/share/java/mariadb-java-client.jar /usr/share/tomcat9/lib/
```
/etc/tomcat9/tomcat-users.xml
```
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="admin" password="xxx" roles="admin-gui,manager-gui"/>
```
/etc/tomcat9/server.xml
```
<Connector port="8080" address="127.0.0.1" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443"/>
<Connector port="8009" protocol="AJP1.3" redirectPort="8443"/>    #取消注释
<Context path="" docBase="ROOT" debug="0" reloadable="true"/>     #在<Host>节点里面添加
```
```
wget https://packages.microsoft.com/config/debian/11/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
dpkg -i packages-microsoft-prod.deb
apt install dotnet-sdk-6.0
```
```
apt install apache2 libapache2-mod-wsgi-py3 python3-pip libmariadbd-dev
pip3 install --upgrade pip
```
/etc/pip.conf
```
[global]
trusted-host = mirrors.aliyun.com
index-url = https://mirrors.aliyun.com/pypi/simple
extra-index-url = https://pypi.tuna.tsinghua.edu.cn/simple
```
/etc/apache2/sites-available/000-default.conf
```
<VirtualHost *:81>
    ServerName xxx.net
    WSGIScriptAlias / /var/www/demo/django.wsgi
    <Directory "/var/www/demo">
        Options FollowSymLinks Indexes
        AllowOverride all
        Require all granted
    </Directory>

    Alias /robots.txt /var/www/demo/static/robots.txt
    Alias /static /var/www/demo/static
    <Location "/static">
        SetHandler None
    </Location>
    <Directory "/var/www/demo/static">
        Require all granted
    </Directory>

    ErrorLog "/var/log/apache2/py-error.log"
    CustomLog "/var/log/apache2/py-access.log" combined
</VirtualHost>
```
```
apt install nginx libapache2-mod-rpaf
```
/etc/apache2/mods-enable/rpaf.conf
```
RPAheader X-Forwarded-For
```
/etc/nginx/proxy_params
```
proxy_set_header            Host $host;
proxy_set_header            X-Real-IP $remote_addr;
proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size        10m;
client_body_buffer_size     128k;
proxy_connect_timeout       30;
proxy_send_timeout          30;
proxy_read_timeout          60;
proxy_buffers               8 128k;
```
```
apt install certbot
certbot certonly --webroot -w /var/www/html -d xxx.net -m xxx@live.cn --agree-tos
```
```
certbot renew --dry-run
crontab -e
30 2 * * 1 /usr/bin/certbot renew >> /var/log/le-renew.log
```
```
openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048
```
/etc/nginx/sites-available/default
```
    upstream php {
        server 127.0.0.1:81;
    }
    upstream java {
        server 127.0.0.1:8080;
    }
    server {
        server_name _;
        return 404;
    }
    server {
        listen 80;
        server_name www.xxx.net;
        location / {
            index index.html;
        }
    }
    server {
        listen 443 ssl http2;
        server_name xxx.net;

        ssl_dhparam /etc/ssl/certs/dhparam.pem;

        ssl_session_timeout 1d;
        ssl_session_cache shared:SSL:10m;
        ssl_session_tickets off;

        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;

        ssl_certificate /etc/letsencrypt/live/xxx.net/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/xxx.net/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/xxx.net/chain.pem;

        ssl_stapling on;
        ssl_stapling_verify on;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 30s;

        add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
        add_header X-Frame-Options DENY;
        add_header X-Content-Type-Options nosniff;

        location / {
            proxy_pass http://java;
            proxy_redirect off;
            include proxy_params;
        }

        location /phpmyadmin/ {
            proxy_pass http://php;
            include proxy_params;
        }
    }
```


text:
package com.suelake.habbo.communication.requests;

import com.blunk.Log;
import com.suelake.habbo.HabboHotel;
import com.suelake.habbo.communication.ClientMessage;
import com.suelake.habbo.communication.ClientRequestHandler;
import com.suelake.habbo.communication.CommunicationHandler;
import com.suelake.habbo.items.Item;

public class PRESENTOPEN implements ClientRequestHandler
{
	public void handle(ClientMessage msg, CommunicationHandler comm)
	{
		if (comm.getSpaceInstance().getUserByClientID(comm.clientID).isFlatOwner)
		{
			// Get present box item
			int itemID = Integer.parseInt(msg.nextArgument('/'));
			Item box = comm.getSpaceInstance().getInteractor().getActiveObject(itemID);

			// Present box?
			if (box != null && box.definition.sprite.startsWith("present_gen"))
			{
				// Pickup present box from room
				comm.getSpaceInstance().getInteractor().pickupActiveObject(itemID);
				HabboHotel.getItemAdmin().deleteItem(box);

				// Parse article data
				int articleID = 0;
				String articleCustomData = null;
				try
				{
					String[] articleData = box.customData.split(":", 3);
					articleID = Integer.parseInt(articleData[0]);
					if(!articleData[1].equals("*"))
					{
						articleCustomData = articleData[1];
					}
				}
				catch (Exception ex)
				{
					Log.error("PRESENTOPEN: article data parser error for string \"" + box.customData + "\", present deleted.");
				}

				// Purchase articles
				Item[] content = HabboHotel.getCatalogue().purchaseArticle(articleID, articleCustomData, comm.getUserObject().ID, comm.getUserObject().ID, false, null);
				if (content == null)
				{
					comm.systemMsg("Sorry, but the contents of this present box are not valid (anymore)!\rIf this happens frequently with the same kind of product, then please contact administrator.");
				}
				else
				{
					// Add content to inventory
					for (Item item : content)
					{
						comm.getItemInventory().addItem(item);
					}

					// Refresh inventory
					comm.getItemInventory().sendStrip("last");

					// Build response
					comm.response.set("PRESENTOPEN");
					comm.response.appendNewArgument(content[0].definition.sprite);
					if (content[0].definition.sprite.equals("poster"))
					{
						comm.response.appendNewArgument("poster " + content[0].customData);
					}
					else
					{
						comm.response.appendNewArgument(content[0].definition.sprite);
						if (content[0].definition.behaviour.onFloor)
						{
							comm.response.appendNewArgument("");
							comm.response.appendArgument(Byte.toString(content[0].definition.length), '|');
							comm.response.appendArgument(Byte.toString(content[0].definition.width), '|');
							comm.response.appendArgument(content[0].definition.color, '|');
						}
					}
					comm.sendResponse();
				}
			}
		}
	}
}


text:
using System.Collections.Generic;

namespace Umbraco.Cms.Core.Models.Entities
{
    /// <summary>
    /// Provides a concrete implementation of <see cref="BeingDirtyBase"/>.
    /// </summary>
    /// <remarks>
    /// <para>This class is provided for classes that cannot inherit from <see cref="BeingDirtyBase"/>
    /// and therefore need to implement <see cref="IRememberBeingDirty"/>, by re-using some of
    /// <see cref="BeingDirtyBase"/> logic.</para>
    /// </remarks>
    public sealed class BeingDirty : BeingDirtyBase
    {
        /// <summary>
        /// Sets a property value, detects changes and manages the dirty flag.
        /// </summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="value">The new value.</param>
        /// <param name="valueRef">A reference to the value to set.</param>
        /// <param name="propertyName">The property name.</param>
        /// <param name="comparer">A comparer to compare property values.</param>
        public new void SetPropertyValueAndDetectChanges<T>(T value, ref T valueRef, string propertyName, IEqualityComparer<T> comparer = null)
        {
            base.SetPropertyValueAndDetectChanges(value, ref valueRef, propertyName, comparer);
        }

        /// <summary>
        /// Registers that a property has changed.
        /// </summary>
        public new void OnPropertyChanged(string propertyName)
        {
            base.OnPropertyChanged(propertyName);
        }
    }
}


text:
<?php

$page['title'] = getlocal("thread.chat_log");

function tpl_content() { global $page, $mibewroot, $errors;
$chatthread = isset($page['thread']) ? $page['thread'] : array();
?>

<?php echo getlocal("thread.intro") ?>

			<?php echo getlocal("page.analysis.search.head_name") ?>:

			<?php echo topage(safe_htmlspecialchars(isset($chatthread['userName']) ? $chatthread['userName'] : '')) ?>

			<?php echo getlocal("page.analysis.search.head_host") ?>:

			<?php echo get_user_addr(topage(isset($chatthread['remote']) ? $chatthread['remote'] : '')) ?>

			<?php echo getlocal("page.analysis.search.head_browser") ?>:

			<?php echo get_useragent_version(topage(isset($chatthread['userAgent']) ? $chatthread['userAgent'] : '')) ?>

		<?php if( isset($chatthread['groupName']) && $chatthread['groupName'] ) { ?>

				<?php echo getlocal("page.analysis.search.head_group") ?>:

				<?php echo topage(safe_htmlspecialchars($chatthread['groupName'])) ?>

		<?php } ?>

		<?php if( isset($chatthread['agentName']) && $chatthread['agentName'] ) { ?>

				<?php echo getlocal("page.analysis.search.head_operator") ?>:

				<?php echo topage(safe_htmlspecialchars($chatthread['agentName'])) ?>

		<?php } ?>

			<?php echo getlocal("page.analysis.search.head_time") ?>:

			<?php echo date_diff_to_text((isset($chatthread['modified']) ? $chatthread['modified'] : 0) - (isset($chatthread['created']) ? $chatthread['created'] : 0)) ?>
				(<?php echo date_to_text(isset($chatthread['created']) ? $chatthread['created'] : 0) ?>)

<?php
	if (isset($page['threadMessages']) && is_array($page['threadMessages'])) {
		foreach( $page['threadMessages'] as $message ) {
			echo $message;
		}
	}
?>

<a href="<?php echo $mibewroot ?>/operator/history.php">
	<?php echo getlocal("thread.back_to_search") ?>

<?php
} /* content */

require_once('inc_main.php');
?>


text:
define({
  "map": {
    "error": "Harita oluşturulamıyor",
    "licenseError": {
      "message": "Hesabınız herkese açık olmayan Yapılandırılabilir Uygulamaları kullanmak için lisanslandırılmamış. Lütfen kuruluş yöneticinizden Temel Uygulamalar veya eklenti Temel Uygulamalar lisansı içeren bir kullanıcı türü atamasını isteyin.",
      "title": "Lisanslı Değil"
    }
  },
  "viewer": {
    "content_title": "Filtre",
    "button_text": "Uygula",
    "filterInstructions": "Katmanı, değerler belirterek filtreleyin.",
    "filterOr": "Aşağıdaki ifadelerden herhangi birinin doğru olması gerekir.",
    "filterAnd": "Aşağıdaki ifadelerin tümünün doğru olması gerekir.",
    "filterNo": "Bu web haritasında etkileşimli filtre yok. Etkileşimli filtre ifadelerini etkinleştirmek için web haritası filtre iletişim kutusundaki 'Değerleri iste' öğesini işaretleyin.

 Web haritanızda etkileşimli filtre ifadesi oluşturma hakkında daha fazla yardım için ${link} yardım konusunu görüntüleyin.",
    "filterLink": "http://doc.arcgis.com/en/arcgis-online/use-maps/apply-filters.htm",
    "errors": {
      "message": "Filtre uygulaması oluşturmada sorun oluştu"
    }
  },
  "tools": {
    "toggle": "Paneli aç/kapat",
    "clear": "Temizle",
    "zoom": "Yakınlaştır"
  },
  "legend": {
    "title": "Açıklama"
  }
});


text:
from hamcrest import assert_that, equal_to, has_entry, is_not
from testutils import (
    DeformSessionProjectClientTestCaseMixin,
    DeformTokenProjectClientTestCaseMixin,
    TestCase
)

class ProjectClientTestBase__collections(object):
    project_client_attr = None

    def convert_generator_to_list(self, generator):
        return [i for i in generator]

    def test_find_is_paginatable(self):
        assert_that(
            getattr(
                self,
                self.project_client_attr
            ).collections.find.is_paginatable,
            equal_to(True)
        )

    def test_find(self):
        response = getattr(self, self.project_client_attr).collections.find()
        response = self.convert_generator_to_list(response)
        users_collection = [i for i in response if i['_id'] == '_users']
        assert_that(users_collection, is_not(equal_to([])))

    def test_find__filter(self):
        response = getattr(self, self.project_client_attr).collections.find(
            filter={
                'name': 'Users'
            }
        )
        response = self.convert_generator_to_list(response)
        assert_that(len(response), equal_to(1))
        assert_that(response[0], has_entry('_id', '_users'))

    def test_find__text(self):
        response = getattr(self, self.project_client_attr).collections.find(
            text='Users'
        )
        response = self.convert_generator_to_list(response)
        assert_that(len(response), equal_to(1))
        assert_that(response[0], has_entry('_id', '_users'))

    def test_find_sort(self):
        response_1 = getattr(self, self.project_client_attr).collections.find(
            sort=['name']
        )
        response_1 = self.convert_generator_to_list(response_1)
        response_2 = getattr(self, self.project_client_attr).collections.find(
            sort=['-name']
        )
        response_2 = self.convert_generator_to_list(response_2)
        for i, item in enumerate(response_1):
            j = (i + 1) * -1
            assert_that(
                item,
                equal_to(response_2[j]),
                'item %s and %s does not equal' % (i, j)
            )

    def test_count(self):
        response = getattr(self, self.project_client_attr).collections.count()
        expected = getattr(self, self.project_client_attr).collections.find(
            per_page=1
        )['total']
        assert_that(response, equal_to(expected))

    def test_count__filter(self):
        response = getattr(self, self.project_client_attr).collections.count(
            filter={
                'name': 'Users'
            }
        )
        assert_that(response, equal_to(1))

    def test_count__text(self):
        response = getattr(self, self.project_client_attr).collections.count(
            text='Users'
        )
        assert_that(response, equal_to(1))

class SessionProjectClientTest__collections(
    DeformSessionProjectClientTestCaseMixin,
    ProjectClientTestBase__collections,
    TestCase
):
    project_client_attr = 'deform_session_project_client'

class TokenProjectClientTest__collections(
    DeformTokenProjectClientTestCaseMixin,
    ProjectClientTestBase__collections,
    TestCase
):
    project_client_attr = 'deform_token_project_client'


text:
package com.intellij.lang.jsgraphql.types.execution.instrumentation.dataloader;

import com.intellij.lang.jsgraphql.types.Assert;
import com.intellij.lang.jsgraphql.types.Internal;
import com.intellij.lang.jsgraphql.types.PublicApi;
import com.intellij.lang.jsgraphql.types.execution.instrumentation.InstrumentationState;
import org.dataloader.DataLoader;
import org.dataloader.DataLoaderRegistry;

import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

/**
 * A base class that keeps track of whether aggressive batching can be used
 */
@PublicApi
public class DataLoaderDispatcherInstrumentationState implements InstrumentationState {

    @Internal
    public static final DataLoaderRegistry EMPTY_DATALOADER_REGISTRY = new DataLoaderRegistry() {

        private static final String ERROR_MESSAGE = "You MUST set in your own DataLoaderRegistry to use data loader";

        @Override
        public DataLoaderRegistry register(String key, DataLoader<?, ?> dataLoader) {
            return Assert.assertShouldNeverHappen(ERROR_MESSAGE);
        }

        @Override
        public <K, V> DataLoader<K, V> computeIfAbsent(final String key,
                                                       final Function<String, DataLoader<?, ?>> mappingFunction) {
            return Assert.assertShouldNeverHappen(ERROR_MESSAGE);
        }

        @Override
        public DataLoaderRegistry unregister(String key) {
            return Assert.assertShouldNeverHappen(ERROR_MESSAGE);
        }
    };

    private final FieldLevelTrackingApproach approach;
    private final AtomicReference<DataLoaderRegistry> dataLoaderRegistry;
    private final InstrumentationState state;
    private volatile boolean aggressivelyBatching = true;
    private volatile boolean hasNoDataLoaders;

    public DataLoaderDispatcherInstrumentationState(DataLoaderRegistry dataLoaderRegistry) {
        this.dataLoaderRegistry = new AtomicReference<>(dataLoaderRegistry);
        this.approach = new FieldLevelTrackingApproach(this::getDataLoaderRegistry);
        this.state = approach.createState();
        hasNoDataLoaders = checkForNoDataLoader(dataLoaderRegistry);
    }

    private boolean checkForNoDataLoader(DataLoaderRegistry dataLoaderRegistry) {
        //
        // if they have never set a dataloader into the execution input then we can optimize
        // away the tracking code
        //
        return dataLoaderRegistry == EMPTY_DATALOADER_REGISTRY;
    }

    boolean isAggressivelyBatching() {
        return aggressivelyBatching;
    }

    void setAggressivelyBatching(boolean aggressivelyBatching) {
        this.aggressivelyBatching = aggressivelyBatching;
    }

    FieldLevelTrackingApproach getApproach() {
        return approach;
    }

    DataLoaderRegistry getDataLoaderRegistry() {
        return dataLoaderRegistry.get();
    }

    void setDataLoaderRegistry(DataLoaderRegistry newRegistry) {
        dataLoaderRegistry.set(newRegistry);
        hasNoDataLoaders = checkForNoDataLoader(newRegistry);
    }

    boolean hasNoDataLoaders() {
        return hasNoDataLoaders;
    }

    InstrumentationState getState() {
        return state;
    }
}


text:
module Workday
    class ResponseHelper

        # If the XML response has more than one element, it'll be an Array.
        # If it has just one element, then it will not be an Array.
        # This method will take either case and will always return an Array.
        def self.element_to_array element
            return [] if element.nil?
            element.is_a?(Array) ? element : [element]
        end

    end
end


text:
package com.gmail.trentech.simplechat.commands.chat;

import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;

import com.gmail.trentech.pjc.core.ConfigManager;
import com.gmail.trentech.pjc.help.Help;
import com.gmail.trentech.simplechat.Main;

import ninja.leaping.configurate.ConfigurationNode;

public class CMDRange implements CommandExecutor {

	@Override
	public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
		Help help = Help.get("chat range").get();

		if (args.hasAny("help")) {
			help.execute(src);
			return CommandResult.empty();
		}

		boolean bool = args.<Boolean> getOne("true|false").get();

		ConfigManager configManager = ConfigManager.get(Main.getPlugin());
		ConfigurationNode config = configManager.getConfig();

		if (args.hasAny("value")) {
			config.getNode("options", "ranged_chat", "range").setValue(args.<Integer> getOne("value").get());
		}

		config.getNode("options", "ranged_chat", "enable").setValue(bool);

		configManager.save();

		src.sendMessage(Text.of(TextColors.DARK_GREEN, "Set ranged chat to ", bool));

		return CommandResult.success();
	}

}


text:
PORT=5004
CODING_SYSTEM="utf-8-unix"

# Swank related directory and file paths.
SWANK_HOME="/var/swank"
PID_FILE="${SWANK_HOME}/screen-${PORT}.pid"
START_SCRIPT="${SWANK_HOME}/swank-start.lisp"

# Lisp implementation configurations.
LISP="/usr/bin/sbcl"
LISP_PARAMS="--no-userinit"

# Will be used user for the process.
USER="swank"

case "$1" in
start)
	echo -n "Starting swank server... "

	touch $PID_FILE
	chown $USER $PID_FILE

	# Don't specify an --ignore-environment (-i) argument for the
	# env command, otherwise it will cause STY environment
	# variable to get unexported. (STY will be written into
	# PID_FILE by swank-start.lisp script.) Same caution goes for
	# the su command too. (Beware --login (-, -l) arguments.)
	screen -d -m -c /dev/null -S swank.$PORT \
	su $USER -c "/usr/bin/env \
	             SWANK_PORT=$PORT \
		     SWANK_CODING_SYSTEM=$CODING_SYSTEM \
		     SWANK_PID_FILE=$PID_FILE \
		     $LISP $LISP_PARAMS --load $START_SCRIPT"

	[ $? -eq 0 ] && echo "done." || echo "failed!"
	;;

stop)
	echo -n "Stopping swank server... "
	STY="`cat $PID_FILE 2>/dev/null`"
	STY="`echo ${STY%%.*}`"

	# [FIXME] There should be a more feasible way of shutting down
	# a lisp instance. We don't want to lead to a corruption by
	# killing a process unexpectedly. (Interruptions might be
	# considered but they are not so portable accross different
	# lisp implementations.)
	[ -e "/proc/${STY}" ] && \
	kill "$STY" 2>/dev/null && \
	rm -f $PID_FILE

	[ $? -eq 0 ] && echo "done." || echo "failed!"
	;;

restart)
	$0 stop
	$0 start
	;;

*)
	echo "Usage: $0 <start|stop|restart>"
	;;
esac


text:
var Sails = require('sails').Sails;

describe('Basic tests ::', function() {

    // Var to hold a running sails app instance
    var sails;

    // Before running any tests, attempt to lift Sails
    before(function (done) {
        // Hook will timeout in 10 seconds
        this.timeout(11000);

        // Attempt to lift sails
        Sails().lift({
            hooks: {
                sockets: false,
                pubsub: false,
                views: false,
                http: false,
                sqlize: require('../'),
                grunt: false
            },

            connections: {
                test: {
                    adapter: 'sails-mysql',
                    host: 'localhost',
                    port: 3306,
                    user: 'root',
                    password: 'password',
                    database: 'test'
                }
            },

            models: {
                connection: 'test',
                migrate: 'drop',
                autoUpdatedAt: false,
                autoCreatedAt: false
            },

            sqlize: {
                connections: {
                    test: {
                        dialect: 'mysql',
                        pool: {
                            max: 5,
                            min: 0,
                            idle: 1000
                        },
                        logging: 'silly'
                    }
                },
                options: {
                    define: {
                        timestamps: false,
                        freezeTableName: true
                    }
                }
            },

            log: {
                level: "debug"
            }
        },function (err, _sails) {
            if (err) return done(err);
            sails = _sails;

            var barrels = new require('barrels')();

            async.series([
                function(fn) {
                    barrels.populate(['group', 'organization'], fn);
                },

                function(fn) {
                    barrels.populate(['user'], fn);
                }

            ], function(error) {
                if (error) {
                    sails.log.error('barrels error', error);
                    return done(error);
                }
                done();
            });
        });
    });

    // After tests are complete, lower Sails
    after(function (done) {

        // Lower Sails (if it successfully lifted)
        if (sails) {
            return sails.lower(done);
        }
        // Otherwise just return
        return done();
    });

    // Test that Sails can lift with the hook in place
    it ('sails does not crash', function() {
        return true;
    });
});


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class GamesAddMapRef2 extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('games', function (Blueprint $table) {
            $table->integer('map_id');
            $table->foreign('map_id')->references('id')->on('maps');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('games', function (Blueprint $table) {
            //
        });
    }
}


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Simpl.Serialization;
using Simpl.Serialization.Library.Maps;
using Simpl.Serialzation.Tests.TestHelper;

namespace Simpl.Serialzation.Tests
{
    [TestClass]
    public class MapsWithinMapsTest
    {

        [TestMethod]
        public void MapsWithinMapsTestXml()
        {
            TranslationS test = MapsWithinMaps.CreateObject();
            SimplTypesScope tScope = SimplTypesScope.Get("testScope", typeof (TranslationS),
                                                         typeof (ClassDes),
                                                         typeof (FieldDes));
            TestMethods.TestSimplObject(test, tScope, Format.Xml);
        }

        [TestMethod]
        public void MapsWithinMapsTestJson()
        {
            TranslationS test = MapsWithinMaps.CreateObject();
            SimplTypesScope tScope = SimplTypesScope.Get("testScope", typeof (TranslationS),
                                                         typeof (ClassDes),
                                                         typeof (FieldDes));
            TestMethods.TestSimplObject(test, tScope, Format.Json);
        }
    }
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Serverless.Common.Async
{
    public class AsyncLock
    {
        private SemaphoreSlim Semaphore { get; set; }

        public AsyncLock()
        {
            this.Semaphore = new SemaphoreSlim(initialCount: 1);
        }

        public async Task<AsyncLockReleaser> WaitAsync()
        {
            await this.Semaphore
                .WaitAsync()
                .ConfigureAwait(continueOnCapturedContext: false);

            return new AsyncLockReleaser(semaphore: this.Semaphore);
        }

        public class AsyncLockReleaser : IDisposable
        {
            private SemaphoreSlim Semaphore { get; set; }

            public AsyncLockReleaser(SemaphoreSlim semaphore)
            {
                this.Semaphore = semaphore;
            }

            public void Dispose()
            {
                this.Semaphore.Release();
            }
        }
    }
}


text:
package mh.smartcard.util;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import mh.smartcard.iso.Element;
import mh.smartcard.iso.Group;
import mh.smartcard.iso.Tags;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GenerateFile {
	private static final Logger logger = LoggerFactory.getLogger(GenerateFile.class);

	private static void generateAIDList() {
		Map<String, String>aidMap = Util.loadProperties(AIDList.class);

		String outPath = "src/mh/smartcard/util/AIDList.java";
		logger.info("outPath = {}", outPath);

		try (PrintWriter out = new PrintWriter(outPath)) {
			out.println("package mh.smartcard.util;");
			out.println();
			out.println("import java.util.ArrayList;");
			out.println("import java.util.List;");
			out.println("import java.util.Map;");
			out.println("import java.util.TreeMap;");
			out.println();
			out.println("import mh.smartcard.data.Hex;");
			out.println();
			out.println("public final class AIDList {");

			for(String number: aidMap.keySet()) {
				String name = aidMap.get(number);
				String javaName = name.replaceAll("-", "_");

				out.format("\t\tpublic static final String NAME_%-40s   = \"%s\";", javaName, name).println();
				out.format("\t\tpublic static final String NUMBER_%-40s = \"%s\";", javaName, number).println();
				out.println();
			}

			out.println("\tprivate static final Map<String, String> map = new TreeMap<>();");
			out.println("\tstatic {");
			for(String number: aidMap.keySet()) {
				String name = aidMap.get(number).replaceAll("-", "_");
				out.format("\t\tmap.put(NUMBER_%-40s NAME_%s);", name + ",", name).println();
			}
			out.println("\t}");
			out.println();

			for(String number: aidMap.keySet()) {
				String name = aidMap.get(number).replaceAll("-", "_");;

				out.format("\tpublic static final byte[] %-40s = Util.fromHexString(NUMBER_%s);", name, name).println();
			}

			//				out.format("\t\tmap.put(%-40s %s);", "\"" + number + "\",", "\"" + name + "\"").println();

			out.println();
			out.println("\tpublic static String getName(byte[] nuberData) {");
			out.println("\t\tString number = Hex.toString(nuberData);");
			out.println("\t\tString ret = map.get(number);");
			out.println("\t\treturn (ret != null) ? ret : (\"UNKNOWN-\" + number);");
			out.println("\t}");

			out.println();
			out.println("\tpublic static List<String> getNumberList() {");
			out.println("\t\tList<String> ret = new ArrayList<>();");
			out.println("\t\tfor(String number: map.keySet()) ret.add(number);");
			out.println("\t\treturn ret;");
			out.println("\t}");

			out.println("}");
		} catch (Exception e) {
			logger.error("Exception", e);
		}
	}

	private static void generateTagList() {
		String className = "TagList";
		String outPath = String.format("src/mh/smartcard/util/%s.java", className);
		logger.info("outPath = {}", outPath);

		// Generate TagMap.java
		try (PrintWriter out = new PrintWriter(outPath)) {
			out.println("package mh.smartcard.util;");
			out.println();
			out.println("import mh.smartcard.iso.Tags;");
			out.println();
			out.format("public final class %s {", className).println();

			for(Group group: Group.getGroupList()) {
				if (group.nameMap.isEmpty()) continue;

				out.format("\tpublic static final class %s {", group.name).println();
				for(Element e: group.nameMap.values()) {
					out.format("\t\tpublic static final Tags %-40s  = Tags.getInstance(0x%s);", e.name.name.replaceAll("-", "_").replaceAll(":", "_"), Tags.toTagString(e.tag)).println();
				}
				out.println("\t}");
			}
			out.println();

			{
				List<String> lineList = new ArrayList<>();
				for(Group group: Group.getGroupList()) {
					if (group.nameMap.isEmpty()) continue;

					out.println();
					for(Map.Entry<Tags, Element>entry: group.tagMap.entrySet()) {
						Tags    key   = entry.getKey();
						Element value = entry.getValue();
						lineList.add(String.format("\t// %-20s  %s", key, value.name.toString()));
					}

					logger.info("{} nameMap = {}", group.name, group.nameMap.size());
					logger.info("{} tagMap  = {}", group.name, group.tagMap.size());
				}

				{
					Comparator<String> stringComparator = new Comparator<String>() {
						@Override
						public int compare(String o1, String o2) {
							return o1.compareTo(o2);
						}
					};
					lineList.sort(stringComparator);
				}

				for(String line: lineList) {
					out.println(line);
				}
			}

			out.println("}");
		} catch (FileNotFoundException e) {
			logger.error("FileNotFoundException", e);
		}

		// Show stats of nameMap and tagMap
		logger.info("dataMap = {}", Element.dataMap.size());
	}

	public static void main(String[] args) {
		Element.init();

		generateTagList();
		generateAIDList();
	}
}


text:
package org.apache.cassandra.db;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;

import com.google.common.annotations.VisibleForTesting;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.composites.Composite;
import org.apache.cassandra.io.sstable.IndexHelper;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.utils.ByteBufferUtil;

public class ColumnIndex
{
    public final List<IndexHelper.IndexInfo> columnsIndex;

    private static final ColumnIndex EMPTY = new ColumnIndex(Collections.<IndexHelper.IndexInfo>emptyList());

    private ColumnIndex(List<IndexHelper.IndexInfo> columnsIndex)
    {
        assert columnsIndex != null;

        this.columnsIndex = columnsIndex;
    }

    @VisibleForTesting
    public static ColumnIndex nothing()
    {
        return EMPTY;
    }

    /**
     * Help to create an index for a column family based on size of columns,
     * and write said columns to disk.
     */
    public static class Builder
    {
        private final ColumnIndex result;
        private final long indexOffset;
        private long startPosition = -1;
        private long endPosition = 0;
        private long blockSize;
        private OnDiskAtom firstColumn;
        private OnDiskAtom lastColumn;
        private OnDiskAtom lastBlockClosing;
        private final DataOutputPlus output;
        private final RangeTombstone.Tracker tombstoneTracker;
        private int atomCount;
        private final ByteBuffer key;
        private final DeletionInfo deletionInfo; // only used for serializing and calculating row header size

        private final OnDiskAtom.Serializer atomSerializer;

        public Builder(ColumnFamily cf,
                       ByteBuffer key,
                       DataOutputPlus output)
        {
            assert cf != null;
            assert key != null;
            assert output != null;

            this.key = key;
            deletionInfo = cf.deletionInfo();
            this.indexOffset = rowHeaderSize(key, deletionInfo);
            this.result = new ColumnIndex(new ArrayList<IndexHelper.IndexInfo>());
            this.output = output;
            this.tombstoneTracker = new RangeTombstone.Tracker(cf.getComparator());
            this.atomSerializer = cf.getComparator().onDiskAtomSerializer();
        }

        /**
         * Returns the number of bytes between the beginning of the row and the
         * first serialized column.
         */
        private static long rowHeaderSize(ByteBuffer key, DeletionInfo delInfo)
        {
            TypeSizes typeSizes = TypeSizes.NATIVE;
            // TODO fix constantSize when changing the nativeconststs.
            int keysize = key.remaining();
            return typeSizes.sizeof((short) keysize) + keysize          // Row key
                 + DeletionTime.serializer.serializedSize(delInfo.getTopLevelDeletion(), typeSizes);
        }

        public RangeTombstone.Tracker tombstoneTracker()
        {
            return tombstoneTracker;
        }

        public int writtenAtomCount()
        {
            return atomCount + tombstoneTracker.writtenAtom();
        }

        /**
         * Serializes the index into in-memory structure with all required components
         * such as Bloom Filter, index block size, IndexInfo list
         *
         * @param cf Column family to create index for
         *
         * @return information about index - it's Bloom Filter, block size and IndexInfo list
         */
        public ColumnIndex build(ColumnFamily cf) throws IOException
        {
            // cf has disentangled the columns and range tombstones, we need to re-interleave them in comparator order
            Comparator<Composite> comparator = cf.getComparator();
            DeletionInfo.InOrderTester tester = cf.deletionInfo().inOrderTester();
            Iterator<RangeTombstone> rangeIter = cf.deletionInfo().rangeIterator();
            RangeTombstone tombstone = rangeIter.hasNext() ? rangeIter.next() : null;

            for (Cell c : cf)
            {
                while (tombstone != null && comparator.compare(c.name(), tombstone.min) >= 0)
                {
                    // skip range tombstones that are shadowed by partition tombstones
                    if (!cf.deletionInfo().getTopLevelDeletion().isDeleted(tombstone))
                        add(tombstone);
                    tombstone = rangeIter.hasNext() ? rangeIter.next() : null;
                }

                // We can skip any cell if it's shadowed by a tombstone already. This is a more
                // general case than was handled by CASSANDRA-2589.
                if (!tester.isDeleted(c))
                    add(c);
            }

            while (tombstone != null)
            {
                add(tombstone);
                tombstone = rangeIter.hasNext() ? rangeIter.next() : null;
            }
            ColumnIndex index = build();

            maybeWriteEmptyRowHeader();

            return index;
        }

        /**
         * The important distinction wrt build() is that we may be building for a row that ends up
         * being compacted away entirely, i.e., the input consists only of expired tombstones (or
         * columns shadowed by expired tombstone).  Thus, it is the caller's responsibility
         * to decide whether to write the header for an empty row.
         */
        //在进行Compaction时使用
        public ColumnIndex buildForCompaction(Iterator<OnDiskAtom> columns) throws IOException
        {
            while (columns.hasNext())
            {
                OnDiskAtom c =  columns.next();
                add(c);
            }

            return build();
        }

        public void add(OnDiskAtom column) throws IOException
        {
            atomCount++;

            if (firstColumn == null)
            {
                firstColumn = column;
                startPosition = endPosition;
                // TODO: have that use the firstColumn as min + make sure we optimize that on read
                endPosition += tombstoneTracker.writeOpenedMarker(firstColumn, output, atomSerializer);
                blockSize = 0; // We don't count repeated tombstone marker in the block size, to avoid a situation
                               // where we wouldn't make any progress because a block is filled by said marker
            }

            long size = atomSerializer.serializedSizeForSSTable(column);
            endPosition += size;
            blockSize += size;

            // if we hit the column index size that we have to index after, go ahead and index it.
            if (blockSize >= DatabaseDescriptor.getColumnIndexSize()) //默认是64K
            {
                IndexHelper.IndexInfo cIndexInfo = new IndexHelper.IndexInfo(firstColumn.name(), column.name(), indexOffset + startPosition, endPosition - startPosition);
                result.columnsIndex.add(cIndexInfo);
                firstColumn = null;
                lastBlockClosing = column;
            }

            maybeWriteRowHeader();
            atomSerializer.serializeForSSTable(column, output);

            // TODO: Should deal with removing unneeded tombstones
            tombstoneTracker.update(column, false);

            lastColumn = column;
        }

        //对应rowHeaderSize
        private void maybeWriteRowHeader() throws IOException
        {
            if (lastColumn == null)
            {
                ByteBufferUtil.writeWithShortLength(key, output);
                DeletionTime.serializer.serialize(deletionInfo.getTopLevelDeletion(), output);
            }
        }

        public ColumnIndex build()
        {
            // all columns were GC'd after all
            if (lastColumn == null)
                return ColumnIndex.EMPTY;

            // the last column may have fallen on an index boundary already.  if not, index it explicitly.
            if (result.columnsIndex.isEmpty() || lastBlockClosing != lastColumn)
            {
                //对每行的数据索引时会直接跳过行头,从行里面的列开始
                IndexHelper.IndexInfo cIndexInfo = new IndexHelper.IndexInfo(firstColumn.name(), lastColumn.name(), indexOffset + startPosition, endPosition - startPosition);
                result.columnsIndex.add(cIndexInfo);
            }

            // we should always have at least one computed index block, but we only write it out if there is more than that.
            assert result.columnsIndex.size() > 0;
            return result;
        }

        public void maybeWriteEmptyRowHeader() throws IOException
        {
            if (!deletionInfo.isLive())
                maybeWriteRowHeader();
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/DynamoDBResponse.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/DynamoDBResponse</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>DynamoDBResponse.h</DeclaredIn>

			<NodeRef refid="324"/>
		</Token>

	</File>
</Tokens>


text:
<?php
	error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);

    include __DIR__ . "/php/Application.php";
    include __DIR__ . "/php/Database.php";

   	$database = connect();
   	$app = new Application($database);

   	if(isset($_GET['q'])) $question = intval($_GET['q']);
   	else $question = 1;
?>

<!DOCTYPE>

		<title>UHC Voting | 2014</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

		<link href="css/bootstrap.min.css" rel="stylesheet" media="screen"/>
		<link href="css/bootstrap-responsive.min.css" rel="stylesheet" media="screen"/>
		<link href="css/main.css" rel="stylesheet" media="screen"/>

			<?php if ($app->getVoterHasVotedBefore($_SERVER['REMOTE_ADDR'])): ?>

					<button type="button" class="close" data-dismiss="alert">×</button>
					Uh-oh! It looks like you've voted before, and you may only do so once.  See results on /r/Ultrahardcore.

			<?php else: ?>

					<button type="button" class="close" data-dismiss="alert">×</button>
					Info! You have not voted before!  Choose carefully: you only get to vote once.  See results on /r/Ultrahardcore.

			<?php endif; ?>

			<div id="question" data-id="<?php echo $question; ?>" class="hero-unit">
				<?php
					$votes = $app->getNumberVotesForQuestion($question);

					echo "
";
						echo "#" . $question . " - ";
						echo $app->getQuestionTitle($question);
					echo "
";

					$nominees = $app->getNomineesFor($question);

					echo "<form class='selection'>";

					$index = 1;
					foreach ($nominees as $name) {
						echo "<input class='choice' id='choice".$index."' name='question[".$question."]' type='radio' value='".$name."'/>" . $name . "";
						$index++;
					}

					echo "

";

					echo "
";
					foreach ($nominees as $name) {
						$user_votes = $app->getVotesForNomineeQuestion($name, $question);
						$votes_per = 100 * round($user_votes / ($votes == 0 ? 1 : $votes),2);

						echo "
";
							echo "
";
								echo "";
								echo "" . $name . "";
								echo "(" . $user_votes . "/" . $votes . ")";
							echo "
";

							echo "
";
								echo "
";
									echo "

";
								echo "
";
							echo "
";
						echo "
";
					}
					echo "
";

						echo "<input type='submit' class='btn btn-large btn-primary' value='Submit!'>";
					echo "</form>";
				?>

Created by: ttaylorr for Ultrahardcore

Copyright © 2013-2014 UltrahardcoreStats