text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W27078_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Oasis Petroleum Well Summary

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Hanover Federal 5300 44-11 4T Section 11 T153N RIOOW Williams County, ND

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Contingency INTERNIEDIATE CASING AND CEMENT DESIGN

    <p class="styleSans37.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

mm" —_ (psi) I a (si) I b (1000 lbs) /c 9-5/8", 36#, J-55, LTC, 8rd 2020 / 2.20 3520/ 1.28 453/ 1.52

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">API Rating & Sam Factor
Collapse based on full casing evacuation with 10.4 ppg fluid on backside (6484' setting depth).
Burst pressure calculated from a gas kick coming from the production zone (Bakken Pool) at 9,000psi and a subsequent breakdown at the 9-5/8" shoe, based on a 15.2#/ft fracture gradient. Backup of 9 ppg fluid.
Tension based on string weight in 10.4 ppg fluid at 6484' TVD plus 100k# overpull, (Buoyed weight equals 196k lbs.)

    <p class="styleSans6.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Cement volumes are based on 9-5/8" casing set in 12-114 " hole with 10% excess to circulate cement back to surface.

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Pre-flush (Spacer):
Lead Slurry:

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">20 bbls Chem wash
588 sks (304 bbls), 2.90 ft3/sk, 11.5 lblgal Conventional system with 94 lb/sk cement, 4% D079 extender, 2% D053 expanding agent. 2% CaClZ and 0.250 lb/sk D130 lost circulation oontrol agent.

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Tail Slurry:

    <p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans688.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans7.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">580 sks (120 bbls), 1.16 ft3lsk 15.8 lb/gal Conventional system with 94 Ib/sk cement, 0.25% CaCl2, and 0.250 lb/sk lost circulation control agent


text:
class Type##Factory \
{ \
public: \
	static ReturnType Create(__VA_ARGS__); \
};

#define IFACTORY(ReturnType, Type, ...) \
class Type##Factory \
{ \
public: \
	virtual ReturnType Create(__VA_ARGS__) = 0; \
};

redpajama_set_name: RedPajamaGithub


text:
use CreationError;
use CreationError::OsError;
use BuilderAttribs;
use libc;
use std::ptr;

use core_foundation::base::TCFType;
use core_foundation::string::CFString;
use core_foundation::bundle::{CFBundleGetBundleWithIdentifier, CFBundleGetFunctionPointerForName};
use cocoa::base::{id, nil};
use cocoa::appkit::*;

mod gl {
    generate_gl_bindings! {
        api: "gl",
        profile: "core",
        version: "3.2",
        generator: "global",
        extensions: ["GL_EXT_framebuffer_object"],
    }
}

static mut framebuffer: u32 = 0;
static mut texture: u32 = 0;

pub struct HeadlessContext {
    width: uint,
    height: uint,
    context: id,
}

impl HeadlessContext {
    pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
        let (width, height) = builder.dimensions;
        let context = unsafe {
            let attributes = [
                NSOpenGLPFADoubleBuffer as uint,
                NSOpenGLPFAClosestPolicy as uint,
                NSOpenGLPFAColorSize as uint, 24,
                NSOpenGLPFAAlphaSize as uint, 8,
                NSOpenGLPFADepthSize as uint, 24,
                NSOpenGLPFAStencilSize as uint, 8,
                NSOpenGLPFAOffScreen as uint,
                0
            ];

            let pixelformat = NSOpenGLPixelFormat::alloc(nil).initWithAttributes_(&attributes);
            if pixelformat == nil {
                return Err(OsError(format!("Could not create the pixel format")));
            }
            let context = NSOpenGLContext::alloc(nil).initWithFormat_shareContext_(pixelformat, nil);
            if context == nil {
                return Err(OsError(format!("Could not create the rendering context")));
            }
            context
        };

        let headless = HeadlessContext {
            width: width,
            height: height,
            context: context,
        };

        // Load the function pointers as we need them to create the FBO
        gl::load_with(|s| headless.get_proc_address(s) as *const libc::c_void);

        Ok(headless)
    }

    pub unsafe fn make_current(&self) {
        self.context.makeCurrentContext();

        gl::GenFramebuffersEXT(1, &mut framebuffer);
        gl::BindFramebufferEXT(gl::FRAMEBUFFER_EXT, framebuffer);
        gl::GenTextures(1, &mut texture);
        gl::BindTexture(gl::TEXTURE_2D, texture);
        gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
        gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
        gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA8 as i32, self.width as i32, self.height as i32,
                       0, gl::RGBA, gl::UNSIGNED_BYTE, ptr::null());
        gl::FramebufferTexture2DEXT(gl::FRAMEBUFFER_EXT, gl::COLOR_ATTACHMENT0_EXT,
                                    gl::TEXTURE_2D, texture, 0);
        let status = gl::CheckFramebufferStatusEXT(gl::FRAMEBUFFER_EXT);
        if status != gl::FRAMEBUFFER_COMPLETE_EXT {
            panic!("Error while creating the framebuffer");
        }
    }

    pub fn get_proc_address(&self, _addr: &str) -> *const () {
        let symbol_name: CFString = from_str(_addr).unwrap();
        let framework_name: CFString = from_str("com.apple.opengl").unwrap();
        let framework = unsafe {
            CFBundleGetBundleWithIdentifier(framework_name.as_concrete_TypeRef())
        };
        let symbol = unsafe {
            CFBundleGetFunctionPointerForName(framework, symbol_name.as_concrete_TypeRef())
        };
        symbol as *const ()
    }

    pub fn get_api(&self) -> ::Api {
        ::Api::OpenGl
    }
}

unsafe impl Send for HeadlessContext {}
unsafe impl Sync for HeadlessContext {}

impl Drop for HeadlessContext {
    fn drop(&mut self) {
        unsafe {
            gl::DeleteTextures(1, &texture);
            gl::DeleteFramebuffersEXT(1, &framebuffer);
        }
    }
}


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

<!--

 This file is part of the Sylius package.

 (c) Paweł Jędrzejewski

 For the full copyright and license information, please view the LICENSE
 file that was distributed with this source code.

-->

<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
                                        http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

    <class name="Sylius\Bundle\SalesBundle\Model\Order">
        <property name="items">
            <constraint name="Valid" />
        </property>
    </class>

    <class name="Sylius\Bundle\SalesBundle\Model\OrderItem">
        <property name="quantity">
            <constraint name="NotBlank">
                <option name="message">sylius.order_item.quantity.not_blank</option>
                <option name="groups">sylius</option>
            </constraint>
            <constraint name="Type">
                <option name="type">integer</option>
                <option name="message">sylius.order_item.quantity.integer</option>
                <option name="groups">sylius</option>
            </constraint>
            <constraint name="Range">
                <option name="min">1</option>
                <option name="minMessage">sylius.order_item.quantity.min</option>
                <option name="groups">sylius</option>
            </constraint>
        </property>
    </class>

    <class name="Sylius\Bundle\SalesBundle\Model\Adjustment">
        <property name="label">
            <constraint name="NotBlank">
                <option name="message">sylius.adjustment.label.not_blank</option>
                <option name="groups">sylius</option>
            </constraint>
        </property>
        <property name="amount">
            <constraint name="NotBlank">
                <option name="message">sylius.adjustment.amount.not_blank</option>
                <option name="groups">sylius</option>
            </constraint>
            <constraint name="Type">
                <option name="type">integer</option>
                <option name="message">sylius.adjustment.amount.integer</option>
                <option name="groups">sylius</option>
            </constraint>
        </property>
    </class>

</constraint-mapping>


text:
package org.apache.hadoop.hbase.regionserver.wal;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.codec.BaseDecoder;
import org.apache.hadoop.hbase.codec.BaseEncoder;
import org.apache.hadoop.hbase.util.VersionInfo;
import org.apache.phoenix.hbase.index.util.VersionUtil;
import org.apache.phoenix.hbase.index.wal.IndexedKeyValue;
import org.apache.phoenix.hbase.index.wal.KeyValueCodec;

/**
 * Support custom indexing {@link KeyValue}s when written to the WAL.
 *

 * Currently, we don't support reading older WAL files - only new WAL files. Therefore, this should
 * not be installed on a running cluster, but rather one that has been cleanly shutdown and requires
 * no WAL replay on startup.
 */
public class IndexedWALEditCodec extends WALCellCodec {

  // can't have negative values because reading off a stream returns a negative if its the end of
  // the stream
  private static final int REGULAR_KEY_VALUE_MARKER = 0;
  private CompressionContext compression;
  private static final int MIN_BINARY_COMPATIBLE_INDEX_CODEC_VERSION = VersionUtil.encodeVersion("1", "1", "3");
  private final boolean useDefaultDecoder;

  public IndexedWALEditCodec(Configuration conf, CompressionContext compression) {
      super(conf, compression);
      this.compression = compression;
      String hbaseVersion = VersionInfo.getVersion();
      this.useDefaultDecoder = VersionUtil.encodeVersion(hbaseVersion) >= MIN_BINARY_COMPATIBLE_INDEX_CODEC_VERSION;
  }

  @Override
  public Decoder getDecoder(InputStream is) {
    // compression isn't enabled
    if (this.compression == null) {
      return useDefaultDecoder ? new IndexKeyValueDecoder(is) : new BinaryCompatibleIndexKeyValueDecoder(is);
    }

    // there is compression, so we get the standard decoder to handle reading those kvs
    Decoder decoder = super.getDecoder(is);
    // compression is on, reqturn our custom decoder
    return useDefaultDecoder ? new CompressedIndexKeyValueDecoder(is, decoder) : new BinaryCompatibleCompressedIndexKeyValueDecoder(is, decoder);
  }

  @Override
  public Encoder getEncoder(OutputStream os) {
    // compression isn't on, do the default thing
    if (this.compression == null) {
      return new IndexKeyValueEncoder(os);
    }

    // compression is on, return our one that will handle putting in the correct markers
    Encoder encoder = super.getEncoder(os);
    return new CompressedIndexKeyValueEncoder(os, encoder);
  }

  /**
   * Returns a DataInput given an InputStream
   */
  private static DataInput getDataInput(InputStream is) {
    return is instanceof DataInput
        ? (DataInput) is
        : new DataInputStream(is);
  }

  /**
   * Returns a DataOutput given an OutputStream
   */
  private static DataOutput getDataOutput(OutputStream os) {
    return os instanceof DataOutput
        ? (DataOutput) os
        : new DataOutputStream(os);
  }

  private static abstract class PhoenixBaseDecoder extends BaseDecoder {
    protected DataInput dataInput;
    public PhoenixBaseDecoder(InputStream in) {
      super(in);
      dataInput = getDataInput(this.in);
    }
  }

  /**
   * Custom Decoder that can handle a stream of regular and indexed {@link KeyValue}s.
   */
  public static class IndexKeyValueDecoder extends PhoenixBaseDecoder {

    /**
     * Create a Decoder on the given input stream with the given Decoder to parse
     * generic {@link KeyValue}s.
     * @param is stream to read from
     */
    public IndexKeyValueDecoder(InputStream is){
      super(is);
    }

    @Override
    protected KeyValue parseCell() throws IOException{
      return KeyValueCodec.readKeyValue(this.dataInput);
    }
  }

  public static class CompressedIndexKeyValueDecoder extends PhoenixBaseDecoder {

    private Decoder decoder;

    /**
     * Create a Decoder on the given input stream with the given Decoder to parse
     * generic {@link KeyValue}s.
     * @param is stream to read from
     * @param compressedDecoder decoder for generic {@link KeyValue}s. Should support the expected
     *          compression.
     */
    public CompressedIndexKeyValueDecoder(InputStream is, Decoder compressedDecoder) {
      super(is);
      this.decoder = compressedDecoder;
    }

    @Override
    protected Cell parseCell() throws IOException {
      // reader the marker
      int marker = this.in.read();
      if (marker < 0) {
        throw new EOFException(
            "Unexepcted end of stream found while reading next (Indexed) KeyValue");
      }

      // do the normal thing, if its a regular kv
      if (marker == REGULAR_KEY_VALUE_MARKER) {
        if (!this.decoder.advance()) {
          throw new IOException("Could not read next key-value from generic KeyValue Decoder!");
        }
        return this.decoder.current();
      }

      // its an indexedKeyValue, so parse it out specially
      return KeyValueCodec.readKeyValue(this.dataInput);
    }
  }

  private static abstract class PhoenixBaseEncoder extends BaseEncoder {
    protected DataOutput dataOutput;
    public PhoenixBaseEncoder(OutputStream out) {
      super(out);
      dataOutput = getDataOutput(this.out);
    }
  }

  /**
   * Encode {@link IndexedKeyValue}s via the {@link KeyValueCodec}. Does not support
   * compression.
   */
  private static class IndexKeyValueEncoder extends PhoenixBaseEncoder {
    public IndexKeyValueEncoder(OutputStream os) {
      super(os);
    }

    @Override
    public void flush() throws IOException {
      super.flush();
    }

    @Override
    public void write(Cell cell) throws IOException {
      // make sure we are open
      checkFlushed();

      // use the standard encoding mechanism
      KeyValueCodec.write(this.dataOutput, KeyValueUtil.ensureKeyValue(cell));
    }
  }

  /**
   * Write {@link IndexedKeyValue}s along side compressed {@link KeyValue}s. This Encoder is
   * not compatible with the {@link IndexKeyValueDecoder} - one cannot intermingle compressed
   * and uncompressed WALs that contain index entries.
   */
  private static class CompressedIndexKeyValueEncoder extends PhoenixBaseEncoder {
    private Encoder compressedKvEncoder;

    public CompressedIndexKeyValueEncoder(OutputStream os, Encoder compressedKvEncoder) {
      super(os);
      this.compressedKvEncoder = compressedKvEncoder;
    }

    @Override
    public void flush() throws IOException {
      this.compressedKvEncoder.flush();
      super.flush();
    }

    @Override
    public void write(Cell cell) throws IOException {
      //make sure we are open
      checkFlushed();

      //write the special marker so we can figure out which kind of kv is it
      int marker = IndexedWALEditCodec.REGULAR_KEY_VALUE_MARKER;
      if (cell instanceof IndexedKeyValue) {
        marker = KeyValueCodec.INDEX_TYPE_LENGTH_MARKER;
      }
      out.write(marker);

      //then serialize based on the marker
      if (marker == IndexedWALEditCodec.REGULAR_KEY_VALUE_MARKER) {
        this.compressedKvEncoder.write(cell);
      }
      else{
        KeyValueCodec.write(this.dataOutput, KeyValueUtil.ensureKeyValue(cell));
      }
    }
  }

  private static abstract class BinaryCompatiblePhoenixBaseDecoder extends BinaryCompatibleBaseDecoder {
      protected DataInput dataInput;
      public BinaryCompatiblePhoenixBaseDecoder(InputStream in) {
        super(in);
        dataInput = getDataInput(this.in);
      }
  }

  /**
   * This class is meant to be used when runtime version of HBase
   * HBase is older than 1.1.3. This is needed to handle binary incompatibility introduced by
   * HBASE-14501. See PHOENIX-2629 and PHOENIX-2636 for details.
   */
  private static class BinaryCompatibleIndexKeyValueDecoder extends BinaryCompatiblePhoenixBaseDecoder {
      /**
       * Create a Decoder on the given input stream with the given Decoder to parse
       * generic {@link KeyValue}s.
       * @param is stream to read from
       */
      public BinaryCompatibleIndexKeyValueDecoder(InputStream is){
        super(is);
      }

      @Override
      protected KeyValue parseCell() throws IOException{
        return KeyValueCodec.readKeyValue(this.dataInput);
      }
  }

  /**
   * This class is meant to be used when runtime version of HBase
   * HBase is older than 1.1.3. This is needed to handle binary incompatibility introduced by
   * HBASE-14501. See PHOENIX-2629 and PHOENIX-2636 for details.
   */
  private static class BinaryCompatibleCompressedIndexKeyValueDecoder extends BinaryCompatiblePhoenixBaseDecoder {

      private Decoder decoder;

      /**
       * Create a Decoder on the given input stream with the given Decoder to parse
       * generic {@link KeyValue}s.
       * @param is stream to read from
       * @param compressedDecoder decoder for generic {@link KeyValue}s. Should support the expected
       *          compression.
       */
      public BinaryCompatibleCompressedIndexKeyValueDecoder(InputStream is, Decoder compressedDecoder) {
        super(is);
        this.decoder = compressedDecoder;
      }

      @Override
      protected Cell parseCell() throws IOException {
        // reader the marker
        int marker = this.in.read();
        if (marker < 0) {
          throw new EOFException(
              "Unexepcted end of stream found while reading next (Indexed) KeyValue");
        }

        // do the normal thing, if its a regular kv
        if (marker == REGULAR_KEY_VALUE_MARKER) {
          if (!this.decoder.advance()) {
            throw new IOException("Could not read next key-value from generic KeyValue Decoder!");
          }
          return this.decoder.current();
        }

        // its an indexedKeyValue, so parse it out specially
        return KeyValueCodec.readKeyValue(this.dataInput);
      }
  }

}


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Class Phlopsi\AccessControl\User | AccessControl</title>

	<link rel="stylesheet" href="resources/style.css?c2f33731c1948fbed7c333554678bfa68d4817da">

		Overview

Namespaces

						Phlopsi

						AccessControl

						Connection

						Exception

						ExceptionTranslator

						Reflection

Classes

AccessControl

Role

User

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text" placeholder="Search">
	</form>

				Overview

				Namespace

Class

Class User

Phlopsi\AccessControl\User
			 implements
				Phlopsi\AccessControl\Connection\ConnectionAware

			 uses
					Phlopsi\AccessControl\Connection\ConnectionAwareTrait,

					Phlopsi\AccessControl\Exception\TranslateExceptionsTrait

		Namespace: Phlopsi\AccessControl

			Located at Phlopsi/AccessControl/User.php

Methods summary

			 public

		#
		__construct( Phlopsi\AccessControl\Propel\User <var>$user</var> )

Parameters

<var>$user</var>

Codecoverageignore

			 public

			string

		#
		getId( )

Returns

					string

Codecoverageignore

			 public

		#
		addRole( string <var>$role_id</var> )

Parameters

<var>$role_id</var>

Throws

					Phlopsi\AccessControl\Exception\LengthException

					Phlopsi\AccessControl\Exception\RuntimeException

			 public

			boolean

		#
		hasPermission( string <var>$permission_id</var> )

Parameters

<var>$permission_id</var>

Returns

					boolean

Throws

					Phlopsi\AccessControl\Exception\LengthException

			 public

		#
		removeRole( string <var>$role_id</var> )

Parameters

<var>$role_id</var>

Throws

					Phlopsi\AccessControl\Exception\LengthException

					Phlopsi\AccessControl\Exception\RuntimeException

Methods inherited from Phlopsi\AccessControl\Connection\ConnectionAware

			setConnection()

Methods used from Phlopsi\AccessControl\Connection\ConnectionAwareTrait

			setConnection()

		AccessControl API documentation generated by ApiGen


text:
package soinc.hovercraft.ui.live;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.jutils.ui.model.IView;

import soinc.hovercraft.HovercraftIcons;
import soinc.hovercraft.data.HoverConfig;
import soinc.hovercraft.tasks.HovercraftCompetition;
import soinc.hovercraft.tasks.HcTeamCompetition;
import soinc.lib.UiUtils;

/*******************************************************************************
 *
 ******************************************************************************/
public class HcCompetitionView implements IView<JComponent>
{
    /**  */
    private final JPanel view;
    /**  */
    private final HcTeamCompetitionView track1View;
    /**  */
    private final HcTeamCompetitionView track2View;

    /***************************************************************************
     *
     **************************************************************************/
    public HcCompetitionView( HoverConfig config, HovercraftCompetition hc )
    {
        this.track1View = new HcTeamCompetitionView( "Track 1", config, hc.track1 );
        this.track2View = new HcTeamCompetitionView( "Track 2", config, hc.track2 );

        this.view = createView();

        setupHotkeys( hc );
    }

    /***************************************************************************
     * @param hc
     **************************************************************************/
    private void setupHotkeys( HovercraftCompetition hc )
    {
        addHotKeys( track1View.getView(), hc.track1, "F1", "F2", "F3", "F4",
            "control 1", "control 2" );

        addHotKeys( track2View.getView(), hc.track2, "F9", "F10", "F11", "F12",
            "control 9", "control 0" );
    }

    /***************************************************************************
     * @param comp
     * @param track
     * @param startPeriodKey
     * @param failKey
     * @param clearKey
     * @param startRunKey
     * @param stopRunKey
     **************************************************************************/
    private static void addHotKeys( JComponent comp, HcTeamCompetition track,
        String startPeriodKey, String failKey, String resetKey, String clearKey,
        String startRunKey, String stopRunKey )
    {
        UiUtils.addHotKey( comp, startPeriodKey,
            ( e ) -> track.signalStartPauseTrack() );

        UiUtils.addHotKey( comp, failKey, ( e ) -> track.signalFailRun() );

        UiUtils.addHotKey( comp, resetKey, ( e ) -> track.signalResetRun() );

        UiUtils.addHotKey( comp, clearKey, ( e ) -> track.signalClearTrack() );

        UiUtils.addHotKey( comp, startRunKey, ( e ) -> track.signalStartRun() );

        UiUtils.addHotKey( comp, stopRunKey,
            ( e ) -> track.signalCompleteRun() );
    }

    /***************************************************************************
     * @return
     **************************************************************************/
    public JPanel createView()
    {
        JPanel panel = new JPanel( new GridBagLayout() );
        GridBagConstraints constraints;

        panel.setOpaque( true );
        panel.setBackground( new Color( 10, 10, 10 ) );

        constraints = new GridBagConstraints( 0, 0, 1, 1, 1.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
            new Insets( 0, 0, 0, 0 ), 0, 0 );
        panel.add( createHeader(), constraints );

        constraints = new GridBagConstraints( 0, 1, 1, 1, 1.0, 1.0,
            GridBagConstraints.CENTER, GridBagConstraints.BOTH,
            new Insets( 0, 0, 0, 0 ), 0, 0 );
        panel.add( createContent(), constraints );

        return panel;
    }

    /***************************************************************************
     * @return
     **************************************************************************/
    private static Component createHeader()
    {
        JPanel panel = new JPanel( new GridBagLayout() );
        GridBagConstraints constraints;

        Icon bannerIcon = HovercraftIcons.getBannerImage();

        JLabel soLabel = new JLabel( bannerIcon );

        constraints = new GridBagConstraints( 0, 0, 1, 1, 1.0, 1.0,
            GridBagConstraints.CENTER, GridBagConstraints.NONE,
            new Insets( 0, 0, 0, 0 ), 0, 0 );
        panel.add( soLabel, constraints );

        panel.setOpaque( false );

        return panel;
    }

    /***************************************************************************
     * @return
     **************************************************************************/
    private Component createContent()
    {
        JPanel panel = new JPanel( new GridBagLayout() );
        GridBagConstraints constraints;

        panel.setOpaque( false );
        // panel.setBorder( new LineBorder( Color.red, 4 ) );

        JComponent sep = Box.createVerticalBox();
        sep.setOpaque( true );
        sep.setBackground( Color.white );
        sep.setPreferredSize( new Dimension( 5, 30 ) );
        sep.setMinimumSize( sep.getPreferredSize() );

        track1View.getView().setPreferredSize( new Dimension( 50, 50 ) );
        track1View.getView().setMinimumSize( new Dimension( 50, 50 ) );
        track1View.getView().setMaximumSize( new Dimension( 50, 50 ) );

        track2View.getView().setPreferredSize( new Dimension( 50, 50 ) );
        track2View.getView().setMinimumSize( new Dimension( 50, 50 ) );
        track2View.getView().setMaximumSize( new Dimension( 50, 50 ) );

        constraints = new GridBagConstraints( 0, 0, 1, 1, 0.5, 1.0,
            GridBagConstraints.NORTH, GridBagConstraints.BOTH,
            new Insets( 20, 40, 20, 40 ), 0, 0 );
        panel.add( track1View.getView(), constraints );

        constraints = new GridBagConstraints( 1, 0, 1, 1, 0.0, 1.0,
            GridBagConstraints.CENTER, GridBagConstraints.VERTICAL,
            new Insets( 20, 0, 20, 0 ), 0, 0 );
        panel.add( sep, constraints );

        constraints = new GridBagConstraints( 2, 0, 1, 1, 0.5, 1.0,
            GridBagConstraints.NORTH, GridBagConstraints.BOTH,
            new Insets( 20, 40, 20, 40 ), 0, 0 );
        panel.add( track2View.getView(), constraints );

        constraints = new GridBagConstraints( 0, 1, 3, 1, 1.0, 0.0,
            GridBagConstraints.NORTH, GridBagConstraints.BOTH,
            new Insets( 0, 0, 0, 0 ), 0, 0 );
        panel.add( Box.createHorizontalStrut( 0 ), constraints );

        return panel;
    }

    /***************************************************************************
     *
     **************************************************************************/
    @Override
    public JComponent getView()
    {
        return view;
    }

    /***************************************************************************
     * @return
     **************************************************************************/
    public boolean isRunning()
    {
        return track1View.isRunning() || track2View.isRunning();
    }
}


text:
// Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.rendering.logic;

import org.joml.Vector3i;
import org.terasology.nui.Color;

/**
 * Entities with this component will cause a outline be drawn about the specified region in block coordinates.
 */
public class RegionOutlineComponent implements VisualComponent<RegionOutlineComponent> {
    public Vector3i corner1;
    public Vector3i corner2;
    public Color color = new Color(Color.white);

    @Override
    public void copyFrom(RegionOutlineComponent other) {
        this.corner1 = new Vector3i(other.corner1);
        this.corner2 = new Vector3i(other.corner2);
        this.color = new Color(other.color);
    }
}


text:
Create a table with the MD routines.
--]]

-- Create returning table
local ret = {}

ret.MDStep = require "flos.md.mdstep"

return ret


text:
import { createMuiTheme, ThemeOptions } from '@material-ui/core'

export const paletteColorsDark = {
  primary: '#0f4c75',
  secondary: '#3282b8',
  error: '#E44C65',
  background: '#1b262c',
  text: '#bbe1fa',
}

export const paletteColorsLight = {
  primary: '#6886c5',
  secondary: '#ffe0ac',
  error: '#E44C65',
  background: '#f9f9f9',
  text: '#050505',
}

const options = (dark: boolean): ThemeOptions => {
  const paletteColors = dark ? paletteColorsDark : paletteColorsLight
  return {
    palette: {
      type: dark ? 'dark' : 'light',
      primary: {
        main: paletteColors.primary,
      },
    // ...
    }
  }
}
export const darkTheme = createMuiTheme(options(true))
export const lightTheme = createMuiTheme(options(false))


text:
package reactor.netty.http.server;

import io.netty.handler.codec.http.HttpHeaders;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

/**
 * @author Violeta Georgieva
 */
class TrailerHeadersTests {

	static final String ERROR_MESSAGE = "Trailer header name [%s] not declared with [Trailer] header," +
			" or it is not a valid trailer header name";
	static final String COMMA = ",";
	static final String EMPTY = "";
	static final String HEADER_NAME_1 = "foo";
	static final String HEADER_NAME_2 = "bar";
	static final String HEADER_VALUE = "test";
	static final String SPACE = " ";

	@ParameterizedTest(name = "{displayName}({0})")
	@MethodSource("disallowedTrailerHeaderNames")
	void testDisallowedTrailerHeaderNames(String declaredHeaderName) {
		assertThatExceptionOfType(IllegalArgumentException.class)
				.isThrownBy(() -> new HttpServerOperations.TrailerHeaders(declaredHeaderName).add(declaredHeaderName, HEADER_VALUE))
				.withMessage(String.format(ERROR_MESSAGE, declaredHeaderName));
	}

	@ParameterizedTest(name = "{displayName}({index})")
	@ValueSource(strings = {
			HEADER_NAME_1,
			COMMA + HEADER_NAME_1,
			HEADER_NAME_1 + COMMA,
			HEADER_NAME_1 + SPACE,
			HEADER_NAME_1 + COMMA + SPACE
	})
	void testNameIncludedInTrailerHeader(String declaredHeaderNames) {
		HttpHeaders headers = new HttpServerOperations.TrailerHeaders(declaredHeaderNames);
		assertThat(headers.isEmpty()).isTrue();
		headers.add(HEADER_NAME_1, HEADER_VALUE);
		assertThat(headers.isEmpty()).isFalse();
		assertThat(headers.size()).isEqualTo(1);
		assertThat(headers.get(HEADER_NAME_1)).isEqualTo(HEADER_VALUE);
	}

	@Test
	void testNamesIncludedInTrailerHeader() {
		HttpHeaders headers = new HttpServerOperations.TrailerHeaders(HEADER_NAME_1 + ',' + HEADER_NAME_2);
		assertThat(headers.isEmpty()).isTrue();
		headers.add(HEADER_NAME_1, HEADER_VALUE);
		headers.add(HEADER_NAME_2, HEADER_VALUE);
		assertThat(headers.isEmpty()).isFalse();
		assertThat(headers.size()).isEqualTo(2);
		assertThat(headers.get(HEADER_NAME_1)).isEqualTo(HEADER_VALUE);
		assertThat(headers.get(HEADER_NAME_2)).isEqualTo(HEADER_VALUE);
	}

	@Test
	void testNameNotIncludedInTrailerHeader() {
		assertThatExceptionOfType(IllegalArgumentException.class)
				.isThrownBy(() -> new HttpServerOperations.TrailerHeaders(HEADER_NAME_1).add(HEADER_NAME_2, HEADER_VALUE))
				.withMessage(String.format(ERROR_MESSAGE, HEADER_NAME_2));
	}

	@ParameterizedTest(name = "{displayName}({index})")
	@ValueSource(strings = {COMMA, EMPTY, SPACE})
	void testNothingIsIncludedInTrailerHeader(String declaredHeaderNames) {
		assertThatExceptionOfType(IllegalArgumentException.class)
				.isThrownBy(() -> new HttpServerOperations.TrailerHeaders(declaredHeaderNames).add(EMPTY, HEADER_VALUE))
				.withMessage(String.format(ERROR_MESSAGE, EMPTY));
	}

	static Set<String> disallowedTrailerHeaderNames() {
		return HttpServerOperations.TrailerHeaders.DISALLOWED_TRAILER_HEADER_NAMES;
	}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>OpenFin Process Monitor</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="css/main.css">

OpenFin Process Monitor

            Start
            Stop
            Export CPU
            Export Memory
            Learn more »

        <highchart id="processChart" config="cpuChartConfig" class="col-lg-12"></highchart>

        <highchart id="processChart" config="memoryChartConfig" class="col-lg-12"></highchart>

      OpenFin runtime:

        Version: {{ openFinVersion }}


text:
[![Build Status](https://github.com/crossbeam-rs/crossbeam/workflows/CI/badge.svg)](
https://github.com/crossbeam-rs/crossbeam/actions)
[![License](https://img.shields.io/badge/license-MIT_OR_Apache--2.0-blue.svg)](
https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-epoch#license)
[![Cargo](https://img.shields.io/crates/v/crossbeam-epoch.svg)](
https://crates.io/crates/crossbeam-epoch)
[![Documentation](https://docs.rs/crossbeam-epoch/badge.svg)](
https://docs.rs/crossbeam-epoch)
[![Rust 1.36+](https://img.shields.io/badge/rust-1.36+-lightgray.svg)](
https://www.rust-lang.org)
[![chat](https://img.shields.io/discord/569610676205781012.svg?logo=discord)](https://discord.com/invite/JXYwgWZ)

This crate provides epoch-based garbage collection for building concurrent data structures.

When a thread removes an object from a concurrent data structure, other threads
may be still using pointers to it at the same time, so it cannot be destroyed
immediately. Epoch-based GC is an efficient mechanism for deferring destruction of
shared objects until no pointers to them can exist.

Everything in this crate except the global GC can be used in `no_std` environments, provided that
`alloc` feature is enabled.

## Usage

Add this to your `Cargo.toml`:

```toml
[dependencies]
crossbeam-epoch = "0.9"
```

## Compatibility

Crossbeam Epoch supports stable Rust releases going back at least six months,
and every time the minimum supported Rust version is increased, a new minor
version is released. Currently, the minimum supported Rust version is 1.36.

## License

Licensed under either of

 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

#### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.


text:
package com.amazonaws.services.applicationdiscovery.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.applicationdiscovery.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * NeighborConnectionDetail JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class NeighborConnectionDetailJsonUnmarshaller implements Unmarshaller<NeighborConnectionDetail, JsonUnmarshallerContext> {

    public NeighborConnectionDetail unmarshall(JsonUnmarshallerContext context) throws Exception {
        NeighborConnectionDetail neighborConnectionDetail = new NeighborConnectionDetail();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("sourceServerId", targetDepth)) {
                    context.nextToken();
                    neighborConnectionDetail.setSourceServerId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("destinationServerId", targetDepth)) {
                    context.nextToken();
                    neighborConnectionDetail.setDestinationServerId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("destinationPort", targetDepth)) {
                    context.nextToken();
                    neighborConnectionDetail.setDestinationPort(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("transportProtocol", targetDepth)) {
                    context.nextToken();
                    neighborConnectionDetail.setTransportProtocol(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("connectionsCount", targetDepth)) {
                    context.nextToken();
                    neighborConnectionDetail.setConnectionsCount(context.getUnmarshaller(Long.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return neighborConnectionDetail;
    }

    private static NeighborConnectionDetailJsonUnmarshaller instance;

    public static NeighborConnectionDetailJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new NeighborConnectionDetailJsonUnmarshaller();
        return instance;
    }
}


text:
require 'selenium-webdriver'
require_relative '../GoogleDriver'

class GoogleMe < GoogleDriver

  def initialize(driver)
    @driver = driver
    @driver.manage.timeouts.script_timeout = 15
    @driver.manage.timeouts.implicit_wait = 15
    @driver.manage.timeouts.page_load = 15
  end

  def do_google_search
    @driver.find_element(:name, "q").clear
    @driver.find_element(:name, "q").send_keys "Prashanth Sams"
    return GoogleDriver.new(@driver)
  end
end


text:
 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
package BMS::SnpTracker::MapLoc::GeneAlignment;
 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

=head1 DESCRIPTION

=head1 SYNOPSIS

=head1 AUTHOR

Charles Tilford <podmail@biocode.fastmail.fm>

//Subject __must__ include 'Perl' to escape mail filters//

=head1 LICENSE

Copyright 2014 Charles Tilford

 http://mit-license.org/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.

=cut

use strict;
use BMS::SnpTracker::MapLoc::TransientAlignment;
use BMS::SnpTracker::MapLoc::RnaToGeneAlignment;

use vars qw(@ISA);
@ISA      = qw(BMS::SnpTracker::MapLoc::TransientAlignment);

# These objects are created by ::Gene::exon_footprints()
# Each is a genome-anchored alignment representing the union of exonic
# regions for one or more RNAs. These locations could represent complex
# interpretations if a single gene is assigned to multiple locations in the
# genome

sub set_rnas {
    my $self = shift;
    if ($self->{RNA_ALIGN}) {
        $self->err("RNA alignment data already set");
    } elsif (my $hsps = shift) {
        $self->{RNA_ALIGN} = $hsps;
    } else {
        $self->err("No RNA information provided");
    }
}

sub rna_genomic_alignments {
    return map { $_->[0] } @{shift->{RNA_ALIGN} || []};
}

sub each_rna {
    return map { $_->[1] } @{shift->{RNA_ALIGN} || []};
}

sub chrAccId {
    my $self = shift;
    unless (defined $self->{GA_CHR_ACC}) {
        #my @csi = $self->chr_seq_info();
        #my ($gAccId, $cind, $chr, $build) = @{$csi[0] || []};
        #$self->{GA_CHR_ACC} = $gAccId || 0;
        # Just require a pre-set order of [gene,chr]:
        my @sids = $self->seq_ids();
        $self->{GA_CHR_ACC} = $sids[1];
    }
    return $self->{GA_CHR_ACC};
}

sub geneAccId {
    my $self = shift;
    unless (defined $self->{GA_GENE_ACC}) {
        my @sids = $self->seq_ids();
        $self->{GA_GENE_ACC} = $sids[0];
    }
    return $self->{GA_GENE_ACC};
}

sub rna_alignments {
    my $self = shift;
    unless ($self->{RNA_ALIGN_OBJS}) {
        # Generate coordinate alignment (intersection) between Gene and RNA
        # Because the gene was built quickly by collating genomic coordinates
        # we need to tease this out now
        my $arr = $self->{RNA_ALIGN_OBJS} = [];
        my $chrid = $self->chrAccId();
        return () unless ($chrid);
        my $geneid = $self->geneAccId();
        foreach my $rdat (sort { $a->[1]->sortable_value() cmp
                                     $b->[1]->sortable_value() }
                          @{$self->{RNA_ALIGN} || []}) {
            my ($aln, $rna) = @{$rdat};
            my ($rcx) = $rna->cx_genome_part( $aln->pkey );
            my $int = $self->intersect( -hsp => $aln, -anchor => $chrid );
            $int->anchor_id( $geneid );
            bless($int, "BMS::SnpTracker::MapLoc::RnaToGeneAlignment");
            $int->{RGA_GENE_IDX} = $int->seqindex($geneid) * 2;
            $int->{RGA_RNA_IDX}  = $int->seqindex($rna->acc_id) * 2;
            $int->{RGA_RNA_ALN}  = $aln;
            $int->{RGA_RNA_OBJ}  = $rna;
            push @{$arr}, $int;
        }
    }
    return @{$self->{RNA_ALIGN_OBJS}};
}


text:
/* File Name: server.c */
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
using namespace std;
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <univ/log.h>
#include <univ/univ.h>
#include <univ/MD5.h>
#include <univ/threadpool.h>
using namespace Sloong;
using namespace Sloong::Universal;

#include "epollex.h"
#include "msgproc.h"
#include "serverconfig.h"
#include "CmdProcess.h"
#include "userv.h"
#include "structs.h"

SloongWallUS::SloongWallUS()
{
	m_pLog = new CLog();
    m_pEpoll = new CEpollEx();
    m_pMsgProc = new CMsgProc();
	m_bIsRunning = false;
}

SloongWallUS::~SloongWallUS()
{
	Exit();
	CThreadPool::End();
	SAFE_DELETE(m_pEpoll);
	SAFE_DELETE(m_pMsgProc);
    m_pLog->End();
	SAFE_DELETE(m_pLog);
}

void SloongWallUS::Initialize(CServerConfig* config)
{
    m_pConfig = config;
	m_nPriorityLevel = config->m_nPriorityLevel;

    LOGTYPE oType = LOGTYPE::ONEFILE;
    if (!config->m_oLogInfo.LogWriteToOneFile)
	{
        oType = LOGTYPE::DAY;
	}
    m_pLog->Initialize(config->m_oLogInfo.LogPath, config->m_oLogInfo.DebugMode, LOGLEVEL(config->m_oLogInfo.LogLevel), oType);

    m_pLog->SetWorkInterval(config->m_nSleepInterval);
    m_pEpoll->Initialize(m_pLog,config->m_nPort,config->m_nEPoolThreadQuantity,config->m_nPriorityLevel,
				config->m_bEnableSwiftNumberSup, config->m_bEnableMD5Check, config->m_nConnectTimeout,
		config->m_nTimeoutInterval,config->m_nReceiveTimeout, config->m_nClientCheckTime, config->m_strClientCheckKey);
	m_pEpoll->SetLogConfiguration(m_pConfig->m_oLogInfo.ShowSendMessage, m_pConfig->m_oLogInfo.ShowReceiveMessage);
    m_pEpoll->SetEvent(&m_oEventCV);
    m_pMsgProc->Initialize(m_pLog,&config->m_oConnectInfo, &config->m_oLuaConfigInfo, config->m_oLogInfo.ShowSQLCmd, config->m_oLogInfo.ShowSQLResult);
}

void SloongWallUS::Run()
{
	m_bIsRunning = true;
	CThreadPool::AddWorkThread(SloongWallUS::HandleEventWorkLoop, this, m_pConfig->m_nProcessThreadQuantity);
	unique_lock<mutex> lck(m_oEventMutex);
	while (m_bIsRunning)
	{
		m_oEventCV.wait(lck);
	}
	Exit();
}

void* SloongWallUS::HandleEventWorkLoop(void* pParam)
{
	SloongWallUS* pThis = (SloongWallUS*)pParam;
    auto log = pThis->m_pLog;
    auto pid = this_thread::get_id();
    string spid = CUniversal::ntos(pid);
    log->Info("Event process thread is running." + spid);
	int id = -1;
	try
	{
		id = pThis->m_pMsgProc->NewThreadInit();
	}
	catch (exception& e)
	{
		log->Fatal("Exception happened in start message process thread. info:[" + string(e.what()) + "]");
		throw e;
	}

    unique_lock<mutex> lck(pThis->m_oEventMutex);
	while (pThis->m_bIsRunning)
	{
		if (!pThis->m_pEpoll->m_EventSockList.empty())
        {
			unique_lock<mutex> eventLoc(pThis->m_pEpoll->m_oEventListMutex);
			if (pThis->m_pEpoll->m_EventSockList.empty())
				continue;

			// process read list.
			EventListItem item = pThis->m_pEpoll->m_EventSockList.front();
			pThis->m_pEpoll->m_EventSockList.pop();
			eventLoc.unlock();

			CSockInfo* info = pThis->m_pEpoll->m_SockList[item.nSocket];
			if (!info)
			{
				log->Error(CUniversal::Format("Get socket info from socket list error, the info is NULL. socket id is: %d", item.nSocket));
				continue;
			}

			if (item.emType == EventType::ReceivedData)
			{
				for (int i = 0; i < pThis->m_nPriorityLevel || i == 0; i++)
				{
					// try to lock the process mutex in current priority level.
					if (info->m_pProcessMutexList[i].try_lock() == false)
					{
						// this sock is processed in other thread. continue
						continue;
					}

					unique_lock<mutex> lock(info->m_pProcessMutexList[i], std::adopt_lock);

					pThis->ProcessEventList(id, &info->m_pReadList[i], info->m_oReadListMutex, item.nSocket, i, info->m_pUserInfo, pThis->m_pEpoll, pThis->m_pMsgProc);

					// unlock current level.
					lock.unlock();
				}

			}
			else if (item.emType == EventType::SocketClose)
			{
				// call close function.
				pThis->m_pMsgProc->CloseSocket(id,info->m_pUserInfo);
				pThis->m_pEpoll->CloseSocket(item.nSocket);
			}

		}
		else
		{
            pThis->m_oEventCV.wait_for(lck,chrono::minutes(1));
        }
	}
	return NULL;
}

void Sloong::SloongWallUS::ProcessEventList(int id, queue<RECVINFO>* pList, mutex& oLock, int sock, int nPriorityLevel, CLuaPacket* pUserInfo, CEpollEx* pEpoll, CMsgProc* pMsgProc)
{
	// if not empty
	while (!pList->empty())
	{
		if (oLock.try_lock() == false)
		{
			continue;
		}
		unique_lock<mutex> readLoc(oLock, std::adopt_lock);
		// recheck is not empty when lock done.
		if (pList->empty())
		{
			oLock.unlock();
			continue;
		}

		RECVINFO msg = pList->front();
		pList->pop();
		oLock.unlock();
		ProcessEvent(id, &msg, sock, nPriorityLevel, pUserInfo, pEpoll,pMsgProc);
	}
}

void Sloong::SloongWallUS::ProcessEvent(int id, RECVINFO* info, int sock, int nPriorityLevel, CLuaPacket* pUserInfo, CEpollEx* pEpoll, CMsgProc* pMsgProc)
{
	if (m_pConfig->m_bEnableMD5Check)
	{
		string rmd5 = CMD5::Encoding(info->strMessage);
		CUniversal::touper(info->strMD5);
		CUniversal::touper(rmd5);
		if (info->strMD5 != rmd5)
		{
			// handle error.
			pEpoll->SendMessage(sock, nPriorityLevel, info->nSwiftNumber, CUniversal::Format("{\"errno\": \"-1\",\"errmsg\" : \"package check error\",\"server_md5\":\"%s\",\"client_md5\":\"%s\",\"check_string\":\"%s\"}",rmd5,info->strMD5,info->strMessage));
			return;
		}
	}

	string strRes("");
	char* pBuf = NULL;
	int nSize = pMsgProc->MsgProcess(id, pUserInfo, info->strMessage, strRes, pBuf);
	pEpoll->SendMessage(sock, nPriorityLevel, info->nSwiftNumber, strRes, pBuf, nSize);
}

void Sloong::SloongWallUS::Exit()
{
	m_pEpoll->Exit();
	m_bIsRunning = false;
    unique_lock<mutex> lck(m_oEventMutex);
    m_oEventCV.notify_all();
}


text:
package org.apache.struts.tiles.actions;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.ComponentContext;

/**
 * Base class for Tiles Actions.
 * This class has the same role as Struts Action. It provides a method execute(...)
 * called when action is invoked. The difference is, that the execute() method takes
 * an additional parameter : tile context.
 * This class extends Struts Action. Subclasses should override
 * execute(ComponentContext ...) method instead of Struts
 * execute(ActionMapping ...) method.
 * @version $Rev$ $Date$
 */
public abstract class TilesAction extends Action {

    /**
     * Original Struts Action's method.
     * Retrieve current Tile context and call TilesAction execute method.
     * Do not overload this method!
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request (if any).
     * @param request The HTTP request we are processing.
     * @param response The HTTP response we are creating.
     *
     * @exception Exception if the application business logic throws
     *  an exception
     * @since Struts 1.1
     */
    public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception {

        // Try to retrieve tile context
        ComponentContext context = ComponentContext.getContext(request);
        if (context == null) {
            throw new ServletException(
                "Can't find Tile context for '"
                    + this.getClass().getName()
                    + "'. TilesAction subclasses must be called from a Tile");
        }

        return this.execute(context, mapping, form, request, response);
    }

    /**
     * Process the specified HTTP request and create the corresponding HTTP
     * response (or forward to another web component that will create it),
     * with provision for handling exceptions thrown by the business logic.
     * <br>
     * Override this method to provide functionality.
     *
     * @param context The current Tile context, containing Tile attributes.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request (if any).
     * @param request The HTTP request we are processing.
     * @param response The HTTP response we are creating.
     *
     * @exception Exception if the application business logic throws
     *  an exception
     * @since Struts 1.1
     */
    public ActionForward execute(
        ComponentContext context,
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response)
        throws Exception {

        return null;
    }

}


text:
Outlier Detection
=================

The hdbscan library supports the GLOSH outlier detection algorithm, and
does so within the HDBSCAN clustering class. The GLOSH outlier detection
algorithm is related to older outlier detection methods such as
`LOF <https://en.wikipedia.org/wiki/Local_outlier_factor>`__ and
`LOCI <http://www.informedia.cs.cmu.edu/documents/loci_icde03.pdf>`__.
It is a fast and flexible outlier detection system, and supports a
notion of local outliers. This means that it can detect outliers that
may be noticeably different from points in its local region (for example
points not on a local submanifold) but that are not necessarily outliers
globally. So how do we find outliers? We proceed identically to the
basic use of HDBSCAN\*. We start with some data, and fit it with an
HDBSCAN object.

.. code:: python

    plt.scatter(*data.T, s=50, linewidth=0, c='b', alpha=0.25)

.. image:: images/outlier_detection_3_1.png

.. code:: python

    clusterer = hdbscan.HDBSCAN(min_cluster_size=15).fit(data)

The clusterer object now has an attribute (computed when first accessed)
called ``outlier_scores_``. This provides a numpy array with a value for
each sample in the original dataset that was fit with the clusterer. The
higher the score, the more likely the point is to be an outlier. In
practice it is often best to look at the distributions of outlier
scores.

.. code:: python

    clusterer.outlier_scores_

.. parsed-literal::

    array([ 0.14791852,  0.14116731,  0.09171929, ...,  0.62050534,
            0.56749298,  0.20681685])

.. code:: python

    sns.distplot(clusterer.outlier_scores_[np.isfinite(clusterer.outlier_scores_)], rug=True)

.. image:: images/outlier_detection_7_1.png

We can pull off upper quantiles to detect outliers, which we can then
plot.

.. code:: python

    threshold = pd.Series(clusterer.outlier_scores_).quantile(0.9)
    outliers = np.where(clusterer.outlier_scores_ > threshold)[0]
    plt.scatter(*data.T, s=50, linewidth=0, c='gray', alpha=0.25)
    plt.scatter(*data[outliers].T, s=50, linewidth=0, c='red', alpha=0.5)

.. image:: images/outlier_detection_9_1.png

Note that not only are the outlying border points highlighted as
outliers, but points at the edge of the central ball like cluster, and
just below the vertical band cluster, are also designated as outliers.
This is because those two clusters are extremely dense, and the points
at the edge of this cluster are close enough to the cluster that they
should be part of it, but far enough from the being core parts of the
cluster that they are extremely unlikely and hence anomalous.


text:
<?php

return [
    // Components
    'components' => [
        'status' => [
            1 => 'Funktionsfähig',
            2 => 'Performance Probleme',
            3 => 'Teilweise Ausfall',
            4 => 'größerer Ausfall',
        ],
    ],

    // Incidents
    'incidents' => [
        'none'          => 'keine Vorfälle.',
        'past'          => 'vergangene Vorfälle',
        'previous_week' => 'letzte Woche',
        'next_week'     => 'nächste Woche',
        'none'          => 'keine Vorfälle',
        'status'        => [
            0 => '',
            1 => 'Untersuchung läuft',
            2 => 'Problem identifiziert',
            3 => 'Problem unter Beobachtung',
            4 => 'Problem behoben',
        ],
    ],

    // Service Status
    'service' => [
        'good' => 'Alle Systeme laufen.',
        'bad'  => 'Bei einigen System sind Fehler aufgetreten.',
    ],

    'api' => [
        'regenerate' => 'API-Schlüssel generieren',
        'revoke'     => 'API-Schlüssel löschen',
    ],

    // Metrics
    'metrics' => [
        'filter' => [
            'hourly'  => 'Hourly',
            'daily'   => 'Daily',
            'monthly' => 'Monthly',
        ],
    ],

    // Subscriber
    'subscriber' => [
        'subscribe' => 'Subscribe to get the most recent updates.',
        'button'    => 'Subscribe',
        'email'     => [
            'subscribe'    => 'Subscribe to email updates.',
            'subscribed'   => 'You\'ve been subscribed to email notifications, please check your email to confirm your subscription.',
            'verified'     => 'Your email subscription has been confirmed. Thank you!',
            'unsubscribe'  => 'Unsuscribe from email updates.',
            'unsubscribed' => 'Your email subscription has been cancelled.',
            'failure'      => 'Something went wrong with the subscription.',
            'verify'       => [
                'text'           => "Please confirm your email subscription to :app_name status updates.\n:link\nThank you, :app_name",
                'html-preheader' => 'Please confirm your email subscription to :app_name status updates.',
                'html'           => '
Please confirm your email subscription to :app_name status updates.

:link

Thank you, :app_name
',
            ],
            'maintenance' => [
                'text'           => "New maintenance has been scheduled on :app_name.\nThank you, :app_name",
                'html-preheader' => 'New maintenance has been scheduled on :app_name.',
                'html'           => '
New maintenance has been scheduled on :app_name.

Thank you, :app_name
',
            ],
            'incident' => [
                'text'           => "New incident has been reported on :app_name.\nThank you, :app_name",
                'html-preheader' => 'New incident has been reported on :app_name.',
                'html'           => '
New incident has been reported on :app_name.

Thank you, :app_name
',
            ],
        ],
    ],

    // Other
    'powered_by'      => ':app Status-Seite via Cachet.',
    'about_this_site' => 'Über diese Seite',
    'rss-feed'        => 'RSS Feed',
    'atom-feed'       => 'Atom Feed',
    'feed'            => 'Status Feed',

];


text:
get_filename_component(CMAKE_CURRENT_LIST_FILENAME ${CMAKE_CURRENT_LIST_FILE} NAME_WE)
if(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED)
  return()
endif()
set(${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED 1)

# Sanity checks
if(DEFINED BRAINSTools_SOURCE_DIR AND NOT EXISTS ${BRAINSTools_SOURCE_DIR})
  message(FATAL_ERROR "BRAINSTools_SOURCE_DIR variable is defined but corresponds to non-existing directory")
endif()

# Set dependency list
set(BRAINSTools_DEPENDENCIES ${ITK_EXTERNAL_NAME} SlicerExecutionModel VTK )

# Include dependent projects if any
SlicerMacroCheckExternalProjectDependency(BRAINSTools)
set(proj BRAINSTools)

# Set CMake OSX variable to pass down the external project
set(CMAKE_OSX_EXTERNAL_PROJECT_ARGS)
if(APPLE)
  list(APPEND CMAKE_OSX_EXTERNAL_PROJECT_ARGS
    -DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}
    -DCMAKE_OSX_SYSROOT=${CMAKE_OSX_SYSROOT}
    -DCMAKE_OSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET})
endif()

if(NOT DEFINED BRAINSTools_SOURCE_DIR)
  #message(STATUS "${__indent}Adding project ${proj}")
  set(GIT_TAG "98a46a2b08da882d46f04cbf0d539c2b73348049")

  if(NOT DEFINED git_protocol)
    set(git_protocol "git")
  endif()

  #message("VTK_DIR: ${VTK_DIR}")
  #message("ITK_DIR: ${ITK_DIR}")
  #message("SlicerExecutionModel_DIR: ${SlicerExecutionModel_DIR}")
  ExternalProject_Add(${proj}
    GIT_REPOSITORY "${git_protocol}://github.com/BRAINSia/BRAINSStandAlone.git"
    GIT_TAG "${GIT_TAG}"
    SOURCE_DIR ${proj}
    BINARY_DIR ${proj}-build
    CMAKE_GENERATOR ${gen}
    "${cmakeversion_external_update}"
    CMAKE_ARGS
      -Wno-dev
      --no-warn-unused-cli
      ${CMAKE_OSX_EXTERNAL_PROJECT_ARGS}
      ${COMMON_EXTERNAL_PROJECT_ARGS}
      -DBUILD_EXAMPLES:BOOL=OFF
      -DBUILD_TESTING:BOOL=OFF
      -DUSE_SYSTEM_ITK:BOOL=ON
      -DUSE_SYSTEM_VTK:BOOL=ON
      -DUSE_SYSTEM_SlicerExecutionModel:BOOL=ON
      -DITK_DIR:PATH=${ITK_DIR}
      -DVTK_DIR:PATH=${VTK_DIR}
      -DUSE_ANTS:BOOL=OFF
      -DUSE_AutoWorkup:BOOL=OFF
      -DUSE_BRAINSABC:BOOL=OFF
      -DUSE_BRAINSConstellationDetector:BOOL=OFF
      -DUSE_BRAINSContinuousClass:BOOL=OFF
      -DUSE_BRAINSCut:BOOL=OFF
      -DUSE_BRAINSDemonWarp:BOOL=OFF
      -DUSE_BRAINSFit:BOOL=ON
      -DUSE_BRAINSFitEZ:BOOL=OFF
      -DUSE_BRAINSImageConvert:BOOL=OFF
      -DUSE_BRAINSInitializedControlPoints:BOOL=OFF
      -DUSE_BRAINSLandmarkInitializer:BOOL=OFF
      -DUSE_BRAINSMultiModeSegment:BOOL=OFF
      -DUSE_BRAINSMush:BOOL=OFF
      -DUSE_BRAINSROIAuto:BOOL=ON
      -DUSE_BRAINSResample:BOOL=ON
      -DUSE_BRAINSSnapShotWriter:BOOL=OFF
      -DUSE_BRAINSSurfaceTools:BOOL=OFF
      -DUSE_BRAINSTransformConvert:BOOL=OFF
      -DUSE_DebugImageViewer:BOOL=OFF
      -DUSE_GTRACT:BOOL=ON
      -DUSE_ICCDEF:BOOL=OFF
      -DUSE_ImageCalculator:BOOL=ON
      -DSlicerExecutionModel_DIR:PATH=${SlicerExecutionModel_DIR}
      ${${proj}_CMAKE_OPTIONS}
    INSTALL_COMMAND ""
    DEPENDS
      ${BRAINSTools_DEPENDENCIES}
    )
  set(BRAINSTools_SOURCE_DIR ${CMAKE_BINARY_DIR}/${proj})
  set(BRAINSCommonLib_DIR    ${CMAKE_BINARY_DIR}/${proj}-build/BRAINSTools-build/BRAINSCommonLib)
else()
  # The project is provided using BRAINSTools_DIR, nevertheless since other project may depend on BRAINSTools,
  # let's add an 'empty' one
  SlicerMacroEmptyExternalProject(${proj} "${BRAINSTools_DEPENDENCIES}")
endif()


text:
<polymer-element name="w5-accordion" attributes="name colspan selected">

    <template>

            <content select="w5-panel"></content>

    </template>

</polymer-element>


text:
/**
 * @author richt / http://richt.me
 * @author WestLangley / http://github.com/WestLangley
 *
 * W3C Device Orientation control (http://w3c.github.io/deviceorientation/spec-source-orientation.html)
 */

THREE.DeviceOrientationControls = function () {

	var _scope = this;

	var _enabled = false;

	var _oldRotationOrder = "";

	var _q = new THREE.Quaternion();	// Tracks orientation

	var _qScreen = new THREE.Quaternion();
	var _qOrient = new THREE.Quaternion( - Math.sqrt( 0.5 ), 0, 0, Math.sqrt( 0.5 ) ); // - PI/2 around the x-axis

	var _zUp = new THREE.Vector3( 0, 0, 1 );

	var _euler = new THREE.Euler();

	this.deviceOrientation = {};
	this.screenOrientation = window.orientation || 0; // 90,-90 = landscape, 0,180 = portrait

	var onDeviceOrientationChangeEvent = function ( event ) {

		_scope.deviceOrientation = event;

	};

	var getOrientation = function() {
		switch (window.screen.orientation || window.screen.mozOrientation) {
		case 'landscape-primary':
			return 90;
		case 'landscape-secondary':
			return -90;
		case 'portrait-secondary':
			return 180;
		case 'portrait-primary':
			return 0;
		}

		// this returns 90 if width is greater then height
		// and window orientation is undefined OR 0
		// if (!window.orientation && window.innerWidth > window.innerHeight)
		//   return 90;
		return window.orientation || 0;
	};

	var onScreenOrientationChangeEvent = function() {

		_scope.screenOrientation = getOrientation();

	};

	this.connect = function() {

		onScreenOrientationChangeEvent(); // run once on load

		window.addEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
		window.addEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );

		_enabled = true;

	};

	this.disconnect = function() {

		_enabled = false;

		window.removeEventListener( 'orientationchange', onScreenOrientationChangeEvent, false );
		window.removeEventListener( 'deviceorientation', onDeviceOrientationChangeEvent, false );
	};

	// Returns a Quaternion containing current orientation
	this.update = function () {

		if ( _enabled === false )
			return null;

		// Y-up coordinate system with portrait the default for a mobile device.
		// If device rotated then need to handle.

		// alpha: rotation around z-axis, 0 = north, increasing as rotated CCW
		var alpha = _scope.deviceOrientation.alpha ? THREE.Math.degToRad( _scope.deviceOrientation.alpha ) : 0; // Z
		// gamma: left to right, -90 to left, 0 = level, 90 to right
		var beta  = _scope.deviceOrientation.beta  ? THREE.Math.degToRad( _scope.deviceOrientation.beta  ) : 0; // X'
		// beta: front back motion, -180 tilt up, 0 = level, 180 = tilt down
		var gamma = _scope.deviceOrientation.gamma ? THREE.Math.degToRad( _scope.deviceOrientation.gamma ) : 0; // Y''

		var orient = _scope.screenOrientation      ? THREE.Math.degToRad( _scope.screenOrientation       ) : 0; // orientation 0,90,-90,180

		// The angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''
		_euler.set( beta, alpha, -gamma, 'YXZ' );             		// 'ZXY' for the device, but need 'YXZ'
		_q.setFromEuler( _euler );                              	// orient the device
		_q.multiply( _qOrient );                                    // camera looks out the back of the device, not the top
		_q.multiply( _qScreen.setFromAxisAngle( _zUp, - orient ) );	// adjust for screen orientation

		return _q;
	};

	this.connect();

};


text:
package com.consol.citrus.ssh.server;

import com.consol.citrus.exceptions.CitrusRuntimeException;
import org.apache.sshd.common.util.io.IoUtils;
import org.apache.sshd.common.util.SecurityUtils;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.springframework.util.FileCopyUtils;
import org.testng.annotations.Test;

import java.io.*;
import java.security.PublicKey;

import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

/**
 * @author Roland Huss
 * @since 05.09.12
 */
public class SinglePublicKeyAuthenticatorTest {

    /**
     * Default constructor.
     */
    public SinglePublicKeyAuthenticatorTest() {
        assertTrue(SecurityUtils.isBouncyCastleRegistered());
    }

    @Test
    public void withClassPath() throws IOException {
        SinglePublicKeyAuthenticator auth = new SinglePublicKeyAuthenticator("roland","classpath:com/consol/citrus/ssh/allowed_test_key.pem");
        PublicKey pKey = getPublicKey("/com/consol/citrus/ssh/allowed_test_key.pem");
        assertTrue(auth.authenticate("roland", pKey, null));
        assertFalse(auth.authenticate("guenther", pKey, null));

        pKey = getPublicKey("/com/consol/citrus/ssh/forbidden_test_key.pem");
        assertFalse(auth.authenticate("roland", pKey, null));

        pKey = getPublicKey("/com/consol/citrus/ssh/citrus.pem");
        assertFalse(auth.authenticate("citrus", pKey, null));
    }

    @Test
    public void withFile() throws IOException {
        File temp = copyToTempFile("/com/consol/citrus/ssh/allowed_test_key.pem");
        SinglePublicKeyAuthenticator auth = new SinglePublicKeyAuthenticator("roland",temp.getAbsolutePath());
        PublicKey pKey = getPublicKeyFromStream(new FileInputStream(temp));
        assertTrue(auth.authenticate("roland", pKey, null));
        assertFalse(auth.authenticate("guenther",pKey,null));

        temp = copyToTempFile("/com/consol/citrus/ssh/forbidden_test_key.pem");
        pKey = getPublicKeyFromStream(new FileInputStream(temp));
        assertFalse(auth.authenticate("roland", pKey, null));
    }

    @Test(expectedExceptions = CitrusRuntimeException.class, expectedExceptionsMessageRegExp = ".*com/consol/citrus/ssh/private.key.*")
    public void invalidKeyFormat() {
        new SinglePublicKeyAuthenticator("roland", "classpath:com/consol/citrus/ssh/private.key");
    }

    @Test(expectedExceptions = CitrusRuntimeException.class, expectedExceptionsMessageRegExp = ".*blubber\\.bla.*")
    public void notInClasspath() {
        new SinglePublicKeyAuthenticator("roland", "classpath:com/consol/citrus/ssh/blubber.bla");
    }

    @Test(expectedExceptions = CitrusRuntimeException.class,expectedExceptionsMessageRegExp = ".*/no/valid/path.*")
    public void invalidFilePath() {
        new SinglePublicKeyAuthenticator("roland","/no/valid/path");
    }

    /**
     * Gets public key instance from resource.
     * @param pResource
     * @return
     * @throws IOException
     */
    private PublicKey getPublicKey(String pResource) throws IOException {
        return getPublicKeyFromStream(getClass().getResourceAsStream(pResource));
    }

    /**
     * Creates new temporary file from resource.
     * @param pResource
     * @return
     * @throws IOException
     */
    private File copyToTempFile(String pResource) throws IOException {
        File temp = File.createTempFile("citrus-ssh-test", "pem");
        FileCopyUtils.copy(getClass().getResourceAsStream(pResource),
                           new FileOutputStream(temp));
        return temp;
    }

    /**
     * Create public key instance from file input stream.
     * @param is
     * @return
     * @throws IOException
     */
    private PublicKey getPublicKeyFromStream(InputStream is) throws IOException {
        Reader reader = new InputStreamReader(is);
        try {
            Object o = new PEMParser(reader).readObject();
            if (o instanceof PEMKeyPair) {
                return new BouncyCastleProvider().getPublicKey(((PEMKeyPair) o).getPublicKeyInfo());
            } else if (o instanceof SubjectPublicKeyInfo) {
                return new BouncyCastleProvider().getPublicKey((SubjectPublicKeyInfo) o);
            } else {
                throw new CitrusRuntimeException("Unable to read public key");
            }
        } catch (IOException e) {
            throw new CitrusRuntimeException("Failed to read public key", e);
        } finally {
            IoUtils.closeQuietly(is, reader);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<scriptmodule xmlns="http://xlt.xceptance.com/xlt-script/2" version="6">
  <description>Click login in header.</description>
  <command name="clickAndWait" target="css=.user-info.active .user-panel .user-links a:first-of-type"/>
  <command name="pause" value="500">
    <comment>Needed because Analytics is delayed by 100ms. If we are faster than that, we miss the call and get problems with the cookies that are changed during login/logout.</comment>
  </command>
</scriptmodule>


text:
Register:

<form id="register-form" action="http://www.picture-this-app.com/users" method="post">
  <input type="text" name="first_name" placeholder="first name">

  <input type="text" name="last_name" placeholder="last name">

  <input type="tel" name="phone" pattern='d{10}' placeholder="10-digit phone number">

  <input type="email" name="email" placeholder="email">

  <input type="password" name="password" placeholder="password">

  <input id="register-submit" class="submit" type="submit" value="Register">
</form>

<button id="button-to-login" type="button">Login</button>


text:
package petClinics;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Map<String, Clinic<Room>> clinics = new HashMap<>();
        Map<String, Pet> pets = new HashMap<>();
        int count = Integer.parseInt(br.readLine());

        for (int i = 0; i < count; i++) {
            String[] tokens = br.readLine().split("\\s+");
            String command = tokens[0];

            switch (command.toLowerCase()) {
                case "create":
                    if ("clinic".equalsIgnoreCase(tokens[1])) {
                        try {
                            Clinic<Room> clinic = new ClinicImpl<>(tokens[2], Integer.parseInt(tokens[3]));
                            clinics.putIfAbsent(tokens[2], clinic);
                        } catch (IllegalArgumentException iae) {
                            System.out.println(iae.getMessage());
                        }
                    } else if ("pet".equalsIgnoreCase(tokens[1])) {
                        Pet pet = new PetImpl(tokens[2], Integer.parseInt(tokens[3]), tokens[4]);
                        pets.putIfAbsent(tokens[2], pet);
                    } else {
                        System.out.println("No such command.");
                    }
                    break;
                case "hasemptyrooms":
                    if (clinics.containsKey(tokens[1])) {
                        System.out.println(clinics.get(tokens[1]).hasEmptyRooms());
                    }
                    break;
                case "release":
                    if (clinics.containsKey(tokens[1])) {
                        System.out.println(clinics.get(tokens[1]).release());
                    }
                    break;
                case "add":
                    if (pets.containsKey(tokens[1])) {
                        Pet pet = pets.get(tokens[1]);
                        if (clinics.containsKey(tokens[2])) {
                            Clinic<Room> clinic = clinics.get(tokens[2]);
                            System.out.println(clinic.addPet(pet));
                        }
                    } else {
                        System.out.println("Invalid Operation!");
                    }
                    break;
                case "print":
                    if (tokens.length == 2) {
                        if (clinics.containsKey(tokens[1])) {
                            Clinic<Room> clinic = clinics.get(tokens[1]);
                            StringBuilder sb = new StringBuilder();
                            for (Room room : clinic) {
                                sb.append(room == null ? "Room empty" : room.toString());
                                sb.append(System.lineSeparator());
                            }
                            System.out.println(sb.toString().trim());
                        }
                    } else if (tokens.length == 3) {
                        if (clinics.containsKey(tokens[1])) {
                            clinics.get(tokens[1]).print(Integer.parseInt(tokens[2]));
                        }
                    } else {
                        System.out.println("No such command.");
                    }
                    break;
            }
        }

        System.out.println();
    }
}


text:
'use strict'

module.exports = (typeof self === 'object' && self.self === self && self) ||
  (typeof global === 'object' && global.global === global && global) ||
  this


text:
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :authenticate_user
  before_filter :increase_traffic_counter

  TRAFFIC_DECREMENTER = 0.15

  TAG_FILTER_COOKIE = :tag_filters

  def authenticate_user
    if session[:u]
      @user = User.find_by_session_token(session[:u].to_s)
    end

    true
  end

  def increase_traffic_counter
    @traffic = 1.0

    if user_is_spider? || [ "json", "rss" ].include?(params[:format])
      return true
    end

    Keystore.transaction do
      date = (Keystore.value_for("traffic:date") || Time.now.to_i)
      traffic = (Keystore.incremented_value_for("traffic:hits", 0).
        to_f / 100.0) + 1.0

      # every second, decrement traffic by some amount
      @traffic = [ 1.0, traffic.to_f -
        ((Time.now.to_i - date) * TRAFFIC_DECREMENTER) ].max

      Keystore.put("traffic:date", Time.now.to_i)
      Keystore.put("traffic:hits", (@traffic * 100.0).to_i)
    end

    Rails.logger.info "  Traffic level: #{@traffic}"

    true
  end

  def require_logged_in_user
    if @user
      true
    else
      redirect_to "/login"
    end
  end

  def require_logged_in_user_or_400
    if @user
      true
    else
      render :text => "not logged in", :status => 400
      return false
    end
  end

  @_tags_filtered = nil
  def tags_filtered_by_cookie
    @_tags_filtered ||= cookies[TAG_FILTER_COOKIE].to_s.split(",").map{|t|
      Tag.find_by_tag(t) }.reject{|tf| !tf }
  end

  def user_is_spider?
    !!request.env["HTTP_USER_AGENT"].to_s.match(/Googlebot/)
  end

  def find_user_from_rss_token
    if !@user && request[:format] == "rss" && params[:token].to_s.present?
      @user = User.find_by_rss_token(params[:token].to_s)
    end
  end
end


text:
package com.javarush.task.task33.task3307;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.IOException;
import java.io.StringReader;

/*
Десериализация XML объекта

В метод convertFromXmlToNormal первым параметром приходит строка, содержащая xml объект.
Вторым параметром приходит класс, объект которого необходимо вернуть.
Метод convertFromXmlToNormal должен создать объект из xml-строки и вернуть его.

Требования:
1. В методе convertFromXmlToNormal должен быть создан новый объект типа JAXBContext с помощью статического метода JAXBContext.newInstance, в качестве параметра используй целевой класс.
2. В методе convertFromXmlToNormal должен быть создан новый объект типа Unmarshaller с помощью метода createUnmarshaller вызванного на объекте типа JAXBContext.
3. Метод convertFromXmlToNormal должен корректно преобразовывать входящую xml строку в объект требуемого класса.
4. Метод convertFromXmlToNormal должен быть статическим.
*/
public class Solution {
    public static void main(String[] args) throws IOException, JAXBException {
        String xmlData = "<cat><name>Murka</name><age>5</age><weight>4</weight></cat>";
        Cat cat = convertFromXmlToNormal(xmlData, Cat.class);
        System.out.println(cat);
    }

    public static <T> T convertFromXmlToNormal(String xmlData, Class<T> clazz) throws IOException, JAXBException {
        StringReader reader = new StringReader(xmlData);

        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        return (T) unmarshaller.unmarshal(reader);
    }

    @XmlType(name = "cat")
    @XmlRootElement
    public static class Cat {
        public String name;
        public int age;
        public int weight;

        @Override
        public String toString() {
            return "Cat{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", weight=" + weight +
                    '}';
        }
    }
}


text:
/*
A simple library that allows you to interface with a REST API compatible with
Hive Home smart devices.
*/
package hive

import (
	"encoding/json"
	"errors"
	"path"
	"strings"
)

const (
	refreshDevicesTarget = "products?after="
	deviceTarget         = "nodes"
)

var (
	// Returned when the login fails due to the server not returning a valid token.
	ErrNoToken = errors.New("no token returned from server")

	// Returned when the login fails to the server not returning an endpoint.
	ErrNoEndpoint = errors.New("no endpoint URL returned from server")
)

type endpoint interface {
	PostJSON(url string, jsonStr []byte, token string) ([]byte, error)
	Get(url string, token string) ([]byte, error)
}

// Client is the main object used to obtain credentials and interface with the
// REST API.
type Client struct {
	// Token represents an authentication token used for all calls to the API.
	Token string

	// EndpointURL is the URL to the given API endpoint all calls will be sent to.
	EndpointURL string

	client  endpoint
	devices map[string]*Device
}

// NewClient returns a new client that's ready to use the Login method or use
// a saved token.
func NewClient() *Client {
	return &Client{client: &httpClient{}}
}

// Login uses the given credentials object to authenticate and obtain a token
// and an endpoint URL. It will also load the initial list of devices.
func (c *Client) Login(creds *Credentials) error {
	credsJSON, err := creds.toJSON(false, true)
	if err != nil {
		return err
	}
	resp, err := c.client.PostJSON(creds.URL, credsJSON, "")
	if err != nil {
		return err
	}
	auth, err := parseSession(resp)
	if err != nil {
		return err
	}

	c.Token = auth.Token
	c.EndpointURL = trailingSlash(auth.Platform.Endpoint)

	c.parseDevices(auth.Products)
	return nil
}

// RefreshDevices updates the devices available and their current states.
func (c *Client) RefreshDevices() error {
	url := c.buildURL(refreshDevicesTarget)
	resp, err := c.client.Get(url, c.Token)
	if err != nil {
		return err
	}

	var devices []jsonEntity
	if err := json.Unmarshal(resp, &devices); err != nil {
		return err
	}

	c.parseDevices(devices)
	return nil
}

// Device returns the device with the given ID or null if no such device could
// be found.
func (c *Client) Device(id string) *Device {
	if c.devices == nil {
		return nil
	}
	return c.devices[id]
}

// Devices returns a slice with all the devices present.
func (c *Client) Devices() []*Device {
	if c.devices == nil {
		return nil
	}

	result := make([]*Device, 0, len(c.devices))
	for _, device := range c.devices {
		result = append(result, device)
	}
	return result
}

func (c *Client) parseDevices(devices []jsonEntity) {
	if c.devices == nil {
		c.devices = make(map[string]*Device, len(devices))
	}

	for i := range devices {
		id := devices[i].ID
		device := c.Device(id)
		if device != nil {
			device.entity = &devices[i]
		} else {
			c.devices[id] = &Device{
				entity: &devices[i],
				client: c,
			}
		}
	}
}

func (c *Client) modifyDeviceState(device *Device, state *jsonState) error {
	data, err := json.Marshal(state)
	if err != nil {
		return err
	}

	url := c.buildURL(deviceTarget, device.Type(), device.ID())
	_, err = c.client.PostJSON(url, data, c.Token)
	return err
}

func (c *Client) buildURL(params ...string) string {
	return c.EndpointURL + path.Join(params...)
}

// Credentials contains the user's username, password and URL used to perform
// the login operation.
type Credentials struct {
	Username string
	Password string
	URL      string
}

var (
	// Returned when the Credentials object contains no username.
	ErrCredsNoUsername = errors.New("no username specified")

	// Returned when the Credentials object contains no password.
	ErrCredsNoPassword = errors.New("no password specified")

	// Returned when the Credentials object contains no URL.
	ErrCredsNoURL = errors.New("no URL specified")
)

func (c *Credentials) toJSON(getDevices bool, getProducts bool) ([]byte, error) {
	if c.Username == "" {
		return nil, ErrCredsNoUsername
	}
	if c.Password == "" {
		return nil, ErrCredsNoPassword
	}
	if c.URL == "" {
		return nil, ErrCredsNoURL
	}

	jsonObj := jsonLogin{
		Username: c.Username,
		Password: c.Password,
		Devices:  getDevices,
		Products: getProducts,
	}

	return json.Marshal(jsonObj)
}

func parseSession(data []byte) (*jsonSession, error) {
	var session jsonSession
	err := json.Unmarshal(data, &session)
	if err != nil {
		return nil, err
	}

	if session.Token == "" {
		return nil, ErrNoToken
	}
	if session.Platform.Endpoint == "" {
		return nil, ErrNoEndpoint
	}

	return &session, nil
}

func trailingSlash(input string) string {
	return strings.TrimRight(input, "/") + "/"
}


text:
// Copyright (c) 2004-2013 Sergey Lyubka
// Copyright (c) 2013-2014 Cesanta Software Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#undef UNICODE                    // Use ANSI WinAPI functions
#undef _UNICODE                   // Use multibyte encoding on Windows
#define _MBCS                     // Use multibyte encoding on Windows
#define _WIN32_WINNT 0x500        // Enable MIIM_BITMAP
#define _CRT_SECURE_NO_WARNINGS   // Disable deprecation warning in VS2005
#define _XOPEN_SOURCE 600         // For PATH_MAX on linux
#undef WIN32_LEAN_AND_MEAN        // Let windows.h always include winsock2.h

#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <stdarg.h>
#include <ctype.h>
#include <time.h>

#include "mongoose.h"

#ifdef _WIN32
#include <windows.h>
#include <direct.h>  // For chdir()
#include <winsvc.h>
#include <shlobj.h>

#ifndef PATH_MAX
#define PATH_MAX MAX_PATH
#endif

#ifndef S_ISDIR
#define S_ISDIR(x) ((x) & _S_IFDIR)
#endif

#define DIRSEP '\\'
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define sleep(x) Sleep((x) * 1000)
#define abs_path(rel, abs, abs_size) _fullpath((abs), (rel), (abs_size))
#define SIGCHLD 0
typedef struct _stat file_stat_t;
#define stat(x, y) _stat((x), (y))
#else
typedef struct stat file_stat_t;
#include <sys/wait.h>
#include <unistd.h>

#ifdef IOS
#include <ifaddrs.h>
#endif

#define DIRSEP '/'
#define __cdecl
#define abs_path(rel, abs, abs_size) realpath((rel), (abs))
#endif // _WIN32

#define MAX_OPTIONS 100
#define MAX_CONF_FILE_LINE_SIZE (8 * 1024)

#ifndef MVER
#define MVER MONGOOSE_VERSION
#endif

static int exit_flag;
static char server_name[50];        // Set by init_server_name()
static char s_config_file[PATH_MAX];  // Set by process_command_line_arguments
static struct mg_server *server;    // Set by start_mongoose()
static const char *s_default_document_root = ".";
static const char *s_default_listening_port = "8080";
static char **s_argv = { NULL };

static void set_options(char *argv[]);

#if !defined(CONFIG_FILE)
#define CONFIG_FILE "mongoose.conf"
#endif /* !CONFIG_FILE */

static void __cdecl signal_handler(int sig_num) {
  // Reinstantiate signal handler
  signal(sig_num, signal_handler);

#ifndef _WIN32
  // Do not do the trick with ignoring SIGCHLD, cause not all OSes (e.g. QNX)
  // reap zombies if SIGCHLD is ignored. On QNX, for example, waitpid()
  // fails if SIGCHLD is ignored, making system() non-functional.
  if (sig_num == SIGCHLD) {
    do {} while (waitpid(-1, &sig_num, WNOHANG) > 0);
  } else
#endif
  { exit_flag = sig_num; }
}

static void vnotify(const char *fmt, va_list ap, int must_exit) {
  char msg[200];

  vsnprintf(msg, sizeof(msg), fmt, ap);
  fprintf(stderr, "%s\n", msg);

  if (must_exit) {
    exit(EXIT_FAILURE);
  }
}

static void notify(const char *fmt, ...) {
  va_list ap;
  va_start(ap, fmt);
  vnotify(fmt, ap, 0);
  va_end(ap);
}

static void die(const char *fmt, ...) {
  va_list ap;
  va_start(ap, fmt);
  vnotify(fmt, ap, 1);
  va_end(ap);
}

static void show_usage_and_exit(void) {
  const char **names;
  int i;

  fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka, built on %s\n",
          MVER, __DATE__);
  fprintf(stderr, "Usage:\n");
#ifndef MONGOOSE_NO_AUTH
  fprintf(stderr, "  mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
#endif
  fprintf(stderr, "  mongoose [config_file]\n");
  fprintf(stderr, "  mongoose [-option value ...]\n");
  fprintf(stderr, "\nOPTIONS:\n");

  names = mg_get_valid_option_names();
  for (i = 0; names[i] != NULL; i += 2) {
    fprintf(stderr, "  -%s %s\n",
            names[i], names[i + 1] == NULL ? "<empty>" : names[i + 1]);
  }
  exit(EXIT_FAILURE);
}

#define EV_HANDLER NULL

static char *sdup(const char *str) {
  char *p;
  if ((p = (char *) malloc(strlen(str) + 1)) != NULL) {
    strcpy(p, str);
  }
  return p;
}

static void set_option(char **options, const char *name, const char *value) {
  int i;

  for (i = 0; i < MAX_OPTIONS - 3; i++) {
    if (options[i] == NULL) {
      options[i] = sdup(name);
      options[i + 1] = sdup(value);
      options[i + 2] = NULL;
      break;
    } else if (!strcmp(options[i], name)) {
      free(options[i + 1]);
      options[i + 1] = sdup(value);
      break;
    }
  }

  if (i == MAX_OPTIONS - 3) {
    die("%s", "Too many options specified");
  }
}

static void process_command_line_arguments(char *argv[], char **options) {
  char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)],
       *p, cpath[PATH_MAX];
  FILE *fp = NULL;
  size_t i, cmd_line_opts_start = 1, line_no = 0;

  // Should we use a config file ?
  if (argv[1] != NULL && argv[1][0] != '-') {
    snprintf(cpath, sizeof(cpath), "%s", argv[1]);
    cmd_line_opts_start = 2;
  } else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
    // No command line flags specified. Look where binary lives
    snprintf(cpath, sizeof(cpath), "%s", CONFIG_FILE);
  } else {
    snprintf(cpath, sizeof(cpath), "%.*s%c%s",
             (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
  }
  abs_path(cpath, s_config_file, sizeof(s_config_file));

  fp = fopen(s_config_file, "r");

  // If config file was set in command line and open failed, die
  if (cmd_line_opts_start == 2 && fp == NULL) {
    die("Cannot open config file %s: %s", s_config_file, strerror(errno));
  }

  // Load config file settings first
  if (fp != NULL) {
    fprintf(stderr, "Loading config file %s\n", s_config_file);

    // Loop over the lines in config file
    while (fgets(line, sizeof(line), fp) != NULL) {
      line_no++;

      // Ignore empty lines and comments
      for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++;
      if (line[i] == '#' || line[i] == '\0') {
        continue;
      }

      if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {
        printf("%s: line %d is invalid, ignoring it:\n %s",
               s_config_file, (int) line_no, line);
      } else {
        set_option(options, opt, val);
      }
    }

    fclose(fp);
  }

  // If we're under MacOS and started by launchd, then the second
  // argument is process serial number, -psn_.....
  // In this case, don't process arguments at all.
  if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {
    // Handle command line flags.
    // They override config file and default settings.
    for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
      if (argv[i][0] != '-' || argv[i + 1] == NULL) {
        show_usage_and_exit();
      }
      set_option(options, &argv[i][1], argv[i + 1]);
    }
  }
}

static void init_server_name(void) {
  const char *descr = "";
  snprintf(server_name, sizeof(server_name), "Mongoose web server v.%s%s",
           MVER, descr);
}

static int is_path_absolute(const char *path) {
#ifdef _WIN32
  return path != NULL &&
    ((path[0] == '\\' && path[1] == '\\') ||  // UNC path, e.g. \\server\dir
     (isalpha(path[0]) && path[1] == ':' && path[2] == '\\'));  // E.g. X:\dir
#else
  return path != NULL && path[0] == '/';
#endif
}

static char *get_option(char **options, const char *option_name) {
  int i;

  for (i = 0; options[i] != NULL; i++)
    if (!strcmp(options[i], option_name))
      return options[i + 1];

  return NULL;
}

static void *serving_thread_func(void *param) {
  struct mg_server *srv = (struct mg_server *) param;
  while (exit_flag == 0) {
    mg_poll_server(srv, 1000);
  }
  return NULL;
}

static int path_exists(const char *path, int is_dir) {
  file_stat_t st;
  return path == NULL || (stat(path, &st) == 0 &&
                          ((S_ISDIR(st.st_mode) ? 1 : 0) == is_dir));
}

static void verify_existence(char **options, const char *name, int is_dir) {
  const char *path = get_option(options, name);
  if (!path_exists(path, is_dir)) {
    notify("Invalid path for %s: [%s]: (%s). Make sure that path is either "
           "absolute, or it is relative to mongoose executable.",
           name, path, strerror(errno));
  }
}

static void set_absolute_path(char *options[], const char *option_name) {
  char path[PATH_MAX], abs[PATH_MAX], *option_value;
  const char *p;

  // Check whether option is already set
  option_value = get_option(options, option_name);

  // If option is already set and it is an absolute path,
  // leave it as it is -- it's already absolute.
  if (option_value != NULL && !is_path_absolute(option_value)) {
    // Not absolute. Use the directory where mongoose executable lives
    // be the relative directory for everything.
    // Extract mongoose executable directory into path.
    if ((p = strrchr(s_config_file, DIRSEP)) == NULL) {
      getcwd(path, sizeof(path));
    } else {
      snprintf(path, sizeof(path), "%.*s", (int) (p - s_config_file),
               s_config_file);
    }

    strncat(path, "/", sizeof(path) - 1);
    strncat(path, option_value, sizeof(path) - 1);

    // Absolutize the path, and set the option
    abs_path(path, abs, sizeof(abs));
    set_option(options, option_name, abs);
  }
}

#ifndef MONGOOSE_NO_AUTH
int modify_passwords_file(const char *fname, const char *domain,
                          const char *user, const char *pass) {
  int found;
  char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];
  FILE *fp, *fp2;

  found = 0;
  fp = fp2 = NULL;

  // Regard empty password as no password - remove user record.
  if (pass != NULL && pass[0] == '\0') {
    pass = NULL;
  }

  (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);

  // Create the file if does not exist
  if ((fp = fopen(fname, "a+")) != NULL) {
    fclose(fp);
  }

  // Open the given file and temporary file
  if ((fp = fopen(fname, "r")) == NULL) {
    return 0;
  } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
    fclose(fp);
    return 0;
  }

  // Copy the stuff to temporary file
  while (fgets(line, sizeof(line), fp) != NULL) {
    if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
      continue;
    }

    if (!strcmp(u, user) && !strcmp(d, domain)) {
      found++;
      if (pass != NULL) {
        mg_md5(ha1, user, ":", domain, ":", pass, NULL);
        fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
      }
    } else {
      fprintf(fp2, "%s", line);
    }
  }

  // If new user, just add it
  if (!found && pass != NULL) {
    mg_md5(ha1, user, ":", domain, ":", pass, NULL);
    fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  }

  // Close files
  fclose(fp);
  fclose(fp2);

  // Put the temp file in place of real file
  remove(fname);
  rename(tmp, fname);

  return 1;
}
#endif

static void start_mongoose(int argc, char *argv[]) {
  s_argv = argv;
  if ((server = mg_create_server(NULL, EV_HANDLER)) == NULL) {
    die("%s", "Failed to start Mongoose.");
  }

#ifndef MONGOOSE_NO_AUTH
  // Edit passwords file if -A option is specified
  if (argc > 1 && !strcmp(argv[1], "-A")) {
    if (argc != 6) {
      show_usage_and_exit();
    }
    exit(modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?
         EXIT_SUCCESS : EXIT_FAILURE);
  }
#endif

  // Show usage if -h or --help options are specified
  if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
    show_usage_and_exit();
  }
  set_options(argv);
}

static void set_options(char *argv[]) {
  char *options[MAX_OPTIONS];
  int i;

  options[0] = NULL;
  set_option(options, "document_root", s_default_document_root);
  set_option(options, "listening_port", s_default_listening_port);

  // Update config based on command line arguments
  process_command_line_arguments(argv, options);

  // Make sure we have absolute paths for files and directories
  // https://github.com/valenok/mongoose/issues/181
  set_absolute_path(options, "document_root");
  set_absolute_path(options, "dav_auth_file");
  set_absolute_path(options, "cgi_interpreter");
  set_absolute_path(options, "access_log_file");
  set_absolute_path(options, "global_auth_file");
  set_absolute_path(options, "ssl_certificate");

  if (!path_exists(get_option(options, "document_root"), 1)) {
    set_option(options, "document_root", s_default_document_root);
    set_absolute_path(options, "document_root");
    notify("Setting document_root to [%s]",
           mg_get_option(server, "document_root"));
  }

  // Make extra verification for certain options
  verify_existence(options, "document_root", 1);
  verify_existence(options, "cgi_interpreter", 0);
  verify_existence(options, "ssl_certificate", 0);

  for (i = 0; options[i] != NULL; i += 2) {
    const char *msg = mg_set_option(server, options[i], options[i + 1]);
    if (msg != NULL) {
      notify("Failed to set option [%s] to [%s]: %s",
             options[i], options[i + 1], msg);
      if (!strcmp(options[i], "listening_port")) {
        mg_set_option(server, "listening_port", s_default_listening_port);
        notify("Setting %s to [%s]", options[i], s_default_listening_port);
      }
    }
    free(options[i]);
    free(options[i + 1]);
  }

  // Change current working directory to document root. This way,
  // scripts can use relative paths.
  chdir(mg_get_option(server, "document_root"));

  // Add an ability to pass listening socket to mongoose
  {
    const char *env = getenv("MONGOOSE_LISTENING_SOCKET");
    if (env != NULL && atoi(env) > 0 ) {
      mg_set_listening_socket(server, atoi(env));
    }
  }

  // Setup signal handler: quit on Ctrl-C
  signal(SIGTERM, signal_handler);
  signal(SIGINT, signal_handler);
#ifndef _WIN32
  signal(SIGCHLD, signal_handler);
#endif
}

int main(int argc, char *argv[]) {
  init_server_name();
  start_mongoose(argc, argv);
  printf("%s serving [%s] on port %s\n",
         server_name, mg_get_option(server, "document_root"),
         mg_get_option(server, "listening_port"));
  fflush(stdout);  // Needed, Windows terminals might not be line-buffered
  serving_thread_func(server);
  printf("Exiting on signal %d ...", exit_flag);
  fflush(stdout);
  mg_destroy_server(&server);
  printf("%s\n", " done.");

  return EXIT_SUCCESS;
}