text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/window_background">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout
        android:id="@+id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone">
        <ImageView
            android:id="@+id/image_empty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="100dp"
            android:scaleType="center"/>
        <TextView
            android:text="@string/today_empty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/image_empty"
            android:layout_marginTop="30dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="?attr/colorPrimary"
            android:gravity="center"
            android:layout_centerHorizontal="true"/>
    </RelativeLayout>
</FrameLayout>


text:
#include <config.h>

#include <stdio.h>
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

#ifdef WINDOWS
# include <winsock.h>
#else
# include <sys/socket.h>
# include <netdb.h>
# include <netinet/in.h>
# include <arpa/inet.h>
#endif /* WINDOWS */

#include <errno.h>
#ifdef HAVE_STRING_H
# include <string.h>
#else
# include <strings.h>
#endif /* HAVE_STRING_H */
#ifdef HAVE_SYS_SELECT_H
# include <sys/select.h>
#endif /* HAVE_SYS_SELECT_H */

#include "wget.h"
#include "connect.h"
#include "host.h"

#ifndef errno
extern int errno;
#endif

/* Variables shared by bindport and acceptport: */
static int msock = -1;
static struct sockaddr *addr;

/* Create an internet connection to HOSTNAME on PORT.  The created
   socket will be stored to *SOCK.  */
uerr_t
make_connection (int *sock, char *hostname, unsigned short port)
{
  struct sockaddr_in sock_name;
  /* struct hostent *hptr; */

  /* Get internet address of the host.  We can do it either by calling
     ngethostbyname, or by calling store_hostaddress, from host.c.
     storehostaddress is better since it caches calls to
     gethostbyname.  */
#if 1
  if (!store_hostaddress ((unsigned char *)&sock_name.sin_addr, hostname))
    return HOSTERR;
#else  /* never */
  if (!(hptr = ngethostbyname (hostname)))
    return HOSTERR;
  /* Copy the address of the host to socket description.  */
  memcpy (&sock_name.sin_addr, hptr->h_addr, hptr->h_length);
#endif /* never */

  /* Set port and protocol */
  sock_name.sin_family = AF_INET;
  sock_name.sin_port = htons (port);

  /* Make an internet socket, stream type.  */
  if ((*sock = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    return CONSOCKERR;

  if (opt.bind_address != NULL)
    {
      /* Bind the client side to the requested address. */
      if (bind (*sock, (struct sockaddr *) opt.bind_address,
		sizeof (*opt.bind_address)))
	return CONSOCKERR;
    }

  /* Connect the socket to the remote host.  */
  if (connect (*sock, (struct sockaddr *) &sock_name, sizeof (sock_name)))
    {
      if (errno == ECONNREFUSED)
	return CONREFUSED;
      else
	return CONERROR;
    }
  DEBUGP (("Created fd %d.\n", *sock));
  return NOCONERROR;
}

/* Bind the local port PORT.  This does all the necessary work, which
   is creating a socket, setting SO_REUSEADDR option on it, then
   calling bind() and listen().  If *PORT is 0, a random port is
   chosen by the system, and its value is stored to *PORT.  The
   internal variable MPORT is set to the value of the ensuing master
   socket.  Call acceptport() to block for and accept a connection.  */
uerr_t
bindport (unsigned short *port)
{
  int optval = 1;
  static struct sockaddr_in srv;

  msock = -1;
  addr = (struct sockaddr *) &srv;
  if ((msock = socket (AF_INET, SOCK_STREAM, 0)) < 0)
    return CONSOCKERR;
  if (setsockopt (msock, SOL_SOCKET, SO_REUSEADDR,
		  (char *)&optval, sizeof (optval)) < 0)
    return CONSOCKERR;

  if (opt.bind_address == NULL)
    {
      srv.sin_family = AF_INET;
      srv.sin_addr.s_addr = htonl (INADDR_ANY);
    }
  else
    srv = *opt.bind_address;

  srv.sin_port = htons (*port);
  if (bind (msock, addr, sizeof (struct sockaddr_in)) < 0)
    {
      CLOSE (msock);
      msock = -1;
      return BINDERR;
    }
  DEBUGP (("Master socket fd %d bound.\n", msock));
  if (!*port)
    {
      size_t addrlen = sizeof (struct sockaddr_in);
      if (getsockname (msock, addr, (int *)&addrlen) < 0)
	{
	  CLOSE (msock);
	  msock = -1;
	  return CONPORTERR;
	}
      *port = ntohs (srv.sin_port);
    }
  if (listen (msock, 1) < 0)
    {
      CLOSE (msock);
      msock = -1;
      return LISTENERR;
    }
  return BINDOK;
}

#ifdef HAVE_SELECT
/* Wait for file descriptor FD to be readable, MAXTIME being the
   timeout in seconds.  If WRITEP is non-zero, checks for FD being
   writable instead.

   Returns 1 if FD is accessible, 0 for timeout and -1 for error in
   select().  */
static int
select_fd (int fd, int maxtime, int writep)
{
  fd_set fds, exceptfds;
  struct timeval timeout;

  FD_ZERO (&fds);
  FD_SET (fd, &fds);
  FD_ZERO (&exceptfds);
  FD_SET (fd, &exceptfds);
  timeout.tv_sec = maxtime;
  timeout.tv_usec = 0;
  /* HPUX reportedly warns here.  What is the correct incantation?  */
  return select (fd + 1, writep ? NULL : &fds, writep ? &fds : NULL,
		 &exceptfds, &timeout);
}
#endif /* HAVE_SELECT */

/* Call accept() on MSOCK and store the result to *SOCK.  This assumes
   that bindport() has been used to initialize MSOCK to a correct
   value.  It blocks the caller until a connection is established.  If
   no connection is established for OPT.TIMEOUT seconds, the function
   exits with an error status.  */
uerr_t
acceptport (int *sock)
{
  int addrlen = sizeof (struct sockaddr_in);

#ifdef HAVE_SELECT
  if (select_fd (msock, opt.timeout, 0) <= 0)
    return ACCEPTERR;
#endif
  if ((*sock = accept (msock, addr, &addrlen)) < 0)
    return ACCEPTERR;
  DEBUGP (("Created socket fd %d.\n", *sock));
  return ACCEPTOK;
}

/* Close SOCK, as well as the most recently remembered MSOCK, created
   via bindport().  If SOCK is -1, close MSOCK only.  */
void
closeport (int sock)
{
  /*shutdown (sock, 2);*/
  if (sock != -1)
    CLOSE (sock);
  if (msock != -1)
    CLOSE (msock);
  msock = -1;
}

/* Return the local IP address associated with the connection on FD.
   It is returned in a static buffer.  */
unsigned char *
conaddr (int fd)
{
  static unsigned char res[4];
  struct sockaddr_in mysrv;
  struct sockaddr *myaddr;
  size_t addrlen = sizeof (mysrv);

  myaddr = (struct sockaddr *) (&mysrv);
  if (getsockname (fd, myaddr, (int *)&addrlen) < 0)
    return NULL;
  memcpy (res, &mysrv.sin_addr, 4);
  return res;
}

/* Read at most LEN bytes from FD, storing them to BUF.  This is
   virtually the same as read(), but takes care of EINTR braindamage
   and uses select() to timeout the stale connections (a connection is
   stale if more than OPT.TIMEOUT time is spent in select() or
   read()).  */
int
iread (int fd, char *buf, int len)
{
  int res;

  do
    {
#ifdef HAVE_SELECT
      if (opt.timeout)
	{
	  do
	    {
	      res = select_fd (fd, opt.timeout, 0);
	    }
	  while (res == -1 && errno == EINTR);
	  if (res <= 0)
	    {
	      /* Set errno to ETIMEDOUT on timeout.  */
	      if (res == 0)
		/* #### Potentially evil!  */
		errno = ETIMEDOUT;
	      return -1;
	    }
	}
#endif
      res = READ (fd, buf, len);
    }
  while (res == -1 && errno == EINTR);

  return res;
}

/* Write LEN bytes from BUF to FD.  This is similar to iread(), but
   doesn't bother with select().  Unlike iread(), it makes sure that
   all of BUF is actually written to FD, so callers needn't bother
   with checking that the return value equals to LEN.  Instead, you
   should simply check for -1.  */
int
iwrite (int fd, char *buf, int len)
{
  int res = 0;

  /* `write' may write less than LEN bytes, thus the outward loop
     keeps trying it until all was written, or an error occurred.  The
     inner loop is reserved for the usual EINTR f*kage, and the
     innermost loop deals with the same during select().  */
  while (len > 0)
    {
      do
	{
#ifdef HAVE_SELECT
	  if (opt.timeout)
	    {
	      do
		{
		  res = select_fd (fd, opt.timeout, 1);
		}
	      while (res == -1 && errno == EINTR);
	      if (res <= 0)
		{
		  /* Set errno to ETIMEDOUT on timeout.  */
		  if (res == 0)
		    /* #### Potentially evil!  */
		    errno = ETIMEDOUT;
		  return -1;
		}
	    }
#endif
	  res = WRITE (fd, buf, len);
	}
      while (res == -1 && errno == EINTR);
      if (res <= 0)
	break;
      buf += res;
      len -= res;
    }
  return res;
}

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"
#include "HTMLTableRowElement.h"

#include "ExceptionCode.h"
#include "HTMLCollection.h"
#include "HTMLNames.h"
#include "HTMLTableCellElement.h"
#include "HTMLTableElement.h"
#include "HTMLTableSectionElement.h"
#include "NodeList.h"
#include "Text.h"

namespace WebCore {

using namespace HTMLNames;

HTMLTableRowElement::HTMLTableRowElement(const QualifiedName& tagName, Document& document)
    : HTMLTablePartElement(tagName, document)
{
    ASSERT(hasTagName(trTag));
}

PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(Document& document)
{
    return adoptRef(new HTMLTableRowElement(trTag, document));
}

PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(const QualifiedName& tagName, Document& document)
{
    return adoptRef(new HTMLTableRowElement(tagName, document));
}

int HTMLTableRowElement::rowIndex() const
{
    ContainerNode* table = parentNode();
    if (!table)
        return -1;
    table = table->parentNode();
    if (!table || !isHTMLTableElement(table))
        return -1;

    // To match Firefox, the row indices work like this:
    //   Rows from the first <thead> are numbered before all <tbody> rows.
    //   Rows from the first <tfoot> are numbered after all <tbody> rows.
    //   Rows from other <thead> and <tfoot> elements don't get row indices at all.

    int rIndex = 0;

    if (HTMLTableSectionElement* head = toHTMLTableElement(table)->tHead()) {
        for (Node *row = head->firstChild(); row; row = row->nextSibling()) {
            if (row == this)
                return rIndex;
            if (row->hasTagName(trTag))
                ++rIndex;
        }
    }

    for (Node *node = table->firstChild(); node; node = node->nextSibling()) {
        if (node->hasTagName(tbodyTag)) {
            HTMLTableSectionElement* section = toHTMLTableSectionElement(node);
            for (Node* row = section->firstChild(); row; row = row->nextSibling()) {
                if (row == this)
                    return rIndex;
                if (row->hasTagName(trTag))
                    ++rIndex;
            }
        }
    }

    if (HTMLTableSectionElement* foot = toHTMLTableElement(table)->tFoot()) {
        for (Node *row = foot->firstChild(); row; row = row->nextSibling()) {
            if (row == this)
                return rIndex;
            if (row->hasTagName(trTag))
                ++rIndex;
        }
    }

    // We get here for rows that are in <thead> or <tfoot> sections other than the main header and footer.
    return -1;
}

int HTMLTableRowElement::sectionRowIndex() const
{
    int rIndex = 0;
    const Node *n = this;
    do {
        n = n->previousSibling();
        if (n && n->hasTagName(trTag))
            rIndex++;
    }
    while (n);

    return rIndex;
}

PassRefPtr<HTMLElement> HTMLTableRowElement::insertCell(int index, ExceptionCode& ec)
{
    RefPtr<HTMLCollection> children = cells();
    int numCells = children ? children->length() : 0;
    if (index < -1 || index > numCells) {
        ec = INDEX_SIZE_ERR;
        return 0;
    }

    RefPtr<HTMLTableCellElement> cell = HTMLTableCellElement::create(tdTag, document());
    if (index < 0 || index >= numCells)
        appendChild(cell, ec);
    else {
        Node* n;
        if (index < 1)
            n = firstChild();
        else
            n = children->item(index);
        insertBefore(cell, n, ec);
    }
    return cell.release();
}

void HTMLTableRowElement::deleteCell(int index, ExceptionCode& ec)
{
    RefPtr<HTMLCollection> children = cells();
    int numCells = children ? children->length() : 0;
    if (index == -1)
        index = numCells-1;
    if (index >= 0 && index < numCells) {
        RefPtr<Node> cell = children->item(index);
        HTMLElement::removeChild(cell.get(), ec);
    } else
        ec = INDEX_SIZE_ERR;
}

PassRefPtr<HTMLCollection> HTMLTableRowElement::cells()
{
    return ensureCachedHTMLCollection(TRCells);
}

void HTMLTableRowElement::setCells(HTMLCollection*, ExceptionCode& ec)
{
    ec = NO_MODIFICATION_ALLOWED_ERR;
}

}


text:
set  system parameters 'dont_reuse_heap_file=yes';
CREATE TABLE bugs (bugID BIGINT not null,CreationDate TIMESTAMP,Author VARCHAR(255),Subject VARCHAR(255),CurrentStatus INTEGER, Closed SMALLINT);
insert into bugs values(1,TIMESTAMP '2010-10-31 01:15:45','yin','test',1,0);
CREATE INDEX open_bugs ON bugs(bugID);
CREATE INDEX open_bugs1 ON bugs(bugID) WHERE Closed = 0;
CREATE INDEX open_bugs2 ON bugs(bugID) WHERE bugID is not null;
drop table bugs;

CREATE TABLE bugs (bugID BIGINT not null,CreationDate TIMESTAMP,Author VARCHAR(255),Subject VARCHAR(255),CurrentStatus INTEGER, Closed SMALLINT);
insert into bugs values(1,TIMESTAMP '2010-10-31 01:15:45','yin','test',1,0);
CREATE INDEX open_bugs ON bugs(bugID) WHERE bugID is not null;
CREATE INDEX open_bugs1 ON bugs(bugID) WHERE Closed = 0;
drop table bugs ;

CREATE TABLE bugs (bugID BIGINT not null,CreationDate TIMESTAMP,Author VARCHAR(255),Subject VARCHAR(255),CurrentStatus INTEGER, Closed SMALLINT);
insert into bugs values(1,TIMESTAMP '2010-10-31 01:15:45','yin','test',1,0);
CREATE INDEX open_bugs ON bugs(bugID) WHERE  Closed >=0 ;
CREATE INDEX open_bugs1 ON bugs(bugID) WHERE Closed = 0;
drop table bugs ;

CREATE TABLE bugs (bugID BIGINT not null,CreationDate TIMESTAMP,Author VARCHAR(255),Subject VARCHAR(255),CurrentStatus INTEGER, Closed SMALLINT);
insert into bugs values(1,TIMESTAMP '2010-10-31 01:15:45','yin','test',1,0);
CREATE INDEX open_bugs ON bugs(bugID) WHERE Closed =0 and CreationDate > '2010-10-30 01:15:45';
CREATE INDEX open_bugs1 ON bugs(bugID) WHERE Closed =0 and CreationDate > '2010-10-29 01:15:45';
drop table bugs ;

CREATE TABLE bugs (bugID BIGINT not null,CreationDate TIMESTAMP,Author VARCHAR(255),Subject VARCHAR(255),CurrentStatus INTEGER, Closed SMALLINT);
insert into bugs values(1,TIMESTAMP '2010-10-31 01:15:45','yin','test',1,0);
CREATE INDEX open_bugs ON bugs(bugID) WHERE Closed =0 and CreationDate > '2010-10-30 01:15:45';
CREATE INDEX open_bugs1 ON bugs(bugID) WHERE Closed =0 and CreationDate <= '2010-10-30 01:15:45';

CREATE INDEX open_bugs2 ON bugs(bugID) WHERE Closed <>0 and CreationDate <= '2010-10-30 01:15:45';

CREATE INDEX open_bugs2 ON bugs(bugID) WHERE Closed <>0 and CreationDate > '2010-10-30 01:15:45';
drop table bugs ;
set  system parameters 'dont_reuse_heap_file=no';
commit;
--+ holdcas off;


text:
using System;

namespace Azure.ResourceManager.ConnectedVMwarevSphere.Models
{
    /// <summary> Instance view status. </summary>
    public partial class MachineExtensionInstanceViewStatus
    {
        /// <summary> Initializes a new instance of MachineExtensionInstanceViewStatus. </summary>
        public MachineExtensionInstanceViewStatus()
        {
        }

        /// <summary> Initializes a new instance of MachineExtensionInstanceViewStatus. </summary>
        /// <param name="code"> The status code. </param>
        /// <param name="level"> The level code. </param>
        /// <param name="displayStatus"> The short localizable label for the status. </param>
        /// <param name="message"> The detailed status message, including for alerts and error messages. </param>
        /// <param name="time"> The time of the status. </param>
        internal MachineExtensionInstanceViewStatus(string code, MachineExtensionStatusLevelType? level, string displayStatus, string message, DateTimeOffset? time)
        {
            Code = code;
            Level = level;
            DisplayStatus = displayStatus;
            Message = message;
            Time = time;
        }

        /// <summary> The status code. </summary>
        public string Code { get; }
        /// <summary> The level code. </summary>
        public MachineExtensionStatusLevelType? Level { get; }
        /// <summary> The short localizable label for the status. </summary>
        public string DisplayStatus { get; }
        /// <summary> The detailed status message, including for alerts and error messages. </summary>
        public string Message { get; }
        /// <summary> The time of the status. </summary>
        public DateTimeOffset? Time { get; }
    }
}


text:
#ifndef PKSAV_MATH_ENDIAN_H
#define PKSAV_MATH_ENDIAN_H

#include <pksav/config.h>

#include <stdint.h>

#ifndef __DOXYGEN__
#if defined(PKSAV_PLATFORM_WIN32) || defined(PKSAV_PLATFORM_MINGW)
#    include <stdlib.h>
#    define PKSAV_BYTESWAP16(num) _byteswap_ushort(num)
#    define PKSAV_BYTESWAP32(num) _byteswap_ulong(num)
#elif defined(PKSAV_PLATFORM_LINUX)
#    include <byteswap.h>
#    define PKSAV_BYTESWAP16(num) bswap_16(num)
#    define PKSAV_BYTESWAP32(num) bswap_32(num)
#elif defined(PKSAV_PLATFORM_MACOS)
#    include <libkern/OSByteOrder.h>
#    define PKSAV_BYTESWAP16(num) OSSwapInt16(num)
#    define PKSAV_BYTESWAP32(num) OSSwapInt32(num)
#else
#    define PKSAV_BYTESWAP16(num) (((num & 0xFF) << 8) | ((num & 0xFF00) >> 8))
#    define PKSAV_BYTESWAP32(num) ((PKSAV_BYTESWAP16((uint16_t)(num & 0xFFFF)) << 16) | \
                                   (PKSAV_BYTESWAP16((uint16_t)((num & 0xFFFF0000) >> 16))))
#endif
#endif /* __DOXYGEN__ */

#ifdef __cplusplus
extern "C" {
#endif

/*!
 * @brief Swaps the endianness (byte ordering) of a 16-bit number.
 *
 * When possible, this function uses an optimized version of this
 * operation provided by the operating system.
 */
static PKSAV_INLINE uint16_t pksav_byteswap16(uint16_t num) {
    return PKSAV_BYTESWAP16(num);
}

/*!
 * @brief Swaps the endianness of a given 16-bit number to/from big-endian.
 *
 * On big-endian platforms, this simply returns the given number.
 */
static PKSAV_INLINE uint16_t pksav_bigendian16(uint16_t num) {
#if PKSAV_LITTLE_ENDIAN
    return pksav_byteswap16(num);
#else
    return num;
#endif
}

/*!
 * @brief Swaps the endianness of a given 16-bit number to/from little-endian.
 *
 * On little-endian platforms, this simply returns the given number.
 */
static PKSAV_INLINE uint16_t pksav_littleendian16(uint16_t num) {
#if PKSAV_LITTLE_ENDIAN
    return num;
#else
    return pksav_byteswap16(num);
#endif
}

/*!
 * @brief Swaps the endianness (byte ordering) of a 32-bit number.
 *
 * When possible, this function uses an optimized version of this
 * operation provided by the operating system.
 */
static PKSAV_INLINE uint32_t pksav_byteswap32(uint32_t num) {
    return PKSAV_BYTESWAP32(num);
}

/*!
 * @brief Swaps the endianness of a given 32-bit number to/from big-endian.
 *
 * On big-endian platforms, this simply returns the given number.
 */
static PKSAV_INLINE uint32_t pksav_bigendian32(uint32_t num) {
#if PKSAV_LITTLE_ENDIAN
    return pksav_byteswap32(num);
#else
    return num;
#endif
}

/*!
 * @brief Swaps the endianness of a given 32-bit number to/from little-endian.
 *
 * On little-endian platforms, this simply returns the given number.
 */
static PKSAV_INLINE uint32_t pksav_littleendian32(uint32_t num) {
#if PKSAV_LITTLE_ENDIAN
    return num;
#else
    return pksav_byteswap32(num);
#endif
}

#ifdef __cplusplus
}
#endif

#endif


text:
from .classes import *
from .lotes import *


text:
/* ###
 * IP: GHIDRA
 *
 * 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.
 */
package ghidra.app.util.bin.format.pdb2.pdbreader;

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

/**
 * This class is the version of {@link TypeProgramInterface} for Microsoft v8.00 PDB.
 */
public class TypeProgramInterface800 extends TypeProgramInterface {

	//==============================================================================================
	// API
	//==============================================================================================
	/**
	 * Constructor
	 * @param pdb {@link AbstractPdb} that owns this {@link TypeProgramInterface}
	 * @param recordCategory the RecordCategory of these records
	 * @param streamNumber the stream number that contains the {@link TypeProgramInterface}
	 */
	public TypeProgramInterface800(AbstractPdb pdb, RecordCategory recordCategory,
			int streamNumber) {
		super(pdb, recordCategory, streamNumber);
	}

	//==============================================================================================
	// Abstract Methods
	//==============================================================================================
	@Override
	protected void deserializeHeader(PdbByteReader reader) throws PdbException {
		versionNumber = reader.parseInt();
		headerLength = reader.parseInt();
		typeIndexMin = reader.parseInt();
		typeIndexMaxExclusive = reader.parseInt();
		dataLength = reader.parseInt();
		hash.deserializeHeader800(reader);
	}

	@Override
	protected void dumpHeader(Writer writer) throws IOException {
		StringBuilder builder = new StringBuilder();
		builder.append("\nversionNumber: ");
		builder.append(versionNumber);
		builder.append("\nheaderLength: ");
		builder.append(headerLength);
		builder.append("\ntypeIndexMin: ");
		builder.append(typeIndexMin);
		builder.append("\ntypeIndexMaxExclusive: ");
		builder.append(typeIndexMaxExclusive);
		builder.append("\ndataLength: ");
		builder.append(dataLength);
		builder.append("\n");
		builder.append(hash.dump());
		writer.write(builder.toString());
	}

}


text:
<?php

namespace Elastica\Processor\Traits;

trait IgnoreFailureTrait
{
    /**
     * Set "ignore_failure" option.
     *
     * @return $this
     */
    public function setIgnoreFailure(bool $ignoreFailure): self
    {
        return $this->setParam('ignore_failure', $ignoreFailure);
    }
}


text:
class TargetTestable
{
public:
	virtual ~TargetTestable() {}
	virtual bool TestTarget(void * obj) = 0;
	virtual void AddToTarget(void * obj) = 0;
	virtual void HighLight(bool highlight) = 0;
};


text:
require 'spec_helper'

module TracLang

RSpec.describe Octal do

  describe '.new' do
    context 'given no arguments' do
      it 'creates zero' do
        expect(Octal.new.value).to eq(0)
      end
    end

    context 'given one string argument' do
      it 'creates octal' do
        expect(Octal.new('abc')).to be_instance_of(Octal)
      end
    end

    context 'given empty string' do
      it 'creates empty value' do
        expect(Octal.new('').value).to eq(0)
        expect(Octal.new('').size).to eq(0)
      end
    end

    context 'given non-string argument' do
      it 'rasise arugment error' do
        expect { Octal.new(123) }.to raise_error(ArgumentError)
      end
    end

    context 'given multiple arguments' do
      it 'raises argument error' do
        expect { Octal.new(1, 2) }.to raise_error(ArgumentError)
      end
    end

  end

  describe '.value' do
    context 'given mixed string' do
      before(:example) do
        @i = Octal.new('abc123')
      end

      it 'converts numeric portion' do
        expect(@i.value).to eq(0123)
        expect(@i.size).to eq(3)
      end
    end

    context 'given mixed numeric' do
      it 'only converts trailing octal digits' do
        expect(Octal.new('1995').value).to eq(5)
        expect(Octal.new('2019').value).to eq(0)
        expect(Octal.new('07').value).to eq(7)
      end
    end

  end

  describe '.size' do
    context 'given mixed numeric' do
      it 'only counts trailing octal digits' do
        expect(Octal.new('1995').size).to eq(1)
        expect(Octal.new('2019').size).to eq(0)
        expect(Octal.new('07').size).to eq(2)
      end
    end
  end

  describe '.==' do
    it 'compares size and value' do
      expect(Octal.new('007') == Octal.new('7')).to be false
    end
    it 'ignores string prefix' do
      expect(Octal.new('a7') == Octal.new('b7')).to be true
    end
  end

  describe 'to_s' do
    it 'converts octal to string' do
      expect(Octal.new('007').to_s).to eq('007')
    end

    it 'handles negatives correctly' do
      expect(Octal.new('717').to_s).to eq('717')
    end

  end

  describe 'bitwise and' do
    it 'calculates correctly' do
      expect((Octal.new('16') & Octal.new('1')).to_s).to eq('0')
    end
  end

  describe 'bitwise or' do
    it 'calculates correctly' do
      expect((Octal.new('70') | Octal.new('7')).to_s).to eq('77')
    end
  end

  describe 'bit complement' do
    it 'creates new Octal' do
      expect(~Octal.new('07')).to be_instance_of(Octal)
    end

    it 'calculates correctly' do
      expect((~Octal.new('07')).to_s).to eq('70')
      expect((~Octal.new('761')).to_s).to eq('016')
    end
  end

  describe 'bit shift' do
    it 'calculates correctly' do
      expect(Octal.new('7').shift(Decimal.new('-1')).to_s).to eq('3')
    end
  end

  describe 'bit rotate' do
    before do
      @dpos = Decimal.new('1')
      @dneg = Decimal.new('-1')
    end
    it 'calculates correctly' do
      expect(Octal.new('7').rotate(@dpos).to_s).to eq('7')
      expect(Octal.new('7').rotate(@dneg).to_s).to eq('7')
      expect(Octal.new('5').rotate(@dpos).to_s).to eq('3')
      expect(Octal.new('3').rotate(@dneg).to_s).to eq('5')
    end
  end
end

end


text:
package com.github.tckz916.blastadmin;

import com.github.tckz916.blastadmin.command.tabcomplete.GamemodeTabComplete;
import com.github.tckz916.blastadmin.command.tabcomplete.PrefixTabComple;
import com.github.tckz916.blastadmin.listener.PlayerListener;
import com.github.tckz916.blastadmin.message.Message;
import com.github.tckz916.blastadmin.message.MessageFormat;
import org.bukkit.command.TabCompleter;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;

/**
 * Created by tckz916 on 2015/07/20.
 */
public class BlastAdmin extends JavaPlugin {

    private static BlastAdmin instance = null;

    private Message message = null;

    private MessageFormat messageFormat = null;

    @Override
    public void onEnable() {
        super.onEnable();

        instance = this;

        message = new Message();
        messageFormat = new MessageFormat();

        saveDefaultConfig();
        reloadConfig();

        registercommand("blastadmin");
        registercommand("day");
        registercommand("gamemode");
        registercommand("iteminfo");
        registercommand("night");
        registercommand("mobhead");
        registercommand("prefix");
        registercommand("serverinfo");
        registercommand("setspawn");
        registercommand("spawn");
        registercommand("tp");
        registercommand("tpa");
        registercommand("tphere");
        registercommand("whois");
        registercommand("tell");
        registercommand("reply");

        registertabcomplete("prefix", new PrefixTabComple());
        registertabcomplete("gamemode", new GamemodeTabComplete());

        registerlistener(new PlayerListener());
    }

    @Override
    public void onDisable() {
        super.onDisable();
    }

    private void registercommand(String cmd) {
        getCommand(cmd).setExecutor(new BlastAdminCommandHandler());
    }

    private void registertabcomplete(String cmd, TabCompleter completer) {
        getCommand(cmd).setTabCompleter(completer);
    }

    private void registerlistener(Listener listener) {
        this.getServer().getPluginManager().registerEvents(listener, this);
    }

    public Message getMessage() {
        return message;
    }

    public MessageFormat getMessageFormat() {
        return messageFormat;
    }

    public static BlastAdmin getInstance() {
        return instance;
    }
}


text:
MfgBatchx.order_class = 'MfgOrderx::Order'
MfgBatchx.rfq_class = 'JobshopRfqx::Rfq'
MfgBatchx.show_rfq_path = 'jobshop_rfqx.rfq_path(r.rfq_id)'
MfgBatchx.warehouse_checkin_path = "produced_item_warehousex.new_item_path(:batch_id => @batch.id, :name => @rfq.product_name + ' ' + @rfq.drawing_num, :qty => @batch.qty_produced)"
MfgBatchx.warehouse_item_class = 'ProducedItemWarehousex::Item'
MfgBatchx.customer_class = 'Kustomerx::Customer'


text:
namespace ArffSharp.ArffAttributes
{
    class ArffAttributeString : ArffAttribute
    {

        /// <summary>
        /// Initializes a new instance of the <see cref="ArffAttributeString"/> class.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="name">The name.</param>
        public ArffAttributeString(int index, string name)
            : base(index, name)
        {
            TypeKeyWord = "string";
        }
    }
}


text:
<?php

declare (strict_types=1);
namespace Jacoby\Intervention\PhpParser\Node;

use Jacoby\Intervention\PhpParser\NodeAbstract;
class Name extends NodeAbstract
{
    /**
     * @var string[] Parts of the name
     */
    public $parts;
    private static $specialClassNames = ['self' => \true, 'parent' => \true, 'static' => \true];
    /**
     * Constructs a name node.
     *
     * @param string|string[]|self $name       Name as string, part array or Name instance (copy ctor)
     * @param array                $attributes Additional attributes
     */
    public function __construct($name, array $attributes = [])
    {
        parent::__construct($attributes);
        $this->parts = self::prepareName($name);
    }
    public function getSubNodeNames() : array
    {
        return ['parts'];
    }
    /**
     * Gets the first part of the name, i.e. everything before the first namespace separator.
     *
     * @return string First part of the name
     */
    public function getFirst() : string
    {
        return $this->parts[0];
    }
    /**
     * Gets the last part of the name, i.e. everything after the last namespace separator.
     *
     * @return string Last part of the name
     */
    public function getLast() : string
    {
        return $this->parts[\count($this->parts) - 1];
    }
    /**
     * Checks whether the name is unqualified. (E.g. Name)
     *
     * @return bool Whether the name is unqualified
     */
    public function isUnqualified() : bool
    {
        return 1 === \count($this->parts);
    }
    /**
     * Checks whether the name is qualified. (E.g. Name\Name)
     *
     * @return bool Whether the name is qualified
     */
    public function isQualified() : bool
    {
        return 1 < \count($this->parts);
    }
    /**
     * Checks whether the name is fully qualified. (E.g. \Name)
     *
     * @return bool Whether the name is fully qualified
     */
    public function isFullyQualified() : bool
    {
        return \false;
    }
    /**
     * Checks whether the name is explicitly relative to the current namespace. (E.g. namespace\Name)
     *
     * @return bool Whether the name is relative
     */
    public function isRelative() : bool
    {
        return \false;
    }
    /**
     * Returns a string representation of the name itself, without taking taking the name type into
     * account (e.g., not including a leading backslash for fully qualified names).
     *
     * @return string String representation
     */
    public function toString() : string
    {
        return \implode('\\', $this->parts);
    }
    /**
     * Returns a string representation of the name as it would occur in code (e.g., including
     * leading backslash for fully qualified names.
     *
     * @return string String representation
     */
    public function toCodeString() : string
    {
        return $this->toString();
    }
    /**
     * Returns lowercased string representation of the name, without taking the name type into
     * account (e.g., no leading backslash for fully qualified names).
     *
     * @return string Lowercased string representation
     */
    public function toLowerString() : string
    {
        return \strtolower(\implode('\\', $this->parts));
    }
    /**
     * Checks whether the identifier is a special class name (self, parent or static).
     *
     * @return bool Whether identifier is a special class name
     */
    public function isSpecialClassName() : bool
    {
        return \count($this->parts) === 1 && isset(self::$specialClassNames[\strtolower($this->parts[0])]);
    }
    /**
     * Returns a string representation of the name by imploding the namespace parts with the
     * namespace separator.
     *
     * @return string String representation
     */
    public function __toString() : string
    {
        return \implode('\\', $this->parts);
    }
    /**
     * Gets a slice of a name (similar to array_slice).
     *
     * This method returns a new instance of the same type as the original and with the same
     * attributes.
     *
     * If the slice is empty, null is returned. The null value will be correctly handled in
     * concatenations using concat().
     *
     * Offset and length have the same meaning as in array_slice().
     *
     * @param int      $offset Offset to start the slice at (may be negative)
     * @param int|null $length Length of the slice (may be negative)
     *
     * @return static|null Sliced name
     */
    public function slice(int $offset, int $length = null)
    {
        $numParts = \count($this->parts);
        $realOffset = $offset < 0 ? $offset + $numParts : $offset;
        if ($realOffset < 0 || $realOffset > $numParts) {
            throw new \OutOfBoundsException(\sprintf('Offset %d is out of bounds', $offset));
        }
        if (null === $length) {
            $realLength = $numParts - $realOffset;
        } else {
            $realLength = $length < 0 ? $length + $numParts - $realOffset : $length;
            if ($realLength < 0 || $realLength > $numParts) {
                throw new \OutOfBoundsException(\sprintf('Length %d is out of bounds', $length));
            }
        }
        if ($realLength === 0) {
            // Empty slice is represented as null
            return null;
        }
        return new static(\array_slice($this->parts, $realOffset, $realLength), $this->attributes);
    }
    /**
     * Concatenate two names, yielding a new Name instance.
     *
     * The type of the generated instance depends on which class this method is called on, for
     * example Name\FullyQualified::concat() will yield a Name\FullyQualified instance.
     *
     * If one of the arguments is null, a new instance of the other name will be returned. If both
     * arguments are null, null will be returned. As such, writing
     *     Name::concat($namespace, $shortName)
     * where $namespace is a Name node or null will work as expected.
     *
     * @param string|string[]|self|null $name1      The first name
     * @param string|string[]|self|null $name2      The second name
     * @param array                     $attributes Attributes to assign to concatenated name
     *
     * @return static|null Concatenated name
     */
    public static function concat($name1, $name2, array $attributes = [])
    {
        if (null === $name1 && null === $name2) {
            return null;
        } elseif (null === $name1) {
            return new static(self::prepareName($name2), $attributes);
        } elseif (null === $name2) {
            return new static(self::prepareName($name1), $attributes);
        } else {
            return new static(\array_merge(self::prepareName($name1), self::prepareName($name2)), $attributes);
        }
    }
    /**
     * Prepares a (string, array or Name node) name for use in name changing methods by converting
     * it to an array.
     *
     * @param string|string[]|self $name Name to prepare
     *
     * @return string[] Prepared name
     */
    private static function prepareName($name) : array
    {
        if (\is_string($name)) {
            if ('' === $name) {
                throw new \InvalidArgumentException('Name cannot be empty');
            }
            return \explode('\\', $name);
        } elseif (\is_array($name)) {
            if (empty($name)) {
                throw new \InvalidArgumentException('Name cannot be empty');
            }
            return $name;
        } elseif ($name instanceof self) {
            return $name->parts;
        }
        throw new \InvalidArgumentException('Expected string, array of parts or Name instance');
    }
    public function getType() : string
    {
        return 'Name';
    }
}


text:
<?php

namespace Tests\Helper;

// here you can define custom actions
// all public methods declared in helper class will be available in $I

use Codeception\Module;

class Integration extends Module
{
}


text:
@interface SyntaxPatternItem : NSObject <SyntaxItemProtocol>
@property id<SyntaxPatternsDelegate> patterns;
- (id)initWithEmbedPatterns:(id<SyntaxPatternsDelegate>)embedP;

@end


text:
<?php

namespace Neutrino\Assets\Closure;

/**
 * Class JqueryIdHack
 *
 * @package Neutrino\Assets\Closure
 */
class JqueryIdPrecompilation extends Precompilation
{

    /**
     * Speed up jQuery ID Selector
     * Add function :
     * function jQuerySelectorSpeedhack(id) {
     *     return jQuery(document.getElementById(id))
     * }
     *
     * Replace :
     *  jQuery('#someid')   > jQuerySelectorSpeedhack('someid')
     *  $('#someid')        > jQuerySelectorSpeedhack('someid')
     *
     *  $('#someid .test')                      > jQuerySelectorSpeedhack('someid').find('.test')
     *  $('#someid li[data="test"]')            > jQuerySelectorSpeedhack('someid').find('li[data="test"]')
     *  $('#someid .item > span:not(.selected)')  > jQuerySelectorSpeedhack('someid').find('.item span:not(.selected)')
     *
     * @param $content
     *
     * @return string
     */
    public function precompile($content)
    {
        $selector = <<<JS
/**
* @param {string} id
* @return {(*|Window|Document|Element|Array<Element>|string|NodeList)}
*/
function jQuerySelectorSpeedhack(id) {
    return jQuery(document.getElementById(id))
}
JS;

        $content = preg_replace_callback(
            '/(jQuery|\$)\(\s*["\']#([\w\\\.-]+)["\']\s*\)/',
            function ($matches) {
                return "jQuerySelectorSpeedhack('" . str_replace('\\\\', '', $matches[2]) . "')";
            },
            $content
        );

        $content = preg_replace_callback(
            '/(jQuery|\$)\(\s*["\']#([\w\\\.-]+) ([ \w!"#$%&\'\(\)*+.\/:;<=>\?@\[\\\\\]^`\{\|\}~-]+)["\']\s*\)/',
            function ($matches) {
                return "jQuerySelectorSpeedhack('" . str_replace('\\\\', '', $matches[2]) . "').find('{$matches[3]}')";
            },
            $content
        );

        return $selector . $content;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Tournaments
{
    public partial class Contact : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
#define REMOTE_CONSOLE
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic; // e.g. Interaction.InputBox, MsgBox, MsgBoxResult etc.
using System.Diagnostics;
#if NETCF
using Microsoft.WindowsCE.Forms;
#endif
using System.IO;

namespace DeviceMenuTesting
{
    class FormMenu : ConsoleMenuTesting.MenuSystem
    {
        volatile bool _disposed;
        TextBox tb;
        Label labelPause;
        Menu parentMenu;
        MenuItem itemUnpause, itemClearConsole, itemDoException;
#if !NETCF
        FormsMenuTesting.FormReadAddr _formReadAddress = new FormsMenuTesting.FormReadAddr();
#endif

        public FormMenu(TextBox tb, Menu parentMenu, Label labelPause)
        {
            this.tb = tb;
            this.tb.Disposed += new EventHandler(tb_Disposed);
            this.labelPause = labelPause;
            this.parentMenu = parentMenu;
            SetupPauseControls();
            LoadKnownAddresses();
        }

        void tb_Disposed(object sender, EventArgs e)
        {
            _disposed = true;
            SaveKnownAddresses();
        }

        Dictionary<string, MenuItem> m_subMenus = new Dictionary<string, MenuItem>();

        public override void RunMenu()
        {
            if (this.tb.InvokeRequired)
                throw new InvalidOperationException("Must be called from the main thread.");
            itemUnpause = new MenuItem();
            itemUnpause.Enabled = false;
            itemUnpause.Text = "Un-pause";
            itemUnpause.Click += Unpause_Click;
            this.parentMenu.MenuItems.Add(itemUnpause);
            //
            itemClearConsole = new MenuItem();
            itemClearConsole.Text = "Clear console";
            itemClearConsole.Click += ClearConsole_Click;
            this.parentMenu.MenuItems.Add(itemClearConsole);
            //
#if NETCF && REMOTE_CONSOLE
            MenuItem itemX = new MenuItem();
            itemX.Text = "Remote console";
            itemX.Click += RemoteConsole_Click;
            this.parentMenu.MenuItems.Add(itemX);
#else
            // Keep the compiler happy.
            _secondConsole = null;
#endif
            //
            MenuItem itemY = new MenuItem();
            itemY.Text = "Save text";
            itemY.Click += SaveText_Click;
            this.parentMenu.MenuItems.Add(itemY);
            //
            itemDoException = new MenuItem();
            itemDoException.Text = "Unhandled Exception";
            itemDoException.Click += delegate
            {
                if (!this.ReadYesNo("Throw exception", false)) return;
                throw new RankException("DeviceMenuTesting manual exception.");
            };
            this.parentMenu.MenuItems.Add(itemDoException);
            //
            foreach (ConsoleMenuTesting.Option cur in Options) {
                MenuItem item = new MenuItem();
                var label = cur.name;
                label = label.Replace('_', '&');
                item.Text = label;
                item.Click += cur.EventHandlerInvokeOnBackground;
                if (cur.SubMenu == null || cur.SubMenu == RootName) {
                    this.parentMenu.MenuItems.Add(item);
                } else {
                    if (!m_subMenus.ContainsKey(cur.SubMenu)) {
                        MenuItem newSubMenu = new MenuItem();
                        newSubMenu.Text = cur.SubMenu;
                        m_subMenus.Add(cur.SubMenu, newSubMenu);
                        this.parentMenu.MenuItems.Add(newSubMenu);
                    }
                    MenuItem subMenu = m_subMenus[cur.SubMenu];
                    subMenu.MenuItems.Add(item);
                }
            }//for
        }

        //----
#if NETCF && REMOTE_CONSOLE
        void RemoteConsole_Click(object sender, EventArgs e)
        {
            if (!ReadYesNo("Connect to Remote console (port " + RemoteConsole.Port + ")", false))
                return;
            if (_secondConsole != null) {
                var msg = "Remote Console already active!";
                SafeMsgBox(msg, "Warning", MsgBoxStyle.Information);
                return;
            }
            _secondConsole = new RemoteConsole(this);
        }
#endif

        void SaveText_Click(object sender, EventArgs e)
        {
            using (var f = System.IO.File.CreateText("output.txt")) {
                f.WriteLine(this.tb.Text);
            }
        }

        //--------
        const string NewLine = "\r\n";

        IAuxConsole _secondConsole;

        void SafeAppendText(string txt)
        {
            if (_secondConsole != null) {
                _secondConsole.AppendText(txt);
            }
            //
            EventHandler dlgt = delegate
            {
                tb.Text += txt;
            };
            SafeInvoke(tb, dlgt);
        }

        void SafeSetText(string txt)
        {
            EventHandler dlgt = delegate
            {
                tb.Text = txt;
            };
            SafeInvoke(tb, dlgt);
        }

        private void SafeInvoke(Control c, EventHandler dlgt)
        {
            if (_disposed) {
                return;
            }
            if (c.InvokeRequired) {
                c.Invoke(dlgt);
            } else {
                dlgt.Invoke(c, EventArgs.Empty);
            }
        }

        public /*override*/ void Clear()
        {
            SafeSetText(string.Empty);
        }

        public override void WriteLine(string msg)
        {
            SafeAppendText(msg + NewLine);
        }
        public override void Write(string msg)
        {
            SafeAppendText(msg);
        }

        public override void WriteLine(object arg0)
        {
            WriteLine(arg0.ToString());
        }

        public override void WriteLine(string fmt, params object[] args)
        {
            WriteLine(string.Format(fmt, args));
        }
        public override void Write(string fmt, params object[] args)
        {
            Write(string.Format(fmt, args));
        }

        string SafeReadLine(string prompt, string title)
        {
            string txt = "eeeeeeh";
            EventHandler dlgt = delegate
            {
                txt = Interaction.InputBox(prompt, title,
                null, -1, -1);
            };
            SafeInvoke(this.tb, dlgt);
            return txt;
        }

        string SafeReadBluetoothAddress(string prompt, string title)
        {
#if NETCF
            return SafeReadLine(prompt, title);
#else
            string txt = "eeeeeeh";
            EventHandler dlgt = delegate {
                _formReadAddress.SetPrompt(prompt, title);
                var rslt = _formReadAddress.ShowDialog();
                if (rslt == DialogResult.OK) {
                    txt = _formReadAddress.Line;
                } else {
                    txt = null;
                }
            };
            SafeInvoke(this.tb, dlgt);
            return txt;
#endif
        }

        MsgBoxResult SafeMsgBox(string prompt, string title,
            MsgBoxStyle buttons)
        {
            MsgBoxResult result = MsgBoxResult.Cancel;
            EventHandler dlgt = delegate
            {
                result = Interaction.MsgBox(prompt, buttons,
                    title);
            };
            SafeInvoke(this.tb, dlgt);
            return result;
        }

        //--------
        public override string ReadLine(string prompt)
        {
            return SafeReadLine(prompt, "ReadLine");
        }

        public override int ReadInteger(string prompt)
        {
            while (true) {
                int value;
                string txt = SafeReadLine(prompt, "ReadInteger");
                try {
                    value = int.Parse(txt);
                } catch (FormatException) {
                    continue;
                }
                return value;
            }
        }

        public override int? ReadOptionalInteger(string prompt)
        {
            while (true) {
                int value;
                string txt = SafeReadLine(prompt, "ReadOptionalInteger");
                if (string.IsNullOrEmpty(txt)) {
                    return null;
                } else {
                    try {
                        value = int.Parse(txt);
                    } catch (FormatException) {
                        continue;
                    }
                    return value;
                }
            }
        }

        public override int? ReadOptionalIntegerHexadecimal(string prompt)
        {
            while (true) {
                int value;
                string txt = SafeReadLine(prompt, "ReadOptionalIntegerHexadecimal");
                if (string.IsNullOrEmpty(txt)) {
                    return null;
                } else {
                    try {
                        value = int.Parse(txt, System.Globalization.NumberStyles.HexNumber);
                    } catch (FormatException) {
                        continue;
                    }
                    return value;
                }
            }
        }

        public override InTheHand.Net.BluetoothAddress ReadBluetoothAddress(string prompt)
        {
            return ReadBluetoothAddress(prompt, false);
        }

        public override InTheHand.Net.BluetoothAddress ReadOptionalBluetoothAddress(string prompt)
        {
            return ReadBluetoothAddress(prompt, true);
        }

        InTheHand.Net.BluetoothAddress ReadBluetoothAddress(string prompt, bool optional)
        {
            while (true) {
                InTheHand.Net.BluetoothAddress value;
                string txt = SafeReadBluetoothAddress(prompt, "ReadBluetoothAddress");
                if (string.IsNullOrEmpty(txt) && optional) {
                    return null;
                }
                if (InTheHand.Net.BluetoothAddress.TryParse(txt, out value)) {
                    AddKnownAddress(value);
                    return value;
                }
            }//while
        }

        public override string GetFilename()
        {
            return GetFilenameWinForms(this);
        }

        void ClearConsole_Click(object sender, EventArgs e)
        {
            Clear();
        }

        System.Threading.ManualResetEvent m_pause = new System.Threading.ManualResetEvent(false);

        public override void Pause(string prompt)
        {
            m_pause.Reset();
            ShowPause(true, prompt);
            bool x = m_pause.WaitOne();
        }

        private void Unpause_Click(object sender, EventArgs e)
        {
            ShowPause(false, null);
            m_pause.Set();
        }

        private void SetupPauseControls()
        {
            this.labelPause.SendToBack();
            ShowPause(false, null);
        }

        private void ShowPause(bool pausing, string prompt)
        {
            System.Threading.ThreadStart dlgt = delegate
            {
                if (pausing) {
                    WriteLine(prompt);
                    this.labelPause.Text = "Menu->Un-pause: " + prompt;
                    this.labelPause.Visible = true;
                    Debug.Assert(itemUnpause != null, "init'd in RunMenu so should be valid!");
                } else {
                    this.labelPause.Visible = false;
                }
                if (itemUnpause != null) {
                    itemUnpause.Enabled = pausing;
                }
            };
            if (this.tb.InvokeRequired) {
                this.tb.BeginInvoke(dlgt);
            } else {
                dlgt();
            }
        }

        void Pause__old()
        {
            //bool hc = this.tb.IsHandleCreated;
            bool ir = this.tb.InvokeRequired;
            if (ir) { //DEBUG
            }
            MessageBox.Show("Pause" + (ir ? " InvokeRequired!!" : " (is on UI thread)"), "Pause",
                MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
        }

        public override bool ReadYesNo(string prompt, bool defaultYes)
        {
            MsgBoxStyle style = MsgBoxStyle.YesNo;
            style |= (defaultYes ? MsgBoxStyle.DefaultButton1 : MsgBoxStyle.DefaultButton2);
            while (true) {
                MsgBoxResult val = SafeMsgBox(prompt, "ReadYesNo", style);
                Debug.Assert(val == MsgBoxResult.Yes || val == MsgBoxResult.No);
                return (val == MsgBoxResult.Yes); // true==Yes, false==No
            }
        }

        public override bool? ReadYesNoCancel(string prompt, bool? defaultYes)
        {
            MsgBoxStyle style = MsgBoxStyle.YesNoCancel;
            style |= (defaultYes == true ? MsgBoxStyle.DefaultButton1
                : defaultYes == false ? MsgBoxStyle.DefaultButton2
                    : MsgBoxStyle.DefaultButton3);
            var twoChoicesSupportedOnly = false;
#if NETCF
            twoChoicesSupportedOnly = SystemSettings.Platform == WinCEPlatform.Smartphone;

#endif
            if (twoChoicesSupportedOnly) {
                bool result;
                result = ReadYesNo("Choose Yes or No/Cancel -- " + prompt, defaultYes == null);
                if (result)
                    return true;
                result = ReadYesNo("Choose No or Cancel -- " + prompt, defaultYes == null);
                if (result)
                    return false;
                else
                    return null;
            }
            while (true) {
                MsgBoxResult val = SafeMsgBox(prompt, "ReadYesNoCancel", style);
                Debug.Assert(val == MsgBoxResult.Yes || val == MsgBoxResult.No
                     || val == MsgBoxResult.Cancel);
                // true==Yes, false==No
                if (val == MsgBoxResult.Yes)
                    return true;
                else if (val == MsgBoxResult.No)
                    return false;
                else return null;
            }
        }

        public override Guid? ReadOptionalBluetoothUuid(string prompt, Guid? promptDefault)
        {
            while (true) {
                Guid value;
                if (promptDefault != null) {
                    prompt += " (default: " + promptDefault.ToString() + ")";
                }
                string txt = SafeReadLine(prompt, "ReadOptionalIntegerHexadecimal");
                if (string.IsNullOrEmpty(txt)) {
                    return null;
                } else {
                    if (base.BluetoothService_TryParseIncludingShortForm(txt, out value))
                        return value;
                    // Continue to give user another chance to input a good value.
                }
            }
        }

        private void Log(string msg)
        {
            SafeAppendText(msg + "\r\n");
        }

        //--
        public override void UiInvoke(EventHandler dlgt)
        {
            SafeInvoke(tb, dlgt);
        }

        public override bool? InvokeRequired
        {
            get { return tb.InvokeRequired; }
        }

        public override object InvokeeControl
        {
            get { return tb; }
        }

        //----
#if !NETCF
        AutoCompleteStringCollection _knownAddresses;

        private string _knownAddressesPath
        {
            get
            {
                var dir = Path.GetDirectoryName(EntryAssemblyPath);
                return Path.Combine(dir, "knownAddresses.txt");
            }
        }

        private string EntryAssemblyPath
        {
            get
            {
                var cb = System.Reflection.Assembly.GetEntryAssembly().CodeBase;
                var u = new Uri(cb);
                var dir = u.LocalPath;
                return dir;
            }
        }

        void LoadKnownAddresses()
        {
            _knownAddresses = new AutoCompleteStringCollection();
            _formReadAddress.SetKnownAddressList(_knownAddresses);
            string[] lines;
            try {
                lines = File.ReadAllLines(_knownAddressesPath);
            } catch (FileNotFoundException) {
                return;
            }
            _knownAddresses.AddRange(lines);
        }

        void SaveKnownAddresses()
        {
            string[] arr = new string[_knownAddresses.Count];
            _knownAddresses.CopyTo(arr, 0);
            System.IO.File.WriteAllLines(_knownAddressesPath, arr);
        }

        void AddKnownAddress(InTheHand.Net.BluetoothAddress value)
        {
            var text = value.ToString("C");
            if (!_knownAddresses.Contains(text)) {
                _knownAddresses.Add(text);
            }
        }
#else
        void LoadKnownAddresses() { }
        void SaveKnownAddresses() { }
        void AddKnownAddress(InTheHand.Net.BluetoothAddress value) { }
#endif
    }
}


text:
/**
 * Status of a friendship
 */
module.exports = {
  // This friend has received a friend request, but not yet accepted.
  Pending: 'pending',

  // This friendship is active. Both parties will have this status once
  // the receiving friend has accepted.
  Accepted: 'accepted',

  // This is a friend request made by the player that has not yet been
  // accepted.
  Requested: 'requested'
}


text:
package org.camunda.bpm.engine.test.standalone.pvm;

import org.camunda.bpm.engine.impl.pvm.ProcessDefinitionBuilder;
import org.camunda.bpm.engine.impl.pvm.PvmProcessDefinition;
import org.camunda.bpm.engine.impl.pvm.PvmProcessInstance;
import org.camunda.bpm.engine.impl.test.PvmTestCase;
import org.camunda.bpm.engine.test.standalone.pvm.activities.Automatic;
import org.camunda.bpm.engine.test.standalone.pvm.activities.End;
import org.camunda.bpm.engine.test.standalone.pvm.activities.ReusableSubProcess;

/**
 * @author Tom Baeyens
 */
public class PvmReusableSubProcessTest extends PvmTestCase {

  public void testReusableSubProcess() {
    PvmProcessDefinition subProcessDefinition = new ProcessDefinitionBuilder()
      .createActivity("start")
        .initial()
        .behavior(new Automatic())
        .transition("subEnd")
      .endActivity()
      .createActivity("subEnd")
        .behavior(new End())
      .endActivity()
    .buildProcessDefinition();

    PvmProcessDefinition superProcessDefinition = new ProcessDefinitionBuilder()
      .createActivity("start")
        .initial()
        .behavior(new Automatic())
        .transition("subprocess")
      .endActivity()
      .createActivity("subprocess")
        .behavior(new ReusableSubProcess(subProcessDefinition))
        .transition("superEnd")
      .endActivity()
      .createActivity("superEnd")
        .behavior(new End())
      .endActivity()
    .buildProcessDefinition();

    PvmProcessInstance processInstance = superProcessDefinition.createProcessInstance();
    processInstance.start();

    assertTrue(processInstance.isEnded());
  }
}


text:
"""
Main module for web service interface.

Author:
Tomas Bambas  xbamba01@stud.fit.vutbr.cz
"""

import http.server
import re
import socket
import urllib.parse
import hashlib
import os.path
import random
import sys

import datamodel
import logger
import util
import common
from .evaluator import evaluate

# global list with tuples (tasks, number)
# tasks is list with datamodel.Task objects
# number is number of tasks per student from this list
_tasks = []
# global list with tuple (student, tasks, status, sid)
# student is datamodel.Student object
# tasks is list with datamodel.Task objects
# status: 0 means student has not got his tasks
#         1 means student got his tasks
#         2 means student sent answers
# sid is session id for this student
_students = []
# XHTML templates
_templates = ()
# global error status
_status = 0

def load_templates():
    """
    Load XHTML templates for http responses.
    """
    module_path = os.path.dirname(__file__)
    template_index_path = os.path.join(module_path,
                                      "templates",
                                      "index.xhtml")
    template_test_path = os.path.join(module_path,
                                      "templates",
                                      "test.xhtml")
    template_test_results_path = os.path.join(module_path,
                                              "templates",
                                              "test_results.xhtml")
    template_403_path = os.path.join(module_path,
                                     "templates",
                                     "403.xhtml")
    template_404_path = os.path.join(module_path,
                                     "templates",
                                     "404.xhtml")
    with open(template_index_path, encoding="u8") as f:
        template_index = f.read()
    with open(template_test_path, encoding="u8") as f:
        template_test = f.read()
    with open(template_test_results_path, encoding="u8") as f:
        template_test_results = f.read()
    with open(template_403_path, encoding="u8") as f:
        template_403 = f.read()
    with open(template_404_path, encoding="u8") as f:
        template_404 = f.read()
    return(template_index, template_test, template_test_results, template_403,
           template_404)

def serve(students, tasks):
    """
    Assign tasks to students (if anonymous mode is off) and start web server.
    """
    # init global variables
    global _tasks
    global _students
    global _templates
    global _status
    _tasks = tasks
    _templates = load_templates()
    # assign tasks to students
    if not common.get_config().is_anonymous():
        for student in students:
            logger.print_msg("assigning tasks for student: " + \
                             student.get_login())
            tasks_for_student = util.random_assign(tasks)
            # generate random session id
            m = hashlib.md5()
            m.update((student.get_name() + \
                      student.get_login() + \
                      str(random.randrange(0xFFFFFFFFFFFFFFFF))).encode("u8"))
            sid = m.hexdigest()
            _students += [(student, tasks_for_student, 0, sid)]
    # start web service
    try:
        serve_forever()
    except KeyboardInterrupt:
        _status = 0
    return _status

def serve_forever():
    """
    Start web server on user specified port
    """
    server_address = ('', common.get_config().get_webserver_port())
    httpd = http.server.HTTPServer(server_address, HTTPRequestHandler)
    logger.print_msg("starting web service on port " + str(server_address[1]))
    print_students_info()
    httpd.serve_forever()

def print_students_info():
    statuses = [0, 0, 0]
    for (*rest, status, sid) in _students:
        statuses[status] += 1
    logger.print_msg(str(statuses[2]) + " students answered, " + \
                     str(statuses[1]) + " students answering, " + \
                     str(statuses[0]) + " students not logged in")

class HTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    def handle(self):
        try:
            super(HTTPRequestHandler, self).handle()
        except socket.error as e:
            logger.print_warning("socket error while comunicating with " +
                                 self.client_address[0] + " " + str(e))

    def do_GET(self):
        # somebody is trying to get index page, send him login form
        if self.path == "/":
            response = self.prepare_index_response()
            self.send_200(response)
        # unknown request
        else:
            self.send_404()

    def do_POST(self):
        # somebody is trying to get test, check password and send him test
        if self.path == "/test":
            cl_header = self.headers.get("Content-Length")
            if cl_header != None:
                try:
                    data = self.rfile.read(int(cl_header)).decode("ascii")
                    data = urllib.parse.parse_qs(data)
                    # check login and password
                    if self.check_login(data) and self.check_password(data):
                        # prepare and send test form
                        response = self.prepare_test_response(data)
                        self.send_200(response)
                        print_students_info()
                    else:
                        self.send_403()
                # incorrect form data
                except UnicodeDecodeError:
                    self.send_403()
            else:
                self.send_403()
        # somebody is trying to send test answers and get results
        elif self.path == "/testresults":
            cl_header = self.headers.get("Content-Length")
            if cl_header != None:
                try:
                    data = self.rfile.read(int(cl_header)).decode("ascii")
                    data = urllib.parse.parse_qs(data)
                    points_list = self.evaluate_answers(data)
                    if points_list != None:
                        response = self.prepare_results_response(data,
                                                                 points_list)
                        self.send_200(response)
                        print_students_info()
                    else:
                        self.send_403()
                # incorrect form data
                except UnicodeDecodeError:
                    self.send_403()
            else:
                self.send_403()
        # unknown request
        else:
            self.send_404()

    def send_200(self, data):
        self.send_response(200)
        self.send_header("Content-Length", str(len(data)))
        self.send_header("Content-Type", "text/html")
        self.end_headers()
        self.wfile.write(data)

    def send_403(self):
        response = self.prepare_403_response()
        self.send_response(403)
        self.send_header("Content-Length", str(len(response)))
        self.send_header("Content-Type", "text/html")
        self.end_headers()
        self.wfile.write(response)

    def send_404(self):
        response = self.prepare_404_response()
        self.send_response(404)
        self.send_header("Content-Length", str(len(response)))
        self.send_header("Content-Type", "text/html")
        self.end_headers()
        self.wfile.write(response)

    def log_message(self, format_, *msg):
        logger.print_msg("request " +
                         str(self.client_address[0]) +
                         " " +
                         str(msg[0]))

    def prepare_index_response(self):
        resp = re.sub(r"#replacepass#([^#]+)#replacepass#",
                      r'\1<input type="password" name="password" />',
                      _templates[0])
        if common.get_config().is_anonymous():
            resp = re.sub("#replacelogin#([^#]+)#replacelogin#",
                          '',
                          resp)
        else:
           resp = re.sub(r"#replacelogin#([^#]+)#replacelogin#",
                         r'\1<input type="text" name="login" />',
                         resp)
        return resp.encode("u8")

    def prepare_test_response(self, formdata):
        global _students
        # get tasks and student's session id
        if common.get_config().is_anonymous():
            # create new anonymous student
            student = datamodel.Student()
            login = "anonymous_" + '{:0>4}'.format(str(len(_students)))
            student.set_login(login)
            logger.print_msg("assigning tasks for student: " + login)
            tasks = util.random_assign(_tasks)
            # generate random session id
            m = hashlib.md5()
            m.update((login + \
                      str(random.randrange(0xFFFFFFFFFFFFFFFF))).encode("u8"))
            sid = m.hexdigest()
            _students += [(student, tasks, 1, sid)]
        else:
            login = formdata["login"][0]
            i = 0
            for (student_, tasks_, status, sid_) in _students:
                if student_.get_login() == login:
                    student = student_
                    tasks = tasks_
                    sid = sid_
                    break
                i += 1
            # set correct status (1 = test already requested)
            _students[i] = (student, tasks, 1, sid)
        # create xhtml form
        inputsdata = ""
        if not common.get_config().is_anonymous():
            inputsdata += "" + student.get_login() + ", " + \
                          student.get_name() + "

"
        i = 0
        for task in tasks:
            inputsdata += self.create_inputs(task, i)
            i += 1
        inputsdata += '<input type="hidden" value="' + sid + '" name="' + \
                      'sid"/>'
        # return created form
        resp = _templates[1].replace(r"#replaceinputs#", inputsdata)
        return resp.encode("u8")

    def create_inputs(self, task, num):
        """
        Create from task HTML form inputs.
        """
        inputsdata = ""
        # question
        question = task.get_question().replace("\n", "
")
        question = question.replace("\t", "    ")
        inputsdata += '' + question + "
" \
                      "[" + str(task.get_max_points()) + " points]" + \
                      "
"
        # radio buttons
        if task.get_type() == "choice":
            i = 0
            for (answer, iscorrect) in task.get_answers():
                inputsdata += "<input type=\"radio\" name=\"" + "a_" + \
                              str(num) + '"' + " value=\"" + str(i) + \
                              '" /> ' + answer + "
"
                i += 1
        # checkboxes
        elif task.get_type() == "multichoice":
            i = 0
            for (answer, iscorrect) in task.get_answers():
                inputsdata += "<input type=\"checkbox\" name=\"" + "a_" + \
                              str(num) + '"' + " value=\"" + str(i) + \
                              '" /> ' + answer + "
"
                i += 1
        # text areas
        else:
            if task.get_prefill() != None:
                prefill = task.get_prefill()
            else:
                prefill = ""
            inputsdata += "<textarea name=\"" + "a_" + str(num) + \
                          "\" cols=80 rows=15 wrap=physical>" + prefill + \
                          "</textarea>
"
        inputsdata += "

"
        return inputsdata

    def prepare_results_response(self, data, points_list):
        # select correct student
        sid = data["sid"][0]
        for (student_, tasks_, status_, sid_) in _students:
            if sid == sid_:
                student = student_
                tasks = tasks_
                break
        resultsdata = "#sumpoints#   "
        if not common.get_config().is_anonymous():
            resultsdata += student.get_login() + ", " + student.get_name()
        else:
            resultsdata += "anonym"
        resultsdata += "

"
        # insert questions and points
        i = 0
        sumpoints = sum(points_list)
        summaxpoints = 0
        for task in tasks:
            question = task.get_question().replace("\n", "
")
            resultsdata += '' + question + \
                           "
"
            maxpoints = task.get_max_points()
            points = points_list[i]
            summaxpoints += maxpoints
            if points <= 0:
                color = "red"
            elif points == maxpoints:
                color = "green"
            else:
                color = "orange"
            resultsdata += '' + "[" + \
                           str(round(points, 2)) + "/" + str(maxpoints) + \
                           "]" + ""
            # add self learning helps
            if common.get_config().is_self_learning():
                # add help string
                if ((task.get_type() == "program" or
                     task.get_type() == "fulltext") and
                     task.get_help() != None and
                     points < maxpoints):
                    resultsdata += "
"
                    resultsdata += task.get_help()
                    resultsdata += "
"
                # add correct and bad answers
                elif (task.get_type() == "choice" or
                      task.get_type() == "multichoice"):
                    resultsdata += "
"
                    resultsdata += self.create_colored_answers(task)
            resultsdata += "

"
            i += 1
        # insert total number of points
        if sumpoints == 0:
            color = "red"
        elif sumpoints == summaxpoints:
            color = "green"
        else:
            color = "orange"
        totalpoints = '' + "[" + \
                      str(round(sumpoints, 2)) + "/" + str(summaxpoints) + \
                      "]" + ""
        resultsdata = resultsdata.replace("#sumpoints#", totalpoints)
        # return created form
        resp = _templates[2].replace(r"#replaceresults#", resultsdata)
        return resp.encode("u8")

    def create_colored_answers(self, task):
        answers = ""
        i = 0
        for answer, is_true in task.get_answers():
            if is_true:
                color = "green"
            else:
                color = "red"
            answers += '' + answer + \
                       ""
            if i in task.get_student_answers():
                answers += " <<<"
            answers += "
"
            i += 1
        return answers

    def prepare_403_response(self):
        return _templates[3].encode("u8")

    def prepare_404_response(self):
        return _templates[4].encode("u8")

    def check_password(self, formdata):
        """Return True is there is a correct password in form data"""
        config = common.get_config()
        try:
            if formdata["password"][0] == config.get_webserver_pass():
                return True
            else:
                return False
        except (KeyError, IndexError):
            return False

    def check_login(self, formdata):
        """
        Return True is there is a student with given login and status 0 or 1
        In anonymous mode this is always true.
        """
        if common.get_config().is_anonymous():
            return True
        try:
            login = formdata["login"][0]
            for (student, tasks, status, sid) in _students:
                if student.get_login() == login:
                    if status < 2:
                        return True
                    else:
                        return False
            return False
        except (KeyError, IndexError):
            return False

    def evaluate_answers(self, formdata):
        """
        Evaluate student's answers and return list with points. Also set a new
        stusent's status (2).
        If something get wrong, return None.
        """
        # find a student by session id
        try:
            req_sid = formdata["sid"][0]
        except KeyError:
            return None
        i = 0
        student = None
        for (student_, tasks_, status_, sid_) in _students:
            if sid_ == req_sid and status_ == 1:
                student = student_
                tasks = tasks_
                break
            i += 1
        # student not found
        if student == None:
            return None
        # set a new user's status (student answered)
        _students[i] = (student, tasks, 2, req_sid)
        # evaluate points
        return evaluate(student, tasks, formdata)

    def all_students_answered(self):
        """
        Return True if all students answered.
        """
        for (*rest, status, sid) in _students:
            if status == 0 or status == 1:
                return False
        return True


text:
#import <Foundation/connection/NSProtocolChecker.h>

@implementation NSProtocolChecker

+protocolCheckerWithTarget:(NSObject *)target protocol:(Protocol *)protocol {
   return [[[self alloc] initWithTarget:target protocol:protocol] autorelease];
}

-initWithTarget:(NSObject *)target protocol:(Protocol *)protocol {
   _target=[target retain];
   _protocol=[protocol retain];
   return self;
}

-(void)dealloc {
   [_target release];
   [_protocol release];
   [super dealloc];
}

-(NSObject *)target {
   return _target;
}

-(Protocol *)protocol {
   return _protocol;
}

@end


text:
var User         = require('../proxy').User;
var Topic        = require('../proxy').Topic;
var Reply        = require('../proxy').Reply;
var TopicCollect = require('../proxy').TopicCollect;
var utility      = require('utility');
var util         = require('util');
var TopicModel   = require('../models').Topic;
var ReplyModel   = require('../models').Reply;
var tools        = require('../common/tools');
var config       = require('../config');
var EventProxy   = require('eventproxy');
var validator    = require('validator');
var _            = require('lodash');

exports.index = function (req, res, next) {
  var user_name = req.params.name;
  User.getUserByLoginName(user_name, function (err, user) {
    if (err) {
      return next(err);
    }
    if (!user) {
      res.render404('这个用户不存在。');
      return;
    }

    var render = function (recent_topics, recent_replies) {
      user.url = (function () {
        if (user.url && user.url.indexOf('http') !== 0) {
          return 'http://' + user.url;
        }
        return user.url;
      })();
      // 如果用户没有激活,那么管理员可以帮忙激活
      var token = '';
      if (!user.active && req.session.user && req.session.user.is_admin) {
        token = utility.md5(user.email + user.pass + config.session_secret);
      }
      res.render('user/index', {
        user: user,
        recent_topics: recent_topics,
        recent_replies: recent_replies,
        token: token,
        pageTitle: util.format('@%s 的个人主页', user.loginname),
      });
    };

    var proxy = new EventProxy();
    proxy.assign('recent_topics', 'recent_replies', render);
    proxy.fail(next);

    var query = {author_id: user._id};
    var opt = {limit: 5, sort: '-create_at'};
    Topic.getTopicsByQuery(query, opt, proxy.done('recent_topics'));

    Reply.getRepliesByAuthorId(user._id, {limit: 20, sort: '-create_at'},
      proxy.done(function (replies) {

        var topic_ids = replies.map(function (reply) {
          return reply.topic_id.toString()
        })
        topic_ids = _.uniq(topic_ids).slice(0, 5); //  只显示最近5条

        var query = {_id: {'$in': topic_ids}};
        var opt = {};
        Topic.getTopicsByQuery(query, opt, proxy.done('recent_replies', function (recent_replies) {
          recent_replies = _.sortBy(recent_replies, function (topic) {
            return topic_ids.indexOf(topic._id.toString())
          })
          return recent_replies;
        }));
      }));
  });
};

exports.listStars = function (req, res, next) {
  User.getUsersByQuery({is_star: true}, {}, function (err, stars) {
    if (err) {
      return next(err);
    }
    res.render('user/stars', {stars: stars});
  });
};

exports.showSetting = function (req, res, next) {
  User.getUserById(req.session.user._id, function (err, user) {
    if (err) {
      return next(err);
    }
    if (req.query.save === 'success') {
      user.success = '保存成功。';
    }
    user.error = null;
    return res.render('user/setting', user);
  });
};

exports.setting = function (req, res, next) {
  var ep = new EventProxy();
  ep.fail(next);

  // 显示出错或成功信息
  function showMessage(msg, data, isSuccess) {
    data = data || req.body;
    var data2 = {
      loginname: data.loginname,
      email: data.email,
      url: data.url,
      location: data.location,
      signature: data.signature,
      weibo: data.weibo,
      accessToken: data.accessToken,
    };
    if (isSuccess) {
      data2.success = msg;
    } else {
      data2.error = msg;
    }
    res.render('user/setting', data2);
  }

  // post
  var action = req.body.action;
  if (action === 'change_setting') {
    var url = validator.trim(req.body.url);
    var location = validator.trim(req.body.location);
    var weibo = validator.trim(req.body.weibo);
    var signature = validator.trim(req.body.signature);

    User.getUserById(req.session.user._id, ep.done(function (user) {
      user.url = url;
      user.location = location;
      user.signature = signature;
      user.weibo = weibo;
      user.save(function (err) {
        if (err) {
          return next(err);
        }
        req.session.user = user.toObject({virtual: true});
        return res.redirect('/setting?save=success');
      });
    }));
  }
  if (action === 'change_password') {
    var old_pass = validator.trim(req.body.old_pass);
    var new_pass = validator.trim(req.body.new_pass);
    if (!old_pass || !new_pass) {
      return res.send('旧密码或新密码不得为空');
    }

    User.getUserById(req.session.user._id, ep.done(function (user) {
      tools.bcompare(old_pass, user.pass, ep.done(function (bool) {
        if (!bool) {
          return showMessage('当前密码不正确。', user);
        }

        tools.bhash(new_pass, ep.done(function (passhash) {
          user.pass = passhash;
          user.save(function (err) {
            if (err) {
              return next(err);
            }
            return showMessage('密码已被修改。', user, true);

          });
        }));
      }));
    }));
  }
};

exports.toggleStar = function (req, res, next) {
  var user_id = req.body.user_id;
  User.getUserById(user_id, function (err, user) {
    if (err) {
      return next(err);
    }
    if (!user) {
      return next(new Error('user is not exists'));
    }
    user.is_star = !user.is_star;
    user.save(function (err) {
      if (err) {
        return next(err);
      }
      res.json({ status: 'success' });
    });
  });
};

exports.listCollectedTopics = function (req, res, next) {
  var name = req.params.name;
  var page = Number(req.query.page) || 1;
  var limit = config.list_topic_count;

  User.getUserByLoginName(name, function (err, user) {
    if (err || !user) {
      return next(err);
    }

    var render = function (topics, pages) {
      res.render('user/collect_topics', {
        topics: topics,
        current_page: page,
        pages: pages,
        user: user
      });
    };

    var proxy = EventProxy.create('topics', 'pages', render);
    proxy.fail(next);

    var opt = {
      skip: (page - 1) * limit,
      limit: limit,
    };

    TopicCollect.getTopicCollectsByUserId(user._id, opt, proxy.done(function (docs) {
      var ids = docs.map(function (doc) {
        return String(doc.topic_id)
      })
      var query = { _id: { '$in': ids } };

      Topic.getTopicsByQuery(query, {}, proxy.done('topics', function (topics) {
        topics = _.sortBy(topics, function (topic) {
          return ids.indexOf(String(topic._id))
        })
        return topics
      }));
      Topic.getCountByQuery(query, proxy.done(function (all_topics_count) {
        var pages = Math.ceil(all_topics_count / limit);
        proxy.emit('pages', pages);
      }));
    }));
  });
};

exports.top100 = function (req, res, next) {
  var opt = {limit: 100, sort: '-score'};
  User.getUsersByQuery({is_block: false}, opt, function (err, tops) {
    if (err) {
      return next(err);
    }
    res.render('user/top100', {
      users: tops,
      pageTitle: 'top100',
    });
  });
};

exports.listTopics = function (req, res, next) {
  var user_name = req.params.name;
  var page = Number(req.query.page) || 1;
  var limit = config.list_topic_count;

  User.getUserByLoginName(user_name, function (err, user) {
    if (!user) {
      res.render404('这个用户不存在。');
      return;
    }

    var render = function (topics, pages) {
      res.render('user/topics', {
        user: user,
        topics: topics,
        current_page: page,
        pages: pages
      });
    };

    var proxy = new EventProxy();
    proxy.assign('topics', 'pages', render);
    proxy.fail(next);

    var query = {'author_id': user._id};
    var opt = {skip: (page - 1) * limit, limit: limit, sort: '-create_at'};
    Topic.getTopicsByQuery(query, opt, proxy.done('topics'));

    Topic.getCountByQuery(query, proxy.done(function (all_topics_count) {
      var pages = Math.ceil(all_topics_count / limit);
      proxy.emit('pages', pages);
    }));
  });
};

exports.listReplies = function (req, res, next) {
  var user_name = req.params.name;
  var page = Number(req.query.page) || 1;
  var limit = 50;

  User.getUserByLoginName(user_name, function (err, user) {
    if (!user) {
      res.render404('这个用户不存在。');
      return;
    }

    var render = function (topics, pages) {
      res.render('user/replies', {
        user: user,
        topics: topics,
        current_page: page,
        pages: pages
      });
    };

    var proxy = new EventProxy();
    proxy.assign('topics', 'pages', render);
    proxy.fail(next);

    var opt = {skip: (page - 1) * limit, limit: limit, sort: '-create_at'};
    Reply.getRepliesByAuthorId(user._id, opt, proxy.done(function (replies) {
      // 获取所有有评论的主题
      var topic_ids = replies.map(function (reply) {
        return reply.topic_id.toString();
      });
      topic_ids = _.uniq(topic_ids);

      var query = {'_id': {'$in': topic_ids}};
      Topic.getTopicsByQuery(query, {}, proxy.done('topics', function (topics) {
        topics = _.sortBy(topics, function (topic) {
          return topic_ids.indexOf(topic._id.toString())
        })
        return topics;
      }));
    }));

    Reply.getCountByAuthorId(user._id, proxy.done('pages', function (count) {
      var pages = Math.ceil(count / limit);
      return pages;
    }));
  });
};

exports.block = function (req, res, next) {
  var loginname = req.params.name;
  var action = req.body.action;

  var ep = EventProxy.create();
  ep.fail(next);

  User.getUserByLoginName(loginname, ep.done(function (user) {
    if (!user) {
      return next(new Error('user is not exists'));
    }
    if (action === 'set_block') {
      ep.all('block_user',
        function (user) {
          res.json({status: 'success'});
        });
      user.is_block = true;
      user.save(ep.done('block_user'));

    } else if (action === 'cancel_block') {
      user.is_block = false;
      user.save(ep.done(function () {

        res.json({status: 'success'});
      }));
    }
  }));
};

exports.deleteAll = function (req, res, next) {
  var loginname = req.params.name;

  var ep = EventProxy.create();
  ep.fail(next);

  User.getUserByLoginName(loginname, ep.done(function (user) {
    if (!user) {
      return next(new Error('user is not exists'));
    }
    ep.all('del_topics', 'del_replys', 'del_ups',
      function () {
        res.json({status: 'success'});
      });
    // 删除主题
    TopicModel.update({author_id: user._id}, {$set: {deleted: true}}, {multi: true}, ep.done('del_topics'));
    // 删除评论
    ReplyModel.update({author_id: user._id}, {$set: {deleted: true}}, {multi: true}, ep.done('del_replys'));
    // 点赞数也全部干掉
    ReplyModel.update({}, {$pull: {'ups': user._id}}, {multi: true}, ep.done('del_ups'));
  }));
};


text:
package worker

import (
	gocontext "context"
	"time"
)

type LogWriterFactory interface {
	LogWriter(gocontext.Context, time.Duration, Job) (LogWriter, error)
	Cleanup() error
}


text:
<?php

namespace osCommerce\OM\Core\Site\Website\Application\_\Action;

use osCommerce\OM\Core\{
    ApplicationAbstract,
    HTML,
    OSCOM,
    Registry
};

use osCommerce\OM\Core\Site\Shop\Address;

use osCommerce\OM\Core\Site\Website\{
    Braintree,
    Users
};

class Ambassadors
{
    const COUNTRIES_WITH_ZONES = ['AU', 'CA', 'DE', 'US'];

    public static function execute(ApplicationAbstract $application)
    {
        $OSCOM_Currency = Registry::get('Currency');
        $OSCOM_Language = Registry::get('Language');
        $OSCOM_Session = Registry::get('Session');
        $OSCOM_Template = Registry::get('Template');

        if (!$OSCOM_Session->hasStarted()) {
            $OSCOM_Session->start();
        }

        $req_sig = OSCOM::getSiteApplication() . '&' . $application->getCurrentAction();

        if (!isset($_SESSION[OSCOM::getSite()]['keepAlive']) || !in_array($req_sig, $_SESSION[OSCOM::getSite()]['keepAlive'])) {
            $_SESSION[OSCOM::getSite()]['keepAlive'][] = $req_sig;
        }

        $OSCOM_Language->loadIniFile('pages/ambassadors.php');
        $OSCOM_Language->loadIniFile('pages/legal_tos_ambassador.php');

        $OSCOM_Template->setValue('public_token', $_SESSION[OSCOM::getSite()]['public_token']);
        $OSCOM_Template->setValue('recaptcha_key_public', OSCOM::getConfig('recaptcha_key_public'));

        $application->setPageContent('ambassadors.html');
        $application->setPageTitle(OSCOM::getDef('amb_html_page_title'));

        if (file_exists(OSCOM::getConfig('dir_fs_public', 'OSCOM') . 'sites/' . OSCOM::getSite() . '/images/highlights/ambassadors.jpg')) {
            $OSCOM_Template->setValue('highlights_image', 'images/highlights/ambassadors.jpg');
        }

        $OSCOM_Template->setValue('language_code', $OSCOM_Language->getCode());
        $OSCOM_Template->setValue('amb_price', $OSCOM_Currency->trim($OSCOM_Currency->show(Users::AMBASSADOR_LEVEL_PRICE)));
        $OSCOM_Template->setValue('amb_prices', $OSCOM_Currency->showAll(Users::AMBASSADOR_LEVEL_PRICE, true));
        $OSCOM_Template->setValue('is_ambassador', (isset($_SESSION[OSCOM::getSite()]['Account']) && ($_SESSION[OSCOM::getSite()]['Account']['amb_level'] > 0)));
        $OSCOM_Template->setValue('ambassador_user_next_level', isset($_SESSION[OSCOM::getSite()]['Account']) ? $_SESSION[OSCOM::getSite()]['Account']['amb_level'] + 1 : 1);
        $OSCOM_Template->setValue('braintree_google_merchant_id', OSCOM::getConfig('braintree_google_merchant_id'));

        $OSCOM_Template->addHtmlElement('footer', '<script src="' . OSCOM::getPublicSiteLink('javascript/Application/_/Ambassadors.min.js') . '"></script>');

        $OSCOM_Template->addHtmlElement('footer', '<script src="' . OSCOM::getPublicSiteLink('external/js.cookie.min.js') . '"></script>');
        $OSCOM_Template->addHtmlElement('footer', '<script>Cookies.defaults = {path: OSCOM.cookie["path"], domain: OSCOM.cookie["domain"], secure: true};</script>');

        $amb_members = [];

        foreach (Users::getNewestAmbassadors(12) as $a) {
            $m = Users::get($a);

            $amb_members[] = [
                'name' => $m['name'],
                'profile_url' => $m['profile_url'],
                'photo_url' => $m['photo_url']
            ];
        }

        $OSCOM_Template->setValue('amb_members', $amb_members);

        $countries = [
            [
                'id' => '',
                'text' => OSCOM::getDef('select_please_select')
            ]
        ];

        foreach (Address::getCountries() as $c) {
            $countries[$c['id']] = [
                'id' => $c['iso_2'],
                'text' => $c['name']
            ];
        }

        $countries_field = HTML::selectMenu('country', $countries, null, 'id="cCountry" class="custom-select" required');

        $OSCOM_Template->setValue('field_countries', $countries_field);

        $zones = [];

        foreach (Address::getZones(static::COUNTRIES_WITH_ZONES) as $z) {
            $zones[$countries[$z['country_id']]['id']][] = [
                'code' => $z['code'],
                'title' => $z['name']
            ];
        }

        $OSCOM_Template->setValue('select_zones', $zones);

        if (isset($_SESSION[OSCOM::getSite()]['Account']) && Users::hasAddress($_SESSION[OSCOM::getSite()]['Account']['id'], 'billing')) {
            $address = Users::getAddress($_SESSION[OSCOM::getSite()]['Account']['id'], 'billing');
            $address = reset($address);

            $OSCOM_Template->setValue('billing_address', $address);
        }
    }
}


text:
<?php

namespace Tree6bee\Support\Ctx\Db\Query;

use Tree6bee\Support\Ctx\Db\Connection;
use Tree6bee\Support\Ctx\Db\Query\Grammars\Grammar;

class Builder
{
    /**
     * @var Connection
     */
    protected $conn;

    /**
     * @var Grammar
     */
    protected $grammar;

    /**
     * @var string
     */
    public $table;

    public function __construct(Connection $conn, Grammar $grammar)
    {
        $this->conn = $conn;
        $this->grammar = $grammar;
    }

    /**
     * @param $table
     * @return $this
     */
    public function table($table)
    {
        $this->table = $table;

        return $this;
    }

//    public function get()
//    {
//        return $this->conn->select($this->toSql(), $this->getBindings());
//    }

    public function insert(array $values)
    {
        if (! is_array(reset($values))) {
            $values = [$values];
        }

        list($query, $bindings) = $this->grammar->compileInsert($this, $values);

        return $this->conn->insert($query, $bindings);
    }

    public function insertGetId(array $values, $primaryKey = 'id')
    {
        list($query, $bindings) = $this->grammar->compileInsertGetId($this, $values);

        return $this->conn->insertGetId($query, $bindings, $primaryKey);
    }
}


text:
namespace blink {

// BytesConsumer to get data from a SharedBuffer.
class PLATFORM_EXPORT SharedBufferBytesConsumer final : public BytesConsumer {
 public:
  // |data| should not be modified after it passed to SharedBufferBytesConsumer.
  explicit SharedBufferBytesConsumer(scoped_refptr<const SharedBuffer> data);
  SharedBufferBytesConsumer(const SharedBufferBytesConsumer&) = delete;
  SharedBufferBytesConsumer& operator=(const SharedBufferBytesConsumer&) =
      delete;

  // Implements BytesConsumer.
  Result BeginRead(const char** buffer, size_t* available) override;
  Result EndRead(size_t read_size) override;
  void SetClient(Client* client) override {}
  void ClearClient() override {}
  void Cancel() override;
  PublicState GetPublicState() const override;
  Error GetError() const override {
    NOTREACHED();
    return Error();
  }
  String DebugName() const override;

 private:
  scoped_refptr<const SharedBuffer> data_;
  SharedBuffer::Iterator iterator_;
  size_t bytes_read_in_chunk_ = 0;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_SHARED_BUFFER_BYTES_CONSUMER_H_


text:
@ECHO OFF
REM *************************************************************************
REM * $Id: build-winpc.cmd,v 1.2 2008/01/09 15:08:41 cnepveu Exp $
REM *
REM * Batch file used to build the Gateway6 Client.
REM *
REM * Prerequisites:
REM *  - Visual Studio 2005 (SP1)
REM *  - Windows Vista RTM SDK  (Integrated in VS2005SP1)
REM *  - DEVENV executable in %PATH%
REM *
REM * Usage:
REM *   build-winpc [/Release /HAP6-Release /Debug /HAP6-Debug] [/Win32 /x64]
REM *
REM *************************************************************************

REM Defaults:
SET CONFIGURATION=Release
SET PLATFORM=Win32
SET COMMAND=Build

REM Overrides:
:ParseArgs
IF /I "%~1" == "/?"             GOTO Usage
IF /I "%~1" == "-h"             GOTO Usage
IF /I "%~1" == "/Release"       SET CONFIGURATION=Release& SHIFT& GOTO ParseArgs
IF /I "%~1" == "/HAP6-Release"  SET CONFIGURATION=HAP6-Release& SHIFT& GOTO ParseArgs
IF /I "%~1" == "/Debug"         SET CONFIGURATION=Debug& SHIFT& GOTO ParseArgs
IF /I "%~1" == "/HAP6-Debug"    SET CONFIGURATION=HAP6-Debug& SHIFT& GOTO ParseArgs
IF /I "%~1" == "/Win32"         SET PLATFORM=Win32& SHIFT& GOTO ParseArgs
IF /I "%~1" == "/x64"           SET PLATFORM=x64& SHIFT& GOTO ParseArgs
IF /I "%~1" == "/Clean"         SET COMMAND=Clean& SHIFT& GOTO ParseArgs
IF    "%~1" EQU ""              GOTO Done_Args
ECHO Unknown command-line switch: %~1
GOTO Usage
:Done_Args

REM Build the target
ECHO Launching build of gw6c solution...
ECHO Configuration: COMMAND=%COMMAND% PLATFORM=%PLATFORM% CONFIGURATION=%CONFIGURATION%
ECHO.
DEVENV platform\winpc\gw6c.sln /%COMMAND% "%CONFIGURATION%|%PLATFORM%"
IF %ERRORLEVEL% == 0 GOTO build_ok
GOTO build_error

:Usage
ECHO.
ECHO Usage:
ECHO   %0 ^[^/Release^|^/HAP6-Release^|^/Debug^|^/HAP6-Debug^] ^[^/Win32^|^/x64^] ^[^/Clean^]
ECHO.
ECHO   Defaults: ^/Release ^/Win32
ECHO.
GOTO the_end

:build_ok
ECHO.
ECHO Build of gw6c solution completed successfully.
GOTO the_end

:build_error
ECHO.
ECHO Build of gw6c solution FAILED!

:the_end


text:
/* Lzma86Dec.h -- LZMA + x86 (BCJ) Filter Decoder
2008-08-05
Igor Pavlov
Public domain */

#ifndef __LZMA86DEC_H
#define __LZMA86DEC_H

#include "../Types.h"

/*
Lzma86_GetUnpackSize:
  In:
    src      - input data
    srcLen   - input data size
  Out:
    unpackSize - size of uncompressed stream
  Return code:
    SZ_OK               - OK
    SZ_ERROR_INPUT_EOF  - Error in headers
*/

SRes Lzma86_GetUnpackSize(const Byte *src, SizeT srcLen, UInt64 *unpackSize);

/*
Lzma86_Decode:
  In:
    dest     - output data
    destLen  - output data size
    src      - input data
    srcLen   - input data size
  Out:
    destLen  - processed output size
    srcLen   - processed input size
  Return code:
    SZ_OK           - OK
    SZ_ERROR_DATA  - Data error
    SZ_ERROR_MEM   - Memory allocation error
    SZ_ERROR_UNSUPPORTED - unsupported file
    SZ_ERROR_INPUT_EOF - it needs more bytes in input buffer
*/

SRes Lzma86_Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen);

#endif


text:
namespace LibRbxl.Instances
{
    public class SelectionBox : PVAdornment
    {
        public override string ClassName => "SelectionBox";

        public float LineThickness { get; set; }
        public Color3 SurfaceColor3 { get; set; }
        public float SurfaceTransparency { get; set; }
    }
}