text:
from __future__ import absolute_import
import __builtin__
import warc as ia_warc
from warc.utils import FilePart as ia_FilePart
from urllib3 import HTTPResponse
from urllib3._collections import HTTPHeaderDict
import gzip
from collections import namedtuple

class WARCResponseRecord(ia_warc.WARCRecord):
    """
    Subclass of WARCRecord that exposes an HttpResponse for a response record payload.

    The HttpResponse provides a usable interface to the response and handles chunking and
    decoding.
    """
    def __init__(self, warc_header, http_response):
        ia_warc.WARCRecord.__init__(self, warc_header, defaults=False)
        self.http_response = http_response

class WARCResponseReader():
    """
    A reader of WARC response records that returns WARCResponseRecords.
    """
    def __init__(self, fileobj):
        self._warc_reader = ia_warc.WARCReader(fileobj)

    def __iter__(self):
        for record in self._warc_reader:
            #Only handle responses.
            if record.type == "response":
                payload = CompositeFilePart(record.payload.fileobj, record.payload.length)
                save_payload = self._save_current_payload()
                #If start of a continuation, look for rest of records and build up a
                #ComposeFilePart.
                self._find_continuations(record, payload)

                #Read http start line and headers
                start_line, http_headers = self.read_http_start_line_and_headers(payload)
                if start_line.startswith("HTTP/1.1 200 OK"):

                    http_response = HTTPResponse(body=payload, headers=http_headers, status=200, version=1.1,
                                                 reason="OK", preload_content=False)
                    yield WARCResponseRecord(record.header, http_response)
                    #Setting this so _warc_reader can read to end of record.
                    self._restore_current_payload(save_payload)

    def _find_continuations(self, record, payload):
        #TODO: Also look in subsequent WARCs for continuations.
        if record.header.get("WARC-Segment-Number") == "1":
            segment = 1
            save_payload = self._save_current_payload()
            for peek_record in self._warc_reader:
                #If it's a continuation record and it is related to the original
                #response record.
                if peek_record.type == "continuation" and \
                        peek_record.header.get("WARC-Segment-Origin-ID") == record["WARC-Record-ID"]:
                    #Make sure this is the next segment.
                    segment += 1
                    assert peek_record.header.get("WARC-Segment-Number") == str(segment)
                    payload.add_file_section(peek_record.payload.fileobj, peek_record.payload.fileobj.tell(),
                                             peek_record.payload.length)
                    #Stop when hit last
                    if "WARC-Segment-Total-Length" in peek_record.header:
                        break
                self._warc_reader.finish_reading_current_record()
            self._restore_current_payload(save_payload)

    def _save_current_payload(self):
        save_payload = ia_FilePart(self._warc_reader.current_payload.fileobj,
                                   self._warc_reader.current_payload.length)
        save_payload.buf = self._warc_reader.current_payload.buf
        save_payload.offset = self._warc_reader.current_payload.offset
        save_payload.fileobj_position = self._warc_reader.current_payload.fileobj.tell()
        return save_payload

    def _restore_current_payload(self, save_payload):
        self._warc_reader.current_payload = save_payload
        self._warc_reader.current_payload.fileobj.seek(save_payload.fileobj_position)

    @staticmethod
    def read_http_start_line_and_headers(payload):
        headers = HTTPHeaderDict()
        start_line = None
        for count, line in enumerate(payload):
            if count == 0:
                start_line = line
            elif line == "\r\n":
                break
            else:
                pos = line.index(":")
                assert pos != -1
                headers.add(line[:pos], line[pos+1:].strip())
        return start_line, headers

class WARCResponseFile(ia_warc.WARCFile):
    def __init__(self, filename):
        #Creating own fileobj to bypass IA WARC's own gzip2.
        if filename.endswith(".gz"):
            fileobj = gzip.open(filename, "rb")
        else:
            fileobj = __builtin__.open(filename, "rb")
        ia_warc.WARCFile.__init__(self, fileobj=fileobj)

    @property
    def reader(self):
        if self._reader is None:
            self._reader = WARCResponseReader(self.fileobj)
        return self._reader

FileSection = namedtuple("FileSection", ["fileobj", "start_position", "length", "start_offset", "end_offset"])

class CompositeFilePart():
    """
    File interface to multiple WARC record payloads.
    """
    def __init__(self, fileobj, length):
        self.file_sections = []
        self.file_sections.append(FileSection(fileobj, fileobj.tell(), length, 0, length-1))
        self.total_length = length
        self.offset = 0

    def add_file_section(self, fileobj, start_position, length):
        self.file_sections.append(FileSection(fileobj, start_position, length, self.total_length,
                                              self.total_length + length - 1))
        self.total_length += length

    def _file_section_offset(self, offset):
        if offset > self.total_length:
            offset = self.total_length
        for file_section in self.file_sections:
            if file_section.start_offset <= offset <= file_section.end_offset:
                return file_section, offset - file_section.start_offset + file_section.start_position
        return None, None

    def read(self, size=-1):
        if size == -1:
            size = self.total_length
        ending_offset = min(self.offset + size, self.total_length)
        buf = ""
        i = 0
        while self.offset != ending_offset:
            file_section, file_section_offset = self._file_section_offset(self.offset)
            assert file_section and file_section_offset
            remaining_size = file_section.length - file_section_offset + file_section.start_position
            read_size = min(size - len(buf), remaining_size)
            file_section.fileobj.seek(file_section_offset)
            buf += file_section.fileobj.read(read_size)
            self.offset += read_size
            assert self.offset <= ending_offset
        return buf

    def tell(self):
        return self.offset

    def seek(self, offset, whence=0):
        if whence == 0:
            #Seek from start
            self.offset = offset
        elif whence == 1:
            #Relative to current
            self.offset += offset
        elif whence == 2:
            #Relative to end
            self.offset = self.total_length - offset

    def readline(self):
        chunks = []
        chunk = self.read(1024)
        while chunk and "\n" not in chunk:
            chunks.append(chunk)
            chunk = self.read(1024)
        if "\n" in chunk:
            chunk_len = len(chunk)
            index = chunk.index("\n")
            chunk = chunk[:index+1]
            self.seek((chunk_len-index-1) * -1, 1)
        chunks.append(chunk)
        return "".join(chunks)

    def __iter__(self):
        line = self.readline()
        while line:
            yield line
            line = self.readline()

    @property
    def closed(self):
        return self.offset >= self.total_length

    @property
    def fp(self):
        return self

    def _safe_read(self, size=-1):
        return self.read(size)

    def close(self):
        self.offset = self.total_length


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;

namespace PdfSharp.Xps.XpsModel
{
  class PartHelper
  {
    internal static Stream OpenPartStream(ZipPackage package, Uri uri)
    {
      return (package.GetPart(uri) as ZipPackagePart).GetStream();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
//Switch to the appropriate trace level
#define TRACE_LEVEL FTP_TRACE_LEVEL

//Dependencies
#include <stdlib.h>
#include "ftp/ftp_server.h"
#include "ftp/ftp_server_events.h"
#include "ftp/ftp_server_commands.h"
#include "ftp/ftp_server_misc.h"
#include "str.h"
#include "path.h"
#include "error.h"
#include "debug.h"

//Check TCP/IP stack configuration
#if (FTP_SERVER_SUPPORT == ENABLED)

/**
 * @brief FTP command processing
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 **/

void ftpServerProcessCmd(FtpServerContext *context,
   FtpClientConnection *connection)
{
   size_t n;
   char_t *p;

   //The <CRLF> sequence should be used to terminate the command line
   for(n = 0; n < connection->commandLength; n++)
   {
      if(connection->command[n] == '\n')
         break;
   }

   //Any command to process?
   if(n < connection->commandLength)
   {
      //Properly terminate the string with a NULL character
      connection->command[n] = '\0';
      //Remove trailing whitespace from the command line
      strRemoveTrailingSpace(connection->command);

      //Debug message
      TRACE_DEBUG("FTP client: %s\r\n", connection->command);

      //Command line too long?
      if(connection->controlState == FTP_CONTROL_STATE_DISCARD)
      {
         //Switch to idle state
         connection->controlState = FTP_CONTROL_STATE_IDLE;
         //Format response message
         strcpy(connection->response, "500 Command line too long\r\n");
      }
      else
      {
         //The command name and the arguments are separated by one or more spaces
         for(p = connection->command; *p != '\0' && *p != ' '; p++);

         //Space character found?
         if(*p == ' ')
         {
            //Split the string at the first occurrence of the space character
            *(p++) = '\0';
            //Skip extra whitespace
            while(*p == ' ') p++;
         }

         //NOOP command received
         if(!strcasecmp(connection->command, "NOOP"))
            ftpServerProcessNoop(context, connection, p);
         //SYST command received
         else if(!strcasecmp(connection->command, "SYST"))
            ftpServerProcessSyst(context, connection, p);
         //FEAT command received?
         else if(!strcasecmp(connection->command, "FEAT"))
            ftpServerProcessFeat(context, connection, p);
         //TYPE command received?
         else if(!strcasecmp(connection->command, "TYPE"))
            ftpServerProcessType(context, connection, p);
         //STRU command received?
         else if(!strcasecmp(connection->command, "STRU"))
            ftpServerProcessStru(context, connection, p);
         //MODE command received?
         else if(!strcasecmp(connection->command, "MODE"))
            ftpServerProcessMode(context, connection, p);
         //USER command received?
         else if(!strcasecmp(connection->command, "USER"))
            ftpServerProcessUser(context, connection, p);
         //PASS command received?
         else if(!strcasecmp(connection->command, "PASS"))
            ftpServerProcessPass(context, connection, p);
         //REIN command received?
         else if(!strcasecmp(connection->command, "REIN"))
            ftpServerProcessRein(context, connection, p);
         //QUIT command received?
         else if(!strcasecmp(connection->command, "QUIT"))
            ftpServerProcessQuit(context, connection, p);
         //PORT command received?
         else if(!strcasecmp(connection->command, "PORT"))
            ftpServerProcessPort(context, connection, p);
         //EPRT command received?
         else if(!strcasecmp(connection->command, "EPRT"))
            ftpServerProcessEprt(context, connection, p);
         //PASV command received?
         else if(!strcasecmp(connection->command, "PASV"))
            ftpServerProcessPasv(context, connection, p);
         //EPSV command received?
         else if(!strcasecmp(connection->command, "EPSV"))
            ftpServerProcessEpsv(context, connection, p);
         //ABOR command received?
         else if(!strcasecmp(connection->command, "ABOR"))
            ftpServerProcessAbor(context, connection, p);
         //PWD command received?
         else if(!strcasecmp(connection->command, "PWD"))
            ftpServerProcessPwd(context, connection, p);
         //LIST command received?
         else if(!strcasecmp(connection->command, "LIST"))
            ftpServerProcessList(context, connection, p);
         //CWD command received?
         else if(!strcasecmp(connection->command, "CWD"))
            ftpServerProcessCwd(context, connection, p);
         //CDUP command received?
         else if(!strcasecmp(connection->command, "CDUP"))
            ftpServerProcessCdup(context, connection, p);
         //MKD command received?
         else if(!strcasecmp(connection->command, "MKD"))
            ftpServerProcessMkd(context, connection, p);
         //RMD command received?
         else if(!strcasecmp(connection->command, "RMD"))
            ftpServerProcessRmd(context, connection, p);
         //SIZE command received?
         else if(!strcasecmp(connection->command, "SIZE"))
            ftpServerProcessSize(context, connection, p);
         //RETR command received?
         else if(!strcasecmp(connection->command, "RETR"))
            ftpServerProcessRetr(context, connection, p);
         //STOR command received?
         else if(!strcasecmp(connection->command, "STOR"))
            ftpServerProcessStor(context, connection, p);
         //APPE command received?
         else if(!strcasecmp(connection->command, "APPE"))
            ftpServerProcessAppe(context, connection, p);
         //RNFR command received?
         else if(!strcasecmp(connection->command, "RNFR"))
            ftpServerProcessRnfr(context, connection, p);
         //RNTO command received?
         else if(!strcasecmp(connection->command, "RNTO"))
            ftpServerProcessRnto(context, connection, p);
         //DELE command received?
         else if(!strcasecmp(connection->command, "DELE"))
            ftpServerProcessDele(context, connection, p);
         //Invalid command received?
         else
            ftpServerProcessInvalidCmd(context, connection, p);
      }

      //Debug message
      TRACE_DEBUG("FTP server: %s", connection->response);

      //Number of bytes in the response buffer
      connection->responseLength = strlen(connection->response);
      connection->responsePos = 0;

      //Clear command line
      connection->commandLength = 0;
   }
   else if(connection->commandLength >= FTP_SERVER_MAX_LINE_LEN)
   {
      //The command line is too long...
      connection->controlState = FTP_CONTROL_STATE_DISCARD;
      //Drop incoming data
      connection->commandLength = 0;
   }
}

/**
 * @brief Invalid command processing
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessInvalidCmd(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //Format response message
   strcpy(connection->response, "500 Command unrecognized\r\n");
}

/**
 * @brief NOOP command processing
 *
 * The NOOP command does not affect any parameters or previously entered
 * commands. It specifies no action other than that the server send an OK reply
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessNoop(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //Send an OK reply
   strcpy(connection->response, "200 Command okay\r\n");
}

/**
 * @brief SYST command processing
 *
 * The SYST command is used to find out the type of operating system
 * at the server side
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessSyst(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //Format the response to the SYST command
   strcpy(connection->response, "215 UNIX Type: L8\r\n");
}

/**
 * @brief FEAT command processing
 *
 * The FEAT command allows a client to discover which optional
 * commands a server supports
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessFeat(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //Format the response to the FEAT command
   strcpy(connection->response, "211-Features supported:\r\n");
   strcat(connection->response, " SIZE\r\n");
   strcat(connection->response, " EPRT\r\n");
   strcat(connection->response, " EPSV\r\n");
   strcat(connection->response, "211 End\r\n");
}

/**
 * @brief TYPE command processing
 *
 * The TYPE command specifies the representation type
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessType(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //The argument specifies the representation type
   if(*param != '\0')
   {
      //ASCII type?
      if(!strcasecmp(param, "A"))
      {
         //Format the response to the TYPE command
         strcpy(connection->response, "200 Type set to A\r\n");
      }
      //Image type?
      else if(!strcasecmp(param, "I"))
      {
         //Format the response to the TYPE command
         strcpy(connection->response, "200 Type set to I\r\n");
      }
      //Unknown type?
      else
      {
         //Report an error
         strcpy(connection->response, "504 Unknown type\r\n");
      }
   }
   else
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
   }
}

/**
 * @brief STRU command processing
 *
 * The STRU command specifies the file structure
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessStru(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //The argument specifies the file structure
   if(*param != '\0')
   {
      //No record structure?
      if(!strcasecmp(param, "F"))
      {
         //Format the response to the STRU command
         strcpy(connection->response, "200 Structure set to F\r\n");
      }
      //Unknown file structure?
      else
      {
         //Report an error
         strcpy(connection->response, "504 Unknown structure\r\n");
      }
   }
   else
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
   }
}

/**
 * @brief MODE command processing
 *
 * The MODE command specifies the data transfer mode
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessMode(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //The argument specifies the data transfer mode
   if(*param != '\0')
   {
      //Stream mode?
      if(!strcasecmp(param, "S"))
      {
         //Format the response to the MODE command
         strcpy(connection->response, "200 Mode set to S\r\n");
      }
      //Unknown data transfer mode?
      else
      {
         //Report an error
         strcpy(connection->response, "504 Unknown mode\r\n");
      }
   }
   else
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
   }
}

/**
 * @brief USER command processing
 *
 * The USER command is used to identify the user
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessUser(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   uint_t status;

   //The argument specifies the user name
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Check the length of the user name
   if(strlen(param) > FTP_SERVER_MAX_USERNAME_LEN)
   {
      //The specified user name is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Save user name
   strcpy(connection->user, param);
   //Log out the user
   connection->userLoggedIn = FALSE;
   //Set home directory
   strcpy(connection->homeDir, context->settings.rootDir);
   //Set current directory
   strcpy(connection->currentDir, context->settings.rootDir);

   //Invoke user-defined callback, if any
   if(context->settings.checkUserCallback != NULL)
      status = context->settings.checkUserCallback(connection, param);
   else
      status = FTP_ACCESS_ALLOWED;

   //Access allowed?
   if(status == FTP_ACCESS_ALLOWED)
   {
      //The user is now logged in
      connection->userLoggedIn = TRUE;
      //Format response message
      strcpy(connection->response, "230 User logged in, proceed\r\n");
   }
   //Password required?
   else if(status == FTP_PASSWORD_REQUIRED)
   {
      //This command must be immediately followed by a PASS command
      connection->controlState = FTP_CONTROL_STATE_USER;
      //Format response message
      strcpy(connection->response, "331 User name okay, need password\r\n");
   }
   //Access denied?
   else
   {
      //Format response message
      strcpy(connection->response, "530 Login authentication failed\r\n");
   }
}

/**
 * @brief PASS command processing
 *
 * The USER command specifies the user's password
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessPass(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   uint_t status;

   //This command must immediately follow a USER command
   if(connection->controlState != FTP_CONTROL_STATE_USER)
   {
      //Switch to idle state
      connection->controlState = FTP_CONTROL_STATE_IDLE;
      //Report an error
      strcpy(connection->response, "503 Bad sequence of commands\r\n");
      //Exit immediately
      return;
   }

   //Switch to idle state
   connection->controlState = FTP_CONTROL_STATE_IDLE;

   //The argument specifies the password
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Invoke user-defined callback, if any
   if(context->settings.checkPasswordCallback != NULL)
      status = context->settings.checkPasswordCallback(connection, connection->user, param);
   else
      status = FTP_ACCESS_ALLOWED;

   //Access allowed?
   if(status == FTP_ACCESS_ALLOWED)
   {
      //The user is now logged in
      connection->userLoggedIn = TRUE;
      //Format response message
      strcpy(connection->response, "230 User logged in, proceed\r\n");
   }
   //Access denied?
   else
   {
      //Format response message
      strcpy(connection->response, "530 Login authentication failed\r\n");
   }
}

/**
 * @brief REIN command processing
 *
 * The REIN command is used to reinitialize a user session
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessRein(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //Close data connection
   ftpServerCloseDataConnection(connection);

   //Release previously allocated resources
   if(connection->file != NULL)
   {
      fsCloseFile(connection->file);
      connection->file = NULL;
   }
   if(connection->dir != NULL)
   {
      fsCloseDir(connection->dir);
      connection->dir = NULL;
   }

   //Clear account information
   connection->userLoggedIn = FALSE;

   //Format response message
   strcpy(connection->response, "220 Service ready for new user\r\n");
}

/**
 * @brief QUIT command processing
 *
 * The QUIT command is used to terminate a user session
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessQuit(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //There are two cases to consider upon receipt of this command
   if(connection->dataState == FTP_DATA_STATE_CLOSED)
   {
      //If the FTP service command was already completed, the server closes
      //the data connection (if it is open)...
      ftpServerCloseDataConnection(connection);

      //...and responds with a 221 reply
      strcpy(connection->response, "221 Service closing control connection\r\n");
   }
   else
   {
      //If the FTP service command is still in progress, the server aborts
      //the FTP service in progress and closes the data connection...
      ftpServerCloseDataConnection(connection);

      //...returning a 426 reply to indicate that the service request
      //terminated abnormally
      strcpy(connection->response, "426 Connection closed; transfer aborted\r\n");

      //The server then sends a 221 reply
      strcat(connection->response, "221 Service closing control connection\r\n");
   }

   //Release previously allocated resources
   if(connection->file != NULL)
   {
      fsCloseFile(connection->file);
      connection->file = NULL;
   }
   if(connection->dir != NULL)
   {
      fsCloseDir(connection->dir);
      connection->dir = NULL;
   }

   //Clear account information
   connection->userLoggedIn = FALSE;
   //Gracefully disconnect from the remote host
   connection->controlState = FTP_CONTROL_STATE_WAIT_ACK;
}

/**
 * @brief PORT command processing
 *
 * The PORT command specifies the data port to be used for the data connection
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessPort(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   size_t i;
   size_t j;
   char_t *p;
   char_t *token;
   char_t *end;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument is the concatenation of the IP address and the 16-bit port number
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Close the data connection, if any
   ftpServerCloseDataConnection(connection);

   //Start of exception handling block
   do
   {
      //Assume an error condition...
      error = ERROR_INVALID_SYNTAX;

      //Parse the string
      for(i = 0, j = 1; param[i] != '\0'; i++)
      {
         //Change commas to dots
         if(param[i] == ',' && j < sizeof(Ipv4Addr))
         {
            param[i] = '.';
            j++;
         }
      }

      //Get the IP address to be used
      token = strtok_r(param, ",", &p);
      //Syntax error?
      if(!token) break;

      //Convert the dot-decimal string to a binary IP address
      error = ipStringToAddr(token, &connection->remoteIpAddr);
      //Invalid IP address?
      if(error) break;

      //Assume an error condition...
      error = ERROR_INVALID_SYNTAX;

      //Get the most significant byte of the port number
      token = strtok_r(NULL, ",", &p);
      //Syntax error?
      if(!token) break;

      //Convert the string representation to integer
      connection->remotePort = strtoul(token, &end, 10) << 8;
      //Syntax error?
      if(*end != '\0') break;

      //Get the least significant byte of the port number
      token = strtok_r(NULL, ",", &p);
      //Syntax error?
      if(!token) break;

      //Convert the string representation to integer
      connection->remotePort |= strtoul(token, &end, 10) & 0xFF;
      //Syntax error?
      if(*end != '\0') break;

      //Successful processing
      error = NO_ERROR;

      //End of exception handling block
   } while(0);

   //Any error to report?
   if(error)
   {
      //Re initialize data connection
      connection->passiveMode = FALSE;
      connection->remotePort = 0;

      //Format response message
      strcpy(connection->response, "501 Syntax error in parameters or arguments\r\n");
      //Exit immediately
      return;
   }

   //Successful processing
   strcpy(connection->response, "200 Command okay\r\n");
}

/**
 * @brief EPRT command processing
 *
 * The EPRT command allows for the specification of an extended address
 * for the data connection
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessEprt(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t protocol;
   char_t *p;
   char_t *token;
   char_t *end;
   char_t delimiter[2];

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The extended address must consist of the network protocol
   //as well as the IP address and the 16-bit port number
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Close the data connection, if any
   ftpServerCloseDataConnection(connection);

   //Start of exception handling block
   do
   {
      //A delimiter character must be specified
      delimiter[0] = param[0];
      delimiter[1] = '\0';
      //Skip delimiter character
      param++;

      //Assume an error condition...
      error = ERROR_INVALID_SYNTAX;

      //Retrieve the network protocol to be used
      token = strtok_r(param, delimiter, &p);
      //Syntax error?
      if(!token) break;

      //Convert the string representation to integer
      protocol = strtoul(token, &end, 10);
      //Syntax error?
      if(*end != '\0') break;

      //Get the IP address to be used
      token = strtok_r(NULL, delimiter, &p);
      //Syntax error?
      if(!token) break;

#if (IPV4_SUPPORT == ENABLED)
      //IPv4 address family?
      if(protocol == 1)
      {
         //IPv4 addresses are 4-byte long
         connection->remoteIpAddr.length = sizeof(Ipv4Addr);
         //Convert the string to IPv4 address
         error = ipv4StringToAddr(token, &connection->remoteIpAddr.ipv4Addr);
         //Invalid IP address?
         if(error) break;
      }
      else
#endif
#if (IPV6_SUPPORT == ENABLED)
      //IPv6 address family?
      if(protocol == 2)
      {
         //IPv6 addresses are 16-byte long
         connection->remoteIpAddr.length = sizeof(Ipv6Addr);
         //Convert the string to IPv6 address
         error = ipv6StringToAddr(token, &connection->remoteIpAddr.ipv6Addr);
         //Invalid IP address?
         if(error) break;
      }
      else
#endif
      //Unknown address family?
      {
         //Report an error
         error = ERROR_INVALID_ADDRESS;
         //Exit immediately
         break;
      }

      //Assume an error condition...
      error = ERROR_INVALID_SYNTAX;

      //Get the port number to be used
      token = strtok_r(NULL, delimiter, &p);
      //Syntax error?
      if(!token) break;

      //Convert the string representation to integer
      connection->remotePort = strtoul(token, &end, 10);
      //Syntax error?
      if(*end != '\0') break;

      //Successful processing
      error = NO_ERROR;

      //End of exception handling block
   } while(0);

   //Any error to report?
   if(error)
   {
      //Re initialize data connection
      connection->passiveMode = FALSE;
      connection->remotePort = 0;

      //Format response message
      strcpy(connection->response, "501 Syntax error in parameters or arguments\r\n");
      //Exit immediately
      return;
   }

   //Successful processing
   strcpy(connection->response, "200 Command okay\r\n");
}

/**
 * @brief PASV command processing
 *
 * The PASV command requests the server to listen on a data port and
 * to wait for a connection rather than initiate one upon receipt of
 * a transfer command
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessPasv(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   size_t n;
   IpAddr ipAddr;
   uint16_t port;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //Close the data connection, if any
   ftpServerCloseDataConnection(connection);

   //Start of exception handling block
   do
   {
      //Open data socket
      connection->dataSocket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
      //Failed to open socket?
      if(!connection->dataSocket)
      {
         //Report an error
         error = ERROR_OPEN_FAILED;
         //Exit immediately
         break;
      }

      //Force the socket to operate in non-blocking mode
      error = socketSetTimeout(connection->dataSocket, 0);
      //Any error to report?
      if(error) break;

      //Change the size of the TX buffer
      error = socketSetTxBufferSize(connection->dataSocket, FTP_SERVER_DATA_SOCKET_BUFFER_SIZE);
      //Any error to report?
      if(error) break;

      //Change the size of the RX buffer
      error = socketSetRxBufferSize(connection->dataSocket, FTP_SERVER_DATA_SOCKET_BUFFER_SIZE);
      //Any error to report?
      if(error) break;

      //Associate the socket with the relevant interface
      error = socketBindToInterface(connection->dataSocket, context->settings.interface);
      //Unable to bind the socket to the desired interface?
      if(error) break;

      //Place the data socket in the listening state
      error = socketListen(connection->dataSocket, 1);
      //Any error to report?
      if(error) break;

      //Retrieve local IP address
      error = socketGetLocalAddr(connection->controlSocket, &ipAddr, NULL);
      //Any error to report?
      if(error) break;

      //The local IP address must be a valid IPv4 address
      if(ipAddr.length != sizeof(Ipv4Addr))
      {
         //PASV command cannot be used on IPv6 connections
         error = ERROR_INVALID_ADDRESS;
         //Exit immediately
         break;
      }

      //Retrieve local port number
      error = socketGetLocalAddr(connection->dataSocket, NULL, &port);
      //Any error to report?
      if(error) break;

      //End of exception handling block
   } while(0);

   //Any error to report?
   if(error)
   {
      //Clean up side effects
      ftpServerCloseDataConnection(connection);
      //Format response message
      strcpy(connection->response, "425 Can't enter passive mode\r\n");
      //Exit immediately
      return;
   }

   //Use passive data transfer
   connection->passiveMode = TRUE;
   //Update data connection state
   connection->dataState = FTP_DATA_STATE_LISTEN;

   //Format response message
   n = sprintf(connection->response, "227 Entering passive mode (");
   //Append host address
   ipAddrToString(&ipAddr, connection->response + n);

   //Parse the resulting string
   for(n = 0; connection->response[n] != '\0'; n++)
   {
      //Change dots to commas
      if(connection->response[n] == '.')
         connection->response[n] = ',';
   }

   //Append port number
   sprintf(connection->response + n, ",%" PRIu8 ",%" PRIu8 ")\r\n", MSB(port), LSB(port));
}

/**
 * @brief EPSV command processing
 *
 * The EPSV command requests that a server listen on a data port and
 * wait for a connection
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessEpsv(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint16_t port;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //Close the data connection, if any
   ftpServerCloseDataConnection(connection);

   //Start of exception handling block
   do
   {
      //Open data socket
      connection->dataSocket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP);
      //Failed to open socket?
      if(!connection->dataSocket)
      {
         //Report an error
         error = ERROR_OPEN_FAILED;
         //Exit immediately
         break;
      }

      //Force the socket to operate in non-blocking mode
      error = socketSetTimeout(connection->dataSocket, 0);
      //Any error to report?
      if(error) break;

      //Change the size of the TX buffer
      error = socketSetTxBufferSize(connection->dataSocket, FTP_SERVER_DATA_SOCKET_BUFFER_SIZE);
      //Any error to report?
      if(error) break;

      //Change the size of the RX buffer
      error = socketSetRxBufferSize(connection->dataSocket, FTP_SERVER_DATA_SOCKET_BUFFER_SIZE);
      //Any error to report?
      if(error) break;

      //Associate the socket with the relevant interface
      error = socketBindToInterface(connection->dataSocket, context->settings.interface);
      //Unable to bind the socket to the desired interface?
      if(error) break;

      //Place the data socket in the listening state
      error = socketListen(connection->dataSocket, 1);
      //Any error to report?
      if(error) break;

      //Retrieve local port number
      error = socketGetLocalAddr(connection->dataSocket, NULL, &port);
      //Any error to report?
      if(error) break;

      //End of exception handling block
   } while(0);

   //Any error to report?
   if(error)
   {
      //Clean up side effects
      ftpServerCloseDataConnection(connection);
      //Format response message
      strcpy(connection->response, "425 Can't enter passive mode\r\n");
      //Exit immediately
      return;
   }

   //Use passive data transfer
   connection->passiveMode = TRUE;
   //Update data connection state
   connection->dataState = FTP_DATA_STATE_LISTEN;

   //The response code for entering passive mode using an extended address must be 229
   snprintf(connection->response, FTP_SERVER_MAX_LINE_LEN,
      "229 Entering extended passive mode (|||%" PRIu16 "|)\r\n", port);
}

/**
 * @brief ABOR command processing
 *
 * The ABOR command tells the server to abort the previous FTP
 * service command and any associated transfer of data
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessAbor(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //There are two cases to consider upon receipt of this command
   if(connection->dataState == FTP_DATA_STATE_CLOSED)
   {
      //If the FTP service command was already completed, the server closes
      //the data connection (if it is open)...
      ftpServerCloseDataConnection(connection);

      //...and responds with a 226 reply, indicating that the abort command
      //was successfully processed
      strcpy(connection->response, "226 Abort command successful\r\n");
   }
   else
   {
      //If the FTP service command is still in progress, the server aborts
      //the FTP service in progress and closes the data connection...
      ftpServerCloseDataConnection(connection);

      //...returning a 426 reply to indicate that the service request
      //terminated abnormally
      strcpy(connection->response, "426 Connection closed; transfer aborted\r\n");

      //The server then sends a 226 reply, indicating that the abort command
      //was successfully processed
      strcat(connection->response, "226 Abort command successful\r\n");
   }

   //Release previously allocated resources
   if(connection->file != NULL)
   {
      fsCloseFile(connection->file);
      connection->file = NULL;
   }
   if(connection->dir != NULL)
   {
      fsCloseDir(connection->dir);
      connection->dir = NULL;
   }
}

/**
 * @brief PWD command processing
 *
 * The PWD command causes the name of the current working
 * directory to be returned in the reply
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessPwd(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //A successful PWD command uses the 257 reply code
   snprintf(connection->response, FTP_SERVER_MAX_LINE_LEN,
      "257 \"%s\" is current directory\r\n",
      ftpServerStripHomeDir(connection, connection->currentDir));
}

/**
 * @brief CWD command processing
 *
 * The CWD command allows the user to work with a different
 * directory
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessCwd(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument specifies the pathname
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname
   error = ftpServerGetPath(connection, param,
      connection->path, FTP_SERVER_MAX_PATH_LEN);

   //Make sure the pathname is valid
   if(error)
   {
      //Report an error
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_READ))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Make sure the specified directory exists
   if(!fsDirExists(connection->path))
   {
      //Report an error
      strcpy(connection->response, "550 Directory not found\r\n");
      //Exit immediately
      return;
   }

   //Change current working directory
   strcpy(connection->currentDir, connection->path);

   //A successful PWD command uses the 250 reply code
   snprintf(connection->response, FTP_SERVER_MAX_LINE_LEN,
      "250 Directory changed to %s\r\n",
      ftpServerStripHomeDir(connection, connection->currentDir));
}

/**
 * @brief CDUP command processing
 *
 * The CDUP command allows the user to change to the parent directory
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessCdup(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //Get current directory
   strcpy(connection->path, connection->currentDir);

   //Change to the parent directory
   pathCombine(connection->path, "..", FTP_SERVER_MAX_PATH_LEN);
   pathCanonicalize(connection->path);

   //Retrieve permissions for the directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Check access rights
   if(perm & FTP_FILE_PERM_READ)
   {
      //Update current directory
      strcpy(connection->currentDir, connection->path);
   }

   //A successful PWD command uses the 250 reply code
   snprintf(connection->response, FTP_SERVER_MAX_LINE_LEN,
      "250 Directory changed to %s\r\n",
      ftpServerStripHomeDir(connection, connection->currentDir));
}

/**
 * @brief LIST command processing
 *
 * The LIST command is used to list the content of a directory
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessList(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //Any option flags
   while(*param == '-')
   {
      //Skip option flags
      while(*param != ' ' && *param != '\0')
         param++;
      //Skip whitespace characters
      while(*param == ' ')
         param++;
   }

   //The pathname is optional
   if(*param == '\0')
   {
      //Use current directory if no pathname is specified
      strcpy(connection->path, connection->currentDir);
   }
   else
   {
      //Retrieve the full pathname
      error = ftpServerGetPath(connection, param,
         connection->path, FTP_SERVER_MAX_PATH_LEN);

      //Any error to report?
      if(error)
      {
         //The specified pathname is not valid...
         strcpy(connection->response, "501 Invalid parameter\r\n");
         //Exit immediately
         return;
      }
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_READ))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Open specified directory for reading
   connection->dir = fsOpenDir(connection->path);

   //Failed to open the directory?
   if(!connection->dir)
   {
      //Report an error
      strcpy(connection->response, "550 Directory not found\r\n");
      //Exit immediately
      return;
   }

   //Check current data transfer mode
   if(connection->passiveMode)
   {
      //Check whether the data connection is already opened
      if(connection->dataState == FTP_DATA_STATE_IDLE)
         connection->dataState = FTP_DATA_STATE_SEND;
   }
   else
   {
      //Open the data connection
      error = ftpServerOpenDataConnection(connection);

      //Any error to report?
      if(error)
      {
         //Clean up side effects
         fsCloseDir(connection->dir);
         //Format response
         strcpy(connection->response, "450 Can't open data connection\r\n");
         //Exit immediately
         return;
      }

      //The data connection is ready to send data
      connection->dataState = FTP_DATA_STATE_SEND;
   }

   //Flush transmission buffer
   connection->bufferLength = 0;
   connection->bufferPos = 0;

   //LIST command is being processed
   connection->controlState = FTP_CONTROL_STATE_LIST;

   //Format response message
   strcpy(connection->response, "150 Opening data connection\r\n");
}

/**
 * @brief MKD command processing
 *
 * The MKD command causes the directory specified in the pathname
 * to be created as a directory
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessMkd(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument specifies the pathname
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname
   error = ftpServerGetPath(connection, param,
      connection->path, FTP_SERVER_MAX_PATH_LEN);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_WRITE))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Create the specified directory
   error = fsCreateDir(connection->path);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "550 Can't create directory\r\n");
      //Exit immediately
      return;
   }

   //The specified directory was successfully created
   snprintf(connection->response, FTP_SERVER_MAX_LINE_LEN,
      "257 \"%s\" created\r\n",
      ftpServerStripHomeDir(connection, connection->path));
}

/**
 * @brief RMD command processing
 *
 * The RMD command causes the directory specified in the pathname
 * to be removed
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessRmd(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument specifies the directory to be removed
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname of the directory
   error = ftpServerGetPath(connection, param,
      connection->path, FTP_SERVER_MAX_PATH_LEN);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_WRITE))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Remove the specified directory
   error = fsRemoveDir(connection->path);

   //Any error to report?
   if(error)
   {
      //The specified directory cannot be deleted...
      strcpy(connection->response, "550 Can't remove directory\r\n");
      //Exit immediately
      return;
   }

   //The specified directory was successfully removed
   strcpy(connection->response, "250 Directory removed\r\n");
}

/**
 * @brief SIZE command processing
 *
 * The SIZE command is used to obtain the transfer size of the specified file
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessSize(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;
   uint32_t size;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument specifies the pathname of the file
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname
   error = ftpServerGetPath(connection, param,
      connection->path, FTP_SERVER_MAX_PATH_LEN);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_LIST) && !(perm & FTP_FILE_PERM_READ))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the size of the specified file
   error = fsGetFileSize(connection->path, &size);

   //Any error to report?
   if(error)
   {
      //Report an error
      strcpy(connection->response, "550 File not found\r\n");
      //Exit immediately
      return;
   }

   //Format response message
   sprintf(connection->response, "213 %" PRIu32 "\r\n", size);
}

/**
 * @brief RETR command processing
 *
 * The RETR command is used to retrieve the content of the specified file
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessRetr(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument specifies the pathname of the file to read
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname
   error = ftpServerGetPath(connection, param,
      connection->path, FTP_SERVER_MAX_PATH_LEN);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_READ))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Open specified file for reading
   connection->file = fsOpenFile(connection->path, FS_FILE_MODE_READ);

   //Failed to open the file?
   if(!connection->file)
   {
      //Report an error
      strcpy(connection->response, "550 File not found\r\n");
      //Exit immediately
      return;
   }

   //Check current data transfer mode
   if(connection->passiveMode)
   {
      //Check whether the data connection is already opened
      if(connection->dataState == FTP_DATA_STATE_IDLE)
         connection->dataState = FTP_DATA_STATE_SEND;
   }
   else
   {
      //Open the data connection
      error = ftpServerOpenDataConnection(connection);

      //Any error to report?
      if(error)
      {
         //Clean up side effects
         fsCloseFile(connection->file);
         //Format response
         strcpy(connection->response, "450 Can't open data connection\r\n");
         //Exit immediately
         return;
      }

      //The data connection is ready to send data
      connection->dataState = FTP_DATA_STATE_SEND;
   }

   //Flush transmission buffer
   connection->bufferLength = 0;
   connection->bufferPos = 0;

   //RETR command is being processed
   connection->controlState = FTP_CONTROL_STATE_RETR;

   //Format response message
   strcpy(connection->response, "150 Opening data connection\r\n");
}

/**
 * @brief STOR command processing
 *
 * The STOR command is used to store data to the specified file
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessStor(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument specifies the pathname of the file to written
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname
   error = ftpServerGetPath(connection, param,
      connection->path, FTP_SERVER_MAX_PATH_LEN);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_WRITE))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Open specified file for writing
   connection->file = fsOpenFile(connection->path,
      FS_FILE_MODE_WRITE | FS_FILE_MODE_CREATE);

   //Failed to open the file?
   if(!connection->file)
   {
      //Report an error
      strcpy(connection->response, "550 File not found\r\n");
      //Exit immediately
      return;
   }

   //Check current data transfer mode
   if(connection->passiveMode)
   {
      //Check whether the data connection is already opened
      if(connection->dataState == FTP_DATA_STATE_IDLE)
         connection->dataState = FTP_DATA_STATE_RECEIVE;
   }
   else
   {
      //Open the data connection
      error = ftpServerOpenDataConnection(connection);

      //Any error to report?
      if(error)
      {
         //Clean up side effects
         fsCloseFile(connection->file);
         //Format response
         strcpy(connection->response, "450 Can't open data connection\r\n");
         //Exit immediately
         return;
      }

      //The data connection is ready to receive data
      connection->dataState = FTP_DATA_STATE_RECEIVE;
   }

   //Flush reception buffer
   connection->bufferLength = 0;
   connection->bufferPos = 0;

   //STOR command is being processed
   connection->controlState = FTP_CONTROL_STATE_STOR;

   //Format response message
   strcpy(connection->response, "150 Opening data connection\r\n");
}

/**
 * @brief APPE command processing
 *
 * The APPE command is used to append data to the the specified file
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessAppe(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument specifies the pathname of the file to written
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname
   error = ftpServerGetPath(connection, param,
      connection->path, FTP_SERVER_MAX_PATH_LEN);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_WRITE))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Open specified file for writing
   connection->file = fsOpenFile(connection->path,
      FS_FILE_MODE_WRITE | FS_FILE_MODE_CREATE);

   //Failed to open the file?
   if(!connection->file)
   {
      //Report an error
      strcpy(connection->response, "550 File not found\r\n");
      //Exit immediately
      return;
   }

   //Move to the end of the file
   error = fsSeekFile(connection->file, 0, FS_SEEK_END);

   //Any error to report?
   if(error)
   {
      //Clean up side effects
      fsCloseFile(connection->file);
      //Format response
      strcpy(connection->response, "550 File unavailable\r\n");
   }

   //Check current data transfer mode
   if(connection->passiveMode)
   {
      //Check whether the data connection is already opened
      if(connection->dataState == FTP_DATA_STATE_IDLE)
         connection->dataState = FTP_DATA_STATE_RECEIVE;
   }
   else
   {
      //Open the data connection
      error = ftpServerOpenDataConnection(connection);

      //Any error to report?
      if(error)
      {
         //Clean up side effects
         fsCloseFile(connection->file);
         //Format response
         strcpy(connection->response, "450 Can't open data connection\r\n");
         //Exit immediately
         return;
      }

      //The data connection is ready to receive data
      connection->dataState = FTP_DATA_STATE_RECEIVE;
   }

   //Flush reception buffer
   connection->bufferLength = 0;
   connection->bufferPos = 0;

   //APPE command is being processed
   connection->controlState = FTP_CONTROL_STATE_APPE;

   //Format response message
   strcpy(connection->response, "150 Opening data connection\r\n");
}

/**
 * @brief RNFR command processing
 *
 * The RNFR command specifies the old pathname of the file which is
 * to be renamed
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessRnfr(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument specifies the file to be renamed
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname
   error = ftpServerGetPath(connection, param,
      connection->path, FTP_SERVER_MAX_PATH_LEN);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_WRITE))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Make sure the file exists
   if(!fsFileExists(connection->path) && !fsDirExists(connection->path))
   {
      //No such file or directory...
      strcpy(connection->response, "550 File not found\r\n");
      //Exit immediately
      return;
   }

   //This command must be immediately followed by a RNTO command
   connection->controlState = FTP_CONTROL_STATE_RNFR;
   //Format the response message
   strcpy(connection->response, "350 File exists, ready for destination name\r\n");
}

/**
 * @brief RNTO command processing
 *
 * The RNTO command specifies the new pathname of the file specified
 * in the immediately preceding RNFR command
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessRnto(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;
   char_t newPath[FTP_SERVER_MAX_PATH_LEN];

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //This command must immediately follow a RNFR command
   if(connection->controlState != FTP_CONTROL_STATE_RNFR)
   {
      //Switch to idle state
      connection->controlState = FTP_CONTROL_STATE_IDLE;
      //Report an error
      strcpy(connection->response, "503 Bad sequence of commands\r\n");
      //Exit immediately
      return;
   }

   //Switch to idle state
   connection->controlState = FTP_CONTROL_STATE_IDLE;

   //The argument specifies the new pathname
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname
   error = ftpServerGetPath(connection, param,
      newPath, FTP_SERVER_MAX_PATH_LEN);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, newPath);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_WRITE))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Check whether the file name already exists
   if(fsFileExists(newPath) || fsDirExists(newPath))
   {
      //Report an error
      strcpy(connection->response, "550 File already exists\r\n");
      //Exit immediately
      return;
   }

   //Rename the specified file
   error = fsRenameFile(connection->path, newPath);

   //Any error to report?
   if(error)
   {
      //The specified file cannot be renamed
      strcpy(connection->response, "550 Can't rename file\r\n");
      //Exit immediately
      return;
   }

   //The specified file was successfully deleted
   strcpy(connection->response, "250 File renamed\r\n");
}

/**
 * @brief DELE command processing
 *
 * The DELE command causes the file specified in the pathname to be
 * deleted at the server site
 *
 * @param[in] context Pointer to the FTP server context
 * @param[in] connection Pointer to the client connection
 * @param[in] param Command line parameters
 **/

void ftpServerProcessDele(FtpServerContext *context,
   FtpClientConnection *connection, char_t *param)
{
   error_t error;
   uint_t perm;

   //Ensure the user is logged in
   if(!connection->userLoggedIn)
   {
      //Format response message
      strcpy(connection->response, "530 Not logged in\r\n");
      //Exit immediately
      return;
   }

   //The argument specifies the file to be deleted
   if(*param == '\0')
   {
      //The argument is missing...
      strcpy(connection->response, "501 Missing parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve the full pathname of the file
   error = ftpServerGetPath(connection, param,
      connection->path, FTP_SERVER_MAX_PATH_LEN);

   //Any error to report?
   if(error)
   {
      //The specified pathname is not valid...
      strcpy(connection->response, "501 Invalid parameter\r\n");
      //Exit immediately
      return;
   }

   //Retrieve permissions for the specified directory
   perm = ftpServerGetFilePermissions(context, connection, connection->path);

   //Insufficient access rights?
   if(!(perm & FTP_FILE_PERM_WRITE))
   {
      //Report an error
      strcpy(connection->response, "550 Access denied\r\n");
      //Exit immediately
      return;
   }

   //Delete the specified file
   error = fsDeleteFile(connection->path);

   //Any error to report?
   if(error)
   {
      //The specified file cannot be deleted...
      strcpy(connection->response, "550 Can't delete file\r\n");
      //Exit immediately
      return;
   }

   //The specified file was successfully deleted
   strcpy(connection->response, "250 File deleted\r\n");
}

#endif


text:
'use strict';

angular.module('bs.system').controller('PlayerGridController', ['$compile', '$scope', 'Global', 'Grid', function($compile, $scope, Global, Grid){
  $scope.global = Global;

  var id = 'playerGrid';
  var isMine = true;
  var width = 10;
  var height = 10;
  var lastCoord = {
    x: 0,
    y: 0
  };
  var grid;

  $scope.init = function(){
    grid = new Grid(id, width, height, isMine);
    grid.setTdAttributes({
      droppable : '',
      dropper   : 'dropper',
      drop      : 'handleShipDrop',
      dragover  : 'handleShipDragOver',
      dragenter : 'handleShipDragOver',
      dragleave : 'handleShipDragLeave'
    });
    grid.drawGrid(function(cell){
      $compile(cell)($scope);
    });
  };

  $scope.redraw = function(){
    if(grid instanceof Grid && grid.htmlTable){
      angular.element(grid.htmlTable).empty();
    }
    $scope.init();
  };

  $scope.handleShipDrop = function(draggedItem, targetItem){
    var direction = draggedItem.getAttribute('boat-direction');
    var size = parseInt(draggedItem.getAttribute('boat-size'));
    var tileSize = 100/(size-1);
    var coord = {
      x: targetItem.cellIndex-1,
      y: targetItem.parentNode.rowIndex-1
    };
    var pos = (direction === 'horizontal') ? 'x' : 'y';
    for(var i=0; i<size; i++){
      if(grid.nodeExist(coord.x, coord.y)){
        var cellStyle = grid.getCellAt(coord.x+1, coord.y+1).style;
        cellStyle.backgroundColor = '';
        cellStyle.backgroundImage = 'url("' + draggedItem.toDataURL() + '")';
        cellStyle.backgroundRepeat = 'no-repeat';
        var bgx = i*tileSize+'%';
        var bgy = '0%';
        cellStyle.backgroundPosition = (direction === 'horizontal') ? bgx+' '+bgy : bgy+' '+bgx;
        grid.getNodeAt(coord.y, coord.x).isBoat = true;
      }
      ++coord[pos];
    }
    var li = document.getElementById(draggedItem.id.replace('canvas_', ''));
    li.removeChild(li.getElementsByTagName('img')[0]);
  };

  $scope.handleShipDragOver = function(draggedItem, targetItem){
    var droppable = true;
    var direction = draggedItem.getAttribute('boat-direction');
    var size = parseInt(draggedItem.getAttribute('boat-size'));
    lastCoord = {
      x: targetItem.cellIndex-1,
      y: targetItem.parentNode.rowIndex-1
    };
    var coord = {
      x: lastCoord.x,
      y: lastCoord.y
    };
    var pos = (direction === 'horizontal') ? 'x' : 'y';

    for(var i=0; i<size; i++){
      if(!grid.nodeExist(coord.x, coord.y) || grid.getNodeAt(coord.y, coord.x).isBoat){
        droppable = false;
        break;
      }
      ++coord[pos];
    }
    coord[pos] = lastCoord[pos];

    for(i=0; i<size; i++){
      if(grid.nodeExist(coord.x, coord.y)){
        var cell = grid.getCellAt(coord.x+1, coord.y+1);
        if(droppable){
          cell.style.backgroundColor = 'green';
        }else{
          cell.style.backgroundColor = 'red';
          cell.classList.add('bs-notDroppable');
        }
      }
      ++coord[pos];
    }
  };

  $scope.handleShipDragLeave = function(draggedItem, targetItem){
    var direction = draggedItem.getAttribute('boat-direction');
    var size = parseInt(draggedItem.getAttribute('boat-size'));
    var coord = {
      x: targetItem.cellIndex-1,
      y: targetItem.parentNode.rowIndex-1
    };
    var pos = (direction === 'horizontal') ? 'x' : 'y';
    for(var i=0; i<size; i++){
      if(grid.nodeExist(coord.x, coord.y)){
        var cell = grid.getCellAt(coord.x+1, coord.y+1);
        cell.style.backgroundColor = '';
        cell.classList.remove('bs-notDroppable');
      }
      ++coord[pos];
    }
  };

  $scope.init();
}]);


text:
<!DOCTYPE html>
<meta name="color-scheme" content="dark">

Focus:
      summary

Non-Focus:
      summary


text:
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const es3ifyPlugin = require('es3ify-webpack-plugin')
const ReplacePlugin = require('replace-bundle-webpack-plugin')

module.exports = {

  devtool: 'inline-source-map',

  entry: fs.readdirSync(__dirname).reduce((entries, dir) => {
    const fullDir = path.join(__dirname, dir)
    const entry = path.join(fullDir, 'app.js')
    if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) {
      entries[dir] = ['webpack-hot-middleware/client', entry]
    }

    return entries
  }, {}),

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    chunkFilename: '[id].chunk.js',
    publicPath: '/dist/'
  },

  module: {
    rules: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
    ]
  },

  resolve: {
    alias: {
      avalonx: path.resolve(__dirname, '../dist/avalonx.esm.js')
    }
  },

  plugins: [
    new es3ifyPlugin(),
    new ReplacePlugin([{
      partten: /Object\.defineProperty\((__webpack_exports__|exports),\s*"__esModule",\s*\{\s*value:\s*true\s*\}\);/g,
      replacement: function (str, p1) {
        return p1 + '.__esModule = true;';
      }
    },{
      partten: /\/\**\/\s*Object\.defineProperty\(exports,\s*name,\s*\{[^})]*\}\);/g,
      replacement: function () {
        return '/******/            exports[name] = getter;';
      }
    },{
      partten: /,\s*hotCreateRequire\(moduleId\)/g,
      replacement: function () {
        return ', (this.noHotCreateRequire ? __webpack_require__ : hotCreateRequire(moduleId))'
      }
    },{
      partten: /return\s*?(hotCreateRequire\(\d+\)\((.*)\))/g,
      replacement: function (str, p1, p2) {
        return `return this.noHotCreateRequire ? __webpack_require__(${p2}) : ${p1}`
      }
    },{
      partten: /\(function\(module\)\s*{\/\*eslint-env browser\*\//g,
      replacement: function (str) {
        return '\nif (window.noHotCreateRequire) { return }\n' + str
      }
    }]),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'shared',
      filename: 'shared.js'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  ]

}


text:
module Unity3d
  class Manager
    def work(options)
      Unity3d.config = options

      FastlaneCore::PrintTable.print_values(config: Unity3d.config,
                                         hide_keys: [],
                                             title: "Summary for Unity3d #{Unity3d::VERSION}")

      return Runner.new.run
    end
  end
end


text:
.ajax-wrapper {
  position: relative;
}
.ajax-wrapper .loader {
  background-image: url("images/ajax-loader.gif");
  background-repeat: no-repeat;
  background-position: center 80px;
  background-color: rgba(255, 255, 255, 0.5);
  position: absolute;
  z-index: 10;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  height: auto;
  -webkit-transition: all 0.3s ease-out;
  -moz-transition: all 0.3s ease-out;
  -o-transition: all 0.3s ease-out;
  transition: all 0.3s ease-out;
  opacity: 1;
}
.ajax-wrapper .loader.transparent {
  opacity: 0;
}
.ajax-wrapper .loader.without-height {
  height: 0;
}


text:
{% extends path+"/_layout-case-simple.html" %}

{% block actioncolumn %}

Return to case list

    Appointment booked

{% endblock %}

{% block citizen_detail %}
Bobby Henderson
{% endblock %}

{% block citizen_content %}

Back

New evidence recorded

    <form class="form" action="/{{path }}/scrutiny/timeline-fme" method="post">

							<fieldset>

									<legend class="heading-medium mb10">

										Does the new evidence change the current case status?

									</legend>

										<input id="yes" type="radio" name="pbachoice" value="yes">
										Yes, we now have enough evidence to recommend a paper based assessment

											<input id="no" type="radio" name="pbachoice" value="no">
											No, keep current case status

								</fieldset>

<button class="button">Save and continue</button>

    </form>

{% endblock %}

{# {% block page_script %}

{% endblock %} #}


text:
package androidx.car.app.sample.showcase.common.screens.userinteractions;

import static androidx.car.app.model.Action.BACK;

import androidx.annotation.NonNull;
import androidx.car.app.CarContext;
import androidx.car.app.Screen;
import androidx.car.app.model.ItemList;
import androidx.car.app.model.ListTemplate;
import androidx.car.app.model.Row;
import androidx.car.app.model.Template;
import androidx.car.app.sample.showcase.common.R;
import androidx.lifecycle.DefaultLifecycleObserver;

/** Screen to list different permission demos */
public final class RequestPermissionMenuDemoScreen extends Screen
        implements DefaultLifecycleObserver {

    public RequestPermissionMenuDemoScreen(@NonNull CarContext carContext) {
        super(carContext);
        getLifecycle().addObserver(this);
    }

    @NonNull
    @Override
    public Template onGetTemplate() {
        ItemList.Builder listBuilder = new ItemList.Builder();

        listBuilder.addItem(
                new Row.Builder()
                        .setTitle(getCarContext().getString(R.string.request_permissions_title))
                        .setOnClickListener(() ->
                                getScreenManager().push(
                                        new RequestPermissionScreen(getCarContext())))
                        .setBrowsable(true)
                        .build());
        listBuilder.addItem(
                new Row.Builder()
                        .setTitle(getCarContext().getString(R.string.preseed_permission_demo_title))
                        .setOnClickListener(() ->
                                getScreenManager().push(
                                        new PreSeedPermissionScreen(getCarContext())))
                        .setBrowsable(true)
                        .build());
        return new ListTemplate.Builder()
                .setSingleList(listBuilder.build())
                .setTitle(getCarContext().getString(R.string.request_permission_menu_demo_title))
                .setHeaderAction(BACK)
                .build();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:starshare="http://schemas.android.com/apk/res/com.cloudTop.starshare"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="48dp">

        <TextView
            android:id="@+id/tv_back"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:background="@android:color/transparent"
            android:drawableLeft="@drawable/back_button"
            android:gravity="center"
            android:paddingLeft="12dp"
            android:paddingRight="30dp"
            android:textColor="@color/white"
            android:visibility="visible" />

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_centerInParent="true"
            android:gravity="center_vertical"
            android:text="@string/to_answers"
            android:textColor="@color/color_8C0808"
            android:textSize="@dimen/fontSize_16sp" />

        <TextView
            android:id="@+id/tv_right"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentRight="true"
            android:layout_centerHorizontal="true"
            android:layout_marginRight="15dp"
            android:gravity="center"
            android:padding="5dp"
            android:text="@string/to_publish"
            android:textColor="@color/color_8C0808"
            android:textSize="@dimen/fontSize_16sp"
            android:visibility="visible" />
    </RelativeLayout>

    <EditText
        android:id="@+id/comment"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_marginLeft="26dp"
        android:layout_marginRight="26dp"
        android:layout_marginTop="20dp"
        android:background="@null"
        android:gravity="top"
        android:hint="@string/ask_answers_content"
        android:maxLength="100"
        android:textColor="@color/font_999999"
        android:textSize="@dimen/fontSize_14sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_word_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0"
            android:textColor="@color/color_black_333333"
            android:textSize="@dimen/fontSize_14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/fontSize_14sp"
            android:text="/100"
            android:textColor="@color/color_black_333333"
            android:textSize="@dimen/fontSize_14sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/img_video"
            android:src="@drawable/ask_vdio"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_marginLeft="26dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginLeft="12dp"
            android:text="@string/record_vido_rule"
            android:textColor="@color/font_999999"
            android:textSize="@dimen/fontSize_12sp" />

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="12dp"
        android:layout_marginTop="35dp"
        android:text="@string/anseres_consume_rule"
        android:textColor="@color/color_666666"
        android:textSize="@dimen/fontSize_14sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="right"
        android:orientation="horizontal">

        <TextView
            android:layout_gravity="center_vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/open_questions"
            android:layout_marginRight="16dp"
            android:textColor="@color/color_black_333333"
            android:textSize="@dimen/fontSize_14sp" />

        <com.cloudTop.starshare.widget.EasySwitchButton
            android:layout_gravity="center_vertical"
            android:id="@+id/esb_button_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/dp_26"
            starshare:isOpened="true"
            starshare:switch_off="@drawable/open_questions_off"
            starshare:switch_on="@drawable/open_questions_oppen" />

    </LinearLayout>

</LinearLayout>


text:
#ifndef BoxShape_h
#define BoxShape_h

#include "core/layout/shapes/Shape.h"
#include "platform/geometry/FloatRoundedRect.h"

namespace blink {

class BoxShape final : public Shape {
 public:
  BoxShape(const FloatRoundedRect& bounds) : Shape(), m_bounds(bounds) {}

  LayoutRect shapeMarginLogicalBoundingBox() const override;
  bool isEmpty() const override { return m_bounds.isEmpty(); }
  LineSegment getExcludedInterval(LayoutUnit logicalTop,
                                  LayoutUnit logicalHeight) const override;
  void buildDisplayPaths(DisplayPaths&) const override;

 private:
  FloatRoundedRect shapeMarginBounds() const;

  FloatRoundedRect m_bounds;
};

}  // namespace blink

#endif  // BoxShape_h


text:
package Jan2021Leetcode;

public class _0365WaterAndJugProblem {

	public static void main(String[] args) {
		System.out.println(canMeasureWater(3, 5, 4));

	}

	public static boolean canMeasureWater(int x, int y, int z) {

	}

}


text:
/*
* PROJECT:          Atomix Development
* LICENSE:          BSD 3-Clause (LICENSE.md)
* PURPOSE:          Ldstr MSIL
* PROGRAMMERS:      Aman Priyadarshi (aman.eureka@gmail.com)
*/

using System;
using System.Reflection;

using Atomixilc.Machine;
using Atomixilc.Attributes;
using Atomixilc.Machine.x86;
using Atomixilc.IL.CodeType;

namespace Atomixilc.IL
{
    [ILImpl(ILCode.Ldstr)]
    internal class Ldstr_il : MSIL
    {
        public Ldstr_il()
            : base(ILCode.Ldstr)
        {

        }

        /*
         * URL : https://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.Ldstr(v=vs.110).aspx
         * Description : Pushes a new object reference to a string literal stored in the metadata.
         */
        internal override void Execute(Options Config, OpCodeType xOp, MethodBase method, Optimizer Optimizer)
        {
            var str = ((OpString)xOp).Value;

            /* The stack transitional behavior, in sequential order, is:
             * An object reference to a string is pushed onto the stack.
             */

            switch (Config.TargetPlatform)
            {
                case Architecture.x86:
                    {
                        new Push { DestinationRef = Helper.GetResolvedStringLabel(str) };

                        Optimizer.vStack.Push(new StackItem(typeof(string)));
                        Optimizer.SaveStack(xOp.NextPosition);
                    }
                    break;
                default:
                    throw new Exception(string.Format("Unsupported target platform '{0}' for MSIL '{1}'", Config.TargetPlatform, msIL));
            }
        }
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
	value: true
});

function compactArray(array) {
	var result = [];
	for (var i = 0; i < array.length; ++i) {
		var elem = array[i];
		if (elem != null) {
			result.push(elem);
		}
	}
	return result;
}

exports.default = compactArray;


text:
/* See license.txt for terms of usage */

"use strict";

const self = require("sdk/self");
const main = require("../main.js");

const { Cu } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { Locale } = require("../core/locale.js");
const { loadSheet } = require("sdk/stylesheet/utils");
const { emit, on, off } = require("sdk/event/core");
const { Win } = require("../core/window.js");
const { Xul } = require("../core/xul.js");
const { Dom } = require("../core/dom.js");
const { Options } = require("../core/options.js");
const { System } = require("../core/system.js");
const { ToolbarButton } = require("../chrome/panel-toolbar.js");
const { windows, isDocumentLoaded } = require("sdk/window/utils");
const { prefs } = require("sdk/simple-prefs");
const { getMostRecentBrowserWindow } = require("sdk/window/utils");

const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
const { gDevTools } = Cu.import("resource:///modules/devtools/gDevTools.jsm", {});
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const StylesheetUtils = devtools["require"]("sdk/stylesheet/utils");

// XUL Builder
const { BOX } = Xul;

const Theme = {};

/**
* Load firebug theme stylesheets into the toolbox.
*
* @param {@Toolbox} toolbox Reference to the toolbox instance
*/
Theme.registerFirebugTheme = function(options) {
  let skinUrl = "chrome://firebug/skin/";

  // List of styles to load.
  let sharedStyles = [
    skinUrl + "firebug-style-variables.css",
    skinUrl + "common.css",
    skinUrl + "firebug-theme.css",
    skinUrl + "toolbox.css",
    skinUrl + "scrollbox.css",
    skinUrl + "toolbars.css",
    skinUrl + "buttons.css",
    skinUrl + "splitter.css",
    skinUrl + "searchbox.css",
    skinUrl + "tabmenu.css",
    skinUrl + "options.css",
    skinUrl + "codemirror-firebug.css",
    skinUrl + "panelbase.css",
    skinUrl + "toggle-sidepanels.css",
    skinUrl + "command-editor.css",
    skinUrl + "webconsole.css",
    skinUrl + "markup-view.css",
    skinUrl + "breadcrumbs.css"
  ];

  // List of OS dependent styles are added at the end, so they
  // can override the default (shared) styling.
  // xxxHonza: we might want to automate this. Automatically change
  // URL (add '-os') of every default (shared) stylesheet and append
  // if it exists.
  let osSkinUrl = "chrome://firebug-os/skin/";
  let osStyles = [
    osSkinUrl + "searchbox.css",
    osSkinUrl + "toolbars.css",
    osSkinUrl + "scrollbox.css",
    osSkinUrl + "webconsole.css",
    osSkinUrl + "breadcrumbs.css",
  ]

  // Register new developer tools theme.
  gDevTools.registerTheme({
    id: "firebug",
    label: Locale.$STR("options.label.firebugTheme"),
    stylesheets: sharedStyles.concat(osStyles),
    classList: ["theme-light", "theme-firebug"],
    onApply: this.onThemeApply.bind(this),
    onUnapply: this.onThemeUnapply.bind(this),
  });

  // Set Firebug theme as the default one if Firebug has been installed
  // or enabled. Downgrade and upgrade is also supported since these
  // changes cause Firebug theme deactivation (when uninstalling the
  // previous version). This way e.g. Firebug reinstallation doesn't
  // deactivate theme. There can be some corner cases where Firebug
  // theme is activated while user didn't want to, but in general,
  // if the user is installing Firebug there is good chance he/she wants
  // to see the Firebug theme.
  let reason = options.loadReason;
  if (reason == "install" || reason == "enable" ||
      reason == "upgrade" || reason == "downgrade") {
    // xxxHonza: iterate over all browser windows and tabs and reopen
    // all existing toolboxes in order to properly apply Firebug overlays.
    // TODO: panel overlays (and the toolbox customizations) should be
    // properly applied even on existing panels.
    let browsers = windows("navigator:browser", {includePrivate: true});
    browsers.forEach(browser => {
      let tabBrowser = browser.getBrowser();
      let numTabs = tabBrowser.browsers.length;
      for (let index=0; index<numTabs; index++) {
        reopenToolbox(tabBrowser.mTabs[index]);
      }
    });

    // Activate Firebug theme.
    this.setCurrentTheme("firebug", true);
  }
}

function reopenToolbox(tab) {
  let target = devtools.TargetFactory.forTab(tab);
  let toolbox = gDevTools.getToolbox(target);
  if (toolbox) {
    toolbox.destroy().then(() => {
      let target = devtools.TargetFactory.forTab(tab);
      gDevTools.showToolbox(target);
    });
  }
}

Theme.unregisterFirebugTheme = function(reason) {
  if (reason == "uninstall" || reason == "disable") {
    // Switch into the correct default theme if Firebug theme
    // is the current one.
    if (this.isFirebugActive()) {
      let defaultTheme = System.isDeveloperBrowser() ? "dark" : "light";
      Theme.setCurrentTheme(defaultTheme);
    }
  }

  // Unregister Firebug theme.
  gDevTools.unregisterTheme("firebug");
}

Theme.onThemeApply = function(win, oldTheme) {
  let documentElement = win.document.documentElement;
  let location = documentElement.ownerDocument.location;

  Trace.sysout("theme.onThemeApply; " + location + ", " +
    documentElement.className, win);

  emit(this, "onThemeApply", win, oldTheme);
}

Theme.onThemeUnapply = function(win, newTheme) {
  let documentElement = win.document.documentElement;
  let location = documentElement.ownerDocument.location;

  Trace.sysout("theme.onThemeUnapply; " + location + ", " +
    documentElement.className, win);

  emit(this, "onThemeUnapply", win, newTheme);
}

Theme.addThemeListeners = function(apply, unapply) {
  on(this, "onThemeApply", apply);
  on(this, "onThemeUnapply", unapply);
}

Theme.removeThemeListeners = function(apply, unapply) {
  off(this, "onThemeApply", apply);
  off(this, "onThemeUnapply", unapply);
}

Theme.getCurrentTheme = function() {
  return Services.prefs.getCharPref("devtools.theme");
}

Theme.isFirebugActive = function() {
  return Theme.getCurrentTheme() == "firebug";
}

Theme.toggle = function() {
  let oldValue = this.getCurrentTheme();
  let newValue = this.isFirebugActive() ? "light" : "firebug";

  this.setCurrentTheme(newValue);
}

/**
 * Set a new devtools theme.
 *
 * @param newTheme {String} If of an existing theme.
 * @param force {Boolean} If true the theme switch logic will happen
 * even if the new theme is already active.
 */
Theme.setCurrentTheme = function(newTheme, force) {
  let oldTheme = this.getCurrentTheme();

  if (force) {
    if (oldTheme == newTheme) {
      oldTheme = null;
    }
  }

  if (oldTheme == newTheme) {
    return;
  }

  Services.prefs.setCharPref("devtools.theme", newTheme);

  let data = {
    pref: "devtools.theme",
    newValue: newTheme,
    oldValue: oldTheme
  };

  gDevTools.emit("pref-changed", data);
}

Theme.customizeSideBarSplitter = function(iframeWin, apply) {
  Win.loaded(iframeWin).then(doc => {
    if (apply) {
      // Create a little box in the splitter, so we can theme its top
      // part located between the main and side panel toolbars.
      // Note that the splitter element is available as soon as
      // the document is loaded.
      if (!doc.querySelector(".devtools-side-splitter > .panelSplitterBox")) {
        let splitter = doc.querySelector(".devtools-side-splitter");
        splitter.setAttribute("valign", "top");
        BOX({"class": "panelSplitterBox"}).build(splitter);
      }
    }
    else {
      // Remove customization
      let splitter = doc.querySelector(".devtools-side-splitter");
      splitter.removeAttribute("valign");
      Dom.clearNode(splitter);
    }
  });
}

// Exports from this module
exports.Theme = Theme;


text:
namespace Gateway.Tests.Load
{
    using System;
    using DotNetty.Transport.Channels;

    public class ConsoleLoggingHandler : ChannelHandlerAdapter
    {
        static readonly ConsoleLoggingHandler instance = new ConsoleLoggingHandler();

        ConsoleLoggingHandler()
        {
        }

        public static ConsoleLoggingHandler Instance
        {
            get { return instance; }
        }

        public override bool IsSharable
        {
            get { return true; }
        }

        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            Console.WriteLine("User Event: {0}", evt);
            base.UserEventTriggered(context, evt);
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            Console.WriteLine("Exception: {0}", exception);
            base.ExceptionCaught(context, exception);
        }
    }
}