text:
require 'concurrent'

module Hanami
  module Model
    # Default Error class
    #
    # @since 0.5.1
    class Error < ::StandardError
      # @api private
      # @since 0.7.0
      @__mapping__ = Concurrent::Map.new

      # @api private
      # @since 0.7.0
      def self.for(exception)
        mapping.fetch(exception.class, self).new(exception)
      end

      # @api private
      # @since 0.7.0
      def self.register(external, internal)
        mapping.put_if_absent(external, internal)
      end

      # @api private
      # @since 0.7.0
      def self.mapping
        @__mapping__
      end
    end

    # Generic database error
    #
    # @since 0.7.0
    class DatabaseError < Error
    end

    # Error for invalid raw command syntax
    #
    # @since 0.5.0
    class InvalidCommandError < Error
      # @since 0.5.0
      # @api private
      def initialize(message = 'Invalid command')
        super
      end
    end

    # Error for Constraint Violation
    #
    # @since 0.7.0
    class ConstraintViolationError < Error
      # @since 0.7.0
      # @api private
      def initialize(message = 'Constraint has been violated')
        super
      end
    end

    # Error for Unique Constraint Violation
    #
    # @since 0.6.1
    class UniqueConstraintViolationError < Error
      # @since 0.6.1
      # @api private
      def initialize(message = 'Unique constraint has been violated')
        super
      end
    end

    # Error for Foreign Key Constraint Violation
    #
    # @since 0.6.1
    class ForeignKeyConstraintViolationError < Error
      # @since 0.6.1
      # @api private
      def initialize(message = 'Foreign key constraint has been violated')
        super
      end
    end

    # Error for Not Null Constraint Violation
    #
    # @since 0.6.1
    class NotNullConstraintViolationError < Error
      # @since 0.6.1
      # @api private
      def initialize(message = 'NOT NULL constraint has been violated')
        super
      end
    end

    # Error for Check Constraint Violation raised by Sequel
    #
    # @since 0.6.1
    class CheckConstraintViolationError < Error
      # @since 0.6.1
      # @api private
      def initialize(message = 'Check constraint has been violated')
        super
      end
    end

    # Unknown database type error for repository auto-mapping
    #
    # @since 1.0.0
    class UnknownDatabaseTypeError < Error
    end

    # Unknown primary key error
    #
    # @since 1.0.0
    class MissingPrimaryKeyError < Error
    end
  end
end


text:
import argparse
import numpy
import math

parser = argparse.ArgumentParser(description='Script to find comparisons done by quicksort')
parser.add_argument('input_file', type=str, help='Input file containing array')
parser.add_argument('--pivot_method', type=int, default=1,
                    help='Pivot selection technique. 1 (default) - First element, 2 - Last element, 3 - Median of three')
args = parser.parse_args()

def find_median(arr, left, right):
    if right - left < 2:
        return left

    mid = (left + right) / 2
    temp = [arr[left], arr[mid], arr[right]]
    median = int(numpy.median(temp))
    pos = temp.index(median)

    if pos == 1:
        return mid
    elif pos == 2:
        return right
    else: return left

def choose_pivot(arr, left, right, method):
    if method == 1:
        return left
    elif method == 2:
        return right
    elif method == 3: # return median of first, last and mid
        return find_median(arr, left, right)
    else:
        raise Exception("Invalid pivot selection mode!")

def partition(arr, left, right, pivot):
    if arr[pivot] != arr[left]: # if pivot is not the first element, swap
        arr[left], arr[pivot] = arr[pivot], arr[left]

    i = left + 1 #initialize i = 1

    for j in range(i, right + 1):
        if arr[j] < arr[left]:
            arr[j], arr[i] = arr[i], arr[j]
            i += 1

    # partition complete, swap pivot and i - 1
    arr[left], arr[i-1] = arr[i-1], arr[left]
    return i - 1

def q_sort(arr, left, right, pivot_method):
    num_comparisons = 0

    if left < right:
        pivot = choose_pivot(arr, left, right, pivot_method)
        pivot_pos = partition(arr, left, right, pivot)
        num_comparisons += right - left

        num_comparisons += q_sort(arr, left, pivot_pos - 1, pivot_method)
        num_comparisons += q_sort(arr, pivot_pos + 1, right, pivot_method)

    return num_comparisons
# load text file
arr = numpy.loadtxt(args.input_file, int)
# print 'Total number of inversions in the given dataset = ' + str(count_inversions(arr)[1])
#
# arr = [8, 2]
# p = choose_pivot(arr, 0, 1, 3)
# print p

# print (arr)

# # partition(arr, 0, 6, 0)
n = q_sort(arr, 0, len(arr) - 1, args.pivot_method)

print (n)
#
with open('output.txt', 'w') as file:
    for item in arr:
            file.write("{}\n".format(item))

# partition(arr, 0, 6, 0)
# # q_sort(arr, 0, len(arr) - 1)
# print (arr)

redpajama_set_name: RedPajamaGithub


text:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:elevation="7dp">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/content_frame">
    </FrameLayout>

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="@dimen/nav_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/holo_red_dark"
        android:choiceMode="singleChoice"
        android:divider="@color/textLabel"
        android:dividerHeight="1dp" />

</android.support.v4.widget.DrawerLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<object name="element_instance">
    <properties>
        <property
            name="id"
            type="integer"
            unsigned="1"
            notnull="1"
            autoincrement="true" />
        <property
            name="schema_instance_id"
            unsigned="1"
            type="integer"
            notnull="1" />
        <property
            name="element_id"
            unsigned="1"
            type="integer"
            notnull="1" />
        <property
            name="vocabulary_id"
            unsigned="1"
            type="integer"
            notnull="1" />
    </properties>
    <index name="schema_instance_id">
        <indexproperty name="schema_instance_id" />
    </index>
    <index name="element_id">
        <indexproperty name="element_id" />
    </index>
    <index name="vocabulary_id">
        <indexproperty name="vocabulary_id" />
    </index>
</object>


text:
package com.sch.p1733;

/**
 * Created by Nov on 2015/5/15.
 */
public class LogContext {
    public void log(String msg){
        LogStrategy strategy = new DbLog();
        try{
            strategy.log(msg);
        }
        catch (Exception e){
            strategy = new FileLog();
            strategy.log(msg);
        }

    }
}


text:
namespace extensions {
namespace declarative_net_request {

// Parses the kDeclarativeNetRequestKey manifest key.
class DNRManifestHandler : public ManifestHandler {
 public:
  DNRManifestHandler();
  ~DNRManifestHandler() override;

 private:
  bool Parse(Extension* extension, base::string16* error) override;
  bool Validate(const Extension* extension,
                std::string* error,
                std::vector<InstallWarning>* warnings) const override;
  base::span<const char* const> Keys() const override;

  DISALLOW_COPY_AND_ASSIGN(DNRManifestHandler);
};

}  // namespace declarative_net_request
}  // namespace extensions

#endif  // EXTENSIONS_COMMON_API_DECLARATIVE_NET_REQUEST_DNR_MANIFEST_HANDLER_H_


text:
Web Sliding Puzzle
==================

Sliding Puzzle is a simple web app originally made during and for the Firefox OS
App days in Paris.

It should work fine most modern mobile and desktop browsers (except Opera
because its support File API is incomplete). It was tested on latest versions of
Firefox, Safari and Chrome on all platforms.

You can see it in action at this URL : http://sliding-puzzle.virgule.net/


text:
Instructions on configuring an embedded computer such as a Raspberry Pi or Odroid

### 1. [Raspberry Pi 4](https://github.com/westpoint-robotics/usma_embedded_computer/blob/master/rpi4.md)
### 2. [Raspberry Pi 3B/+](https://github.com/westpoint-robotics/usma_embedded_computer/blob/master/rpi3b.md) with Ubuntu MATE 18.04
### 3. [Raspberry Pi 3](https://github.com/westpoint-robotics/usma_embedded_computer/blob/master/rpi3.md)
### 4. [Odroid (Turtlebot)](https://github.com/westpoint-robotics/usma_embedded_computer/blob/master/odroid.md)
### 5. [Raspberry Pi 2](https://github.com/westpoint-robotics/usma_embedded_computer/blob/master/rpi2.md)

### Extras:
#### 1. [PixyCam](https://github.com/westpoint-robotics/usma_embedded_computer/blob/master/pixy.md)


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

<!DOCTYPE suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN" "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">

<suppressions>
    <suppress files=".*[\\/]Messages\.java" checks=".*"/>
    <suppress files=".*[\\/]Scope\.java" checks="JavadocVariable"/>
    <suppress files=".*\.vtl" checks=".*"/>
</suppressions>


text:
package com.budwk.app.web.controllers.platform.sys;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.budwk.app.base.result.Result;
import com.budwk.app.base.utils.PageUtil;
import com.budwk.app.sys.services.SysApiService;
import com.budwk.app.web.commons.auth.utils.SecurityUtil;
import com.budwk.app.web.commons.slog.annotation.SLog;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;

;

/**
 * Created by wizzer on 2016/6/24.
 */
@IocBean
@At("/platform/sys/api")
public class SysApiController {
    private static final Log log = Logs.get();
    @Inject
    private SysApiService sysApiService;

    @At("")
    @Ok("beetl:/platform/sys/api/index.html")
    @SaCheckPermission("sys.manager.api")
    public void index() {
    }

    @At
    @Ok("json")
    @SaCheckPermission("sys.manager.api.add")
    @SLog(tag = "新建密钥", msg = "应用名称:${name}")
    public Object addDo(@Param("name") String name, HttpServletRequest req) {
        try {
            sysApiService.createAppkey(name, SecurityUtil.getUserId());
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/delete/?")
    @Ok("json")
    @SaCheckPermission("sys.manager.api.delete")
    @SLog(tag = "删除密钥", msg = "Appid:${appid}")
    public Object delete(String appid, HttpServletRequest req) {
        try {
            sysApiService.deleteAppkey(appid);
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/enable/?")
    @Ok("json")
    @SaCheckPermission("sys.manager.api.edit")
    @SLog(tag = "启用密钥", msg = "Appid:${appid}")
    public Object enable(String appid, HttpServletRequest req) {
        try {
            sysApiService.updateAppkey(appid, false);
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At("/disable/?")
    @Ok("json")
    @SaCheckPermission("sys.manager.api.edit")
    @SLog(tag = "禁用密钥", msg = "Appid:${appid}")
    public Object disable(String appid, HttpServletRequest req) {
        try {
            sysApiService.updateAppkey(appid, true);
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }

    @At
    @Ok("json:full")
    @SaCheckPermission("sys.manager.api")
    public Object data(@Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        try {
            Cnd cnd = Cnd.NEW();
            if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
                cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
            }
            return Result.success().addData(sysApiService.listPage(pageNumber, pageSize, cnd));
        } catch (Exception e) {
            return Result.error();
        }
    }
}


text:
default: build

build:
	dune build @install

clean:
	dune clean

test:
	dune runtest

doc:
	dune build @doc
	cp -r _build/default/_doc/_html docs

.PHONY: default build clean test doc


text:
from django.core.management.base import CommandError

from devilry_subjectadminadd import AdminAddBase

class Command(AdminAddBase):
    args = '<subject-short_name>'
    help = 'Clear subject admins (removes all subject admins on a subject).'

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError('Subject is required. See --help.')
        short_name = args[0]
        subject = self.get_subject(short_name)
        subject.admins.clear()


text:
import React, { Component } from 'react';

import { Alert, Button, Col, Nav, NavItem, NavLink, Row, TabContent, TabPane } from 'reactstrap';

import moment from 'moment-timezone';

import ExpressionInput from './ExpressionInput';
import GraphControls from './GraphControls';
import { GraphTabContent } from './GraphTabContent';
import DataTable from './DataTable';
import TimeInput from './TimeInput';
import QueryStatsView, { QueryStats } from './QueryStatsView';
import { QueryParams, ExemplarData } from '../../types/types';
import { API_PATH } from '../../constants/constants';
import { debounce } from '../../utils';

interface PanelProps {
  options: PanelOptions;
  onOptionsChanged: (opts: PanelOptions) => void;
  useLocalTime: boolean;
  pastQueries: string[];
  metricNames: string[];
  removePanel: () => void;
  onExecuteQuery: (query: string) => void;
  pathPrefix: string;
  enableAutocomplete: boolean;
  enableHighlighting: boolean;
  enableLinter: boolean;
  id: string;
}

interface PanelState {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  data: any; // TODO: Type data.
  exemplars: ExemplarData;
  lastQueryParams: QueryParams | null;
  loading: boolean;
  warnings: string[] | null;
  error: string | null;
  stats: QueryStats | null;
  exprInputValue: string;
}

export interface PanelOptions {
  expr: string;
  type: PanelType;
  range: number; // Range in milliseconds.
  endTime: number | null; // Timestamp in milliseconds.
  resolution: number | null; // Resolution in seconds.
  stacked: boolean;
  showExemplars: boolean;
}

export enum PanelType {
  Graph = 'graph',
  Table = 'table',
}

export const PanelDefaultOptions: PanelOptions = {
  type: PanelType.Table,
  expr: '',
  range: 60 * 60 * 1000,
  endTime: null,
  resolution: null,
  stacked: false,
  showExemplars: false,
};

class Panel extends Component<PanelProps, PanelState> {
  private abortInFlightFetch: (() => void) | null = null;
  private debounceExecuteQuery: () => void;

  constructor(props: PanelProps) {
    super(props);

    this.state = {
      data: null,
      exemplars: [],
      lastQueryParams: null,
      loading: false,
      warnings: null,
      error: null,
      stats: null,
      exprInputValue: props.options.expr,
    };

    this.debounceExecuteQuery = debounce(this.executeQuery.bind(this), 250);
  }

  componentDidUpdate({ options: prevOpts }: PanelProps): void {
    const { endTime, range, resolution, showExemplars, type } = this.props.options;

    if (prevOpts.endTime !== endTime || prevOpts.range !== range) {
      this.debounceExecuteQuery();
      return;
    }

    if (prevOpts.resolution !== resolution || prevOpts.type !== type || showExemplars !== prevOpts.showExemplars) {
      this.executeQuery();
    }
  }

  componentDidMount(): void {
    this.executeQuery();
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  executeQuery = async (): Promise<any> => {
    const { exprInputValue: expr } = this.state;
    const queryStart = Date.now();
    this.props.onExecuteQuery(expr);
    if (this.props.options.expr !== expr) {
      this.setOptions({ expr });
    }
    if (expr === '') {
      return;
    }

    if (this.abortInFlightFetch) {
      this.abortInFlightFetch();
      this.abortInFlightFetch = null;
    }

    const abortController = new AbortController();
    this.abortInFlightFetch = () => abortController.abort();
    this.setState({ loading: true });

    const endTime = this.getEndTime().valueOf() / 1000; // TODO: shouldn't valueof only work when it's a moment?
    const startTime = endTime - this.props.options.range / 1000;
    const resolution = this.props.options.resolution || Math.max(Math.floor(this.props.options.range / 250000), 1);
    const params: URLSearchParams = new URLSearchParams({
      query: expr,
    });

    let path: string;
    switch (this.props.options.type) {
      case 'graph':
        path = 'query_range';
        params.append('start', startTime.toString());
        params.append('end', endTime.toString());
        params.append('step', resolution.toString());
        break;
      case 'table':
        path = 'query';
        params.append('time', endTime.toString());
        break;
      default:
        throw new Error('Invalid panel type "' + this.props.options.type + '"');
    }

    let query;
    let exemplars;
    try {
      query = await fetch(`${this.props.pathPrefix}/${API_PATH}/${path}?${params}`, {
        cache: 'no-store',
        credentials: 'same-origin',
        signal: abortController.signal,
      }).then((resp) => resp.json());

      if (query.status !== 'success') {
        throw new Error(query.error || 'invalid response JSON');
      }

      if (this.props.options.type === 'graph' && this.props.options.showExemplars) {
        params.delete('step'); // Not needed for this request.
        exemplars = await fetch(`${this.props.pathPrefix}/${API_PATH}/query_exemplars?${params}`, {
          cache: 'no-store',
          credentials: 'same-origin',
          signal: abortController.signal,
        }).then((resp) => resp.json());

        if (exemplars.status !== 'success') {
          throw new Error(exemplars.error || 'invalid response JSON');
        }
      }

      let resultSeries = 0;
      if (query.data) {
        const { resultType, result } = query.data;
        if (resultType === 'scalar') {
          resultSeries = 1;
        } else if (result && result.length > 0) {
          resultSeries = result.length;
        }
      }

      this.setState({
        error: null,
        data: query.data,
        exemplars: exemplars?.data,
        warnings: query.warnings,
        lastQueryParams: {
          startTime,
          endTime,
          resolution,
        },
        stats: {
          loadTime: Date.now() - queryStart,
          resolution,
          resultSeries,
        },
        loading: false,
      });
      this.abortInFlightFetch = null;
    } catch (err: unknown) {
      const error = err as Error;
      if (error.name === 'AbortError') {
        // Aborts are expected, don't show an error for them.
        return;
      }
      this.setState({
        error: 'Error executing query: ' + error.message,
        loading: false,
      });
    }
  };

  setOptions(opts: Partial<PanelOptions>): void {
    const newOpts = { ...this.props.options, ...opts };
    this.props.onOptionsChanged(newOpts);
  }

  handleExpressionChange = (expr: string): void => {
    this.setState({ exprInputValue: expr });
  };

  handleChangeRange = (range: number): void => {
    this.setOptions({ range: range });
  };

  getEndTime = (): number | moment.Moment => {
    if (this.props.options.endTime === null) {
      return moment();
    }
    return this.props.options.endTime;
  };

  handleChangeEndTime = (endTime: number | null): void => {
    this.setOptions({ endTime: endTime });
  };

  handleChangeResolution = (resolution: number | null): void => {
    this.setOptions({ resolution: resolution });
  };

  handleChangeType = (type: PanelType): void => {
    if (this.props.options.type === type) {
      return;
    }

    this.setState({ data: null });
    this.setOptions({ type: type });
  };

  handleChangeStacking = (stacked: boolean): void => {
    this.setOptions({ stacked: stacked });
  };

  handleChangeShowExemplars = (show: boolean): void => {
    this.setOptions({ showExemplars: show });
  };

  handleTimeRangeSelection = (startTime: number, endTime: number): void => {
    this.setOptions({ range: endTime - startTime, endTime: endTime });
  };

  render(): JSX.Element {
    const { pastQueries, metricNames, options } = this.props;
    return (

        <Row>
          <Col>
            <ExpressionInput
              value={this.state.exprInputValue}
              onExpressionChange={this.handleExpressionChange}
              executeQuery={this.executeQuery}
              loading={this.state.loading}
              enableAutocomplete={this.props.enableAutocomplete}
              enableHighlighting={this.props.enableHighlighting}
              enableLinter={this.props.enableLinter}
              queryHistory={pastQueries}
              metricNames={metricNames}
            />
          </Col>
        </Row>
        <Row>
          <Col>{this.state.error && <Alert color="danger">{this.state.error}</Alert>}</Col>
        </Row>
        {this.state.warnings?.map((warning, index) => (
          <Row key={index}>
            <Col>{warning && <Alert color="warning">{warning}</Alert>}</Col>
          </Row>
        ))}
        <Row>
          <Col>

              <NavItem>
                <NavLink
                  className={options.type === 'table' ? 'active' : ''}
                  onClick={() => this.handleChangeType(PanelType.Table)}
                >
                  Table
                </NavLink>
              </NavItem>
              <NavItem>
                <NavLink
                  className={options.type === 'graph' ? 'active' : ''}
                  onClick={() => this.handleChangeType(PanelType.Graph)}
                >
                  Graph
                </NavLink>
              </NavItem>
              {!this.state.loading && !this.state.error && this.state.stats && <QueryStatsView {...this.state.stats} />}

            <TabContent activeTab={options.type}>
              <TabPane tabId="table">
                {options.type === 'table' && (
                  <>

                      <TimeInput
                        time={options.endTime}
                        useLocalTime={this.props.useLocalTime}
                        range={options.range}
                        placeholder="Evaluation time"
                        onChangeTime={this.handleChangeEndTime}
                      />

                    <DataTable data={this.state.data} useLocalTime={this.props.useLocalTime} />
                  </>
                )}
              </TabPane>
              <TabPane tabId="graph">
                {this.props.options.type === 'graph' && (
                  <>
                    <GraphControls
                      range={options.range}
                      endTime={options.endTime}
                      useLocalTime={this.props.useLocalTime}
                      resolution={options.resolution}
                      stacked={options.stacked}
                      showExemplars={options.showExemplars}
                      onChangeRange={this.handleChangeRange}
                      onChangeEndTime={this.handleChangeEndTime}
                      onChangeResolution={this.handleChangeResolution}
                      onChangeStacking={this.handleChangeStacking}
                      onChangeShowExemplars={this.handleChangeShowExemplars}
                    />
                    <GraphTabContent
                      data={this.state.data}
                      exemplars={this.state.exemplars}
                      stacked={options.stacked}
                      useLocalTime={this.props.useLocalTime}
                      showExemplars={options.showExemplars}
                      lastQueryParams={this.state.lastQueryParams}
                      id={this.props.id}
                      handleTimeRangeSelection={this.handleTimeRangeSelection}
                    />
                  </>
                )}
              </TabPane>
            </TabContent>
          </Col>
        </Row>
        <Row>
          <Col>
            <Button className="float-right" color="link" onClick={this.props.removePanel} size="sm">
              Remove Panel
            </Button>
          </Col>
        </Row>

    );
  }
}

export default Panel;


text:
namespace task_manager {

// static
WebContentsTagsManager* WebContentsTagsManager::GetInstance() {
  return base::Singleton<WebContentsTagsManager>::get();
}

void WebContentsTagsManager::AddTag(WebContentsTag* tag) {
  DCHECK(tag);
  tracked_tags_.push_back(tag);

  if (provider_)
    provider_->OnWebContentsTagCreated(tag);
}

void WebContentsTagsManager::RemoveTag(WebContentsTag* tag) {
  DCHECK(tag);
  tracked_tags_.erase(base::ranges::find(tracked_tags_, tag));

  // No need to inform the provider here. The provider will create an entry
  // for each WebContents it's tracking which is a WebContentsObserver and
  // can be used to track the lifetime of the WebContents.

  // We must however make sure that the provider has already forgotten about the
  // tag and its associated web_contents.
  if (provider_)
    CHECK(!provider_->HasWebContents(tag->web_contents()));
}

void WebContentsTagsManager::SetProvider(WebContentsTaskProvider* provider) {
  DCHECK(provider);
  DCHECK(!provider_);
  provider_ = provider;
}

void WebContentsTagsManager::ClearProvider() {
  DCHECK(provider_);
  provider_ = nullptr;
}

void WebContentsTagsManager::ClearFromProvider(const WebContentsTag* tag) {
  if (provider_)
    provider_->OnWebContentsTagRemoved(tag);
}

WebContentsTagsManager::WebContentsTagsManager()
    : provider_(nullptr) {
}

WebContentsTagsManager::~WebContentsTagsManager() {
}

}  // namespace task_manager


text:
package com.zaliczenie.projekt;

import org.junit.Test;

import java.io.File;
import java.net.URL;
import java.util.List;

import static org.junit.Assert.*;

/**
 * Created by mk on 2016-02-02.
 */
public class ImageDuplicateFinderTest {
    URL pathToResources = ImageDuplicateCheckerTest.class.getClassLoader().getResource("images/");
    ImageDuplicateFinder duplicateFinder = new ImageDuplicateFinder(new MockImageDuplicateChecker());

    @Test
    public void testGetAllFiles() throws Exception {
        List<File> files = duplicateFinder.GetAllFiles(new File(pathToResources.toURI()));
        assertEquals(13, files.size());
    }

    @Test
    public void testFindDuplicates_for_3_koalas() throws Exception {
        List<File> files = duplicateFinder.findDuplicates(new File(pathToResources.toURI() + "/Koala.jpg"), new File(pathToResources.toURI()));
        assertEquals(3, files.size());
    }

    @Test
    public void testFindDuplicates_for_2_chryzantenium() throws Exception {
        List<File> files = duplicateFinder.findDuplicates(new File(pathToResources.toURI() + "/Chrysanthemum.jpg"), new File(pathToResources.toURI()));
        assertEquals(2, files.size());
    }
}


text:
package io.bogar.ecdtool.ui;

import java.util.Arrays;
import java.util.SortedMap;

import io.bogar.ecdtool.bl.BL;

import javax.swing.table.AbstractTableModel;

public class TranslationTableModel extends AbstractTableModel {

	private BL bl;
	private boolean onlyNew;
	private char[] keys;
	private String[] values;
	private int boundary;
	private final static String[] headers = { "Source", "Target" };

	public TranslationTableModel(BL bl, boolean onlyNew) {
		this.bl = bl;
		this.onlyNew = onlyNew;
		SortedMap<Character, String> mappingTable = bl.getMappingTable();
		int keySize = mappingTable.size();
		keys = new char[keySize];
		values = new String[keySize];
		boundary = 0;
		int fromEnd = keySize-1;
		for (Character c : mappingTable.keySet()) {
			String s = mappingTable.get(c);
			if (c.toString().equals(s)) {
				keys[boundary++] = c;
			} else {
				keys[fromEnd--] = c;
			}
		}
		if (boundary>0) {
			Arrays.sort(keys,0,boundary);
		}
		if (fromEnd<keySize-1) {
			Arrays.sort(keys,fromEnd+1,keys.length);
		}
		for (int i=0;i<keys.length;i++) {
			values[i] = mappingTable.get(keys[i]);
		}
	}

	public String getColumnName(int col) {
		return headers[col];
	}

	public int getColumnCount() {
		return 2;
	}

	public int getRowCount() {
		return onlyNew ? boundary : keys.length;
	}

	public Object getValueAt(int row, int col) {
		// TODO Auto-generated method stub
		switch (col) {
		case 0:	return keys[row];
		case 1:	return values[row];
		default: return null;
		}
	}

    public boolean isCellEditable(int row, int col) {
    	return col==1;
    }

    public void setValueAt(Object value, int row, int col) {
    	if (col==1) {
    		values[row] = (String) value;
    	}
    }

	public void setOnlyNew(boolean onlyNew) {
		this.onlyNew = onlyNew;
		fireTableDataChanged();
	}

	public void commit() {
		for (int i=0;i<keys.length;i++) {
			if (!bl.getMappingTable().get(keys[i]).equals(values[i])) {
				bl.getMappingTable().put(keys[i], values[i]);
			}
		}
	}

}


text:
<?php namespace models;

use models\base\Model;

/**
 * Class UserModel
 * @package models
 */
class PostModel extends Model
{

	public $id;
	public $type;
	public $title;
	public $body;
	public $date;

	public function __construct($id)
	{
		parent::__construct('post', $id);
		$this->title		= $this->faker->words(10, true);
		$this->body			= $this->faker->text();
		$this->date			= $this->faker->date();
	}

}


text:
#pragma once
#include <aws/chime-sdk-media-pipelines/ChimeSDKMediaPipelines_EXPORTS.h>
#include <aws/chime-sdk-media-pipelines/model/ConcatenationSinkType.h>
#include <aws/chime-sdk-media-pipelines/model/S3BucketSinkConfiguration.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ChimeSDKMediaPipelines
{
namespace Model
{

  /**
   *
The data sink of the configuration object.

See Also:
   AWS
   * API Reference

   */
  class AWS_CHIMESDKMEDIAPIPELINES_API ConcatenationSink
  {
  public:
    ConcatenationSink();
    ConcatenationSink(Aws::Utils::Json::JsonView jsonValue);
    ConcatenationSink& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The type of data sink in the configuration object.

     */
    inline const ConcatenationSinkType& GetType() const{ return m_type; }

    /**
     *
The type of data sink in the configuration object.

     */
    inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }

    /**
     *
The type of data sink in the configuration object.

     */
    inline void SetType(const ConcatenationSinkType& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
The type of data sink in the configuration object.

     */
    inline void SetType(ConcatenationSinkType&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
The type of data sink in the configuration object.

     */
    inline ConcatenationSink& WithType(const ConcatenationSinkType& value) { SetType(value); return *this;}

    /**
     *
The type of data sink in the configuration object.

     */
    inline ConcatenationSink& WithType(ConcatenationSinkType&& value) { SetType(std::move(value)); return *this;}

    /**
     *
The configuration settings for an Amazon S3 bucket sink.

     */
    inline const S3BucketSinkConfiguration& GetS3BucketSinkConfiguration() const{ return m_s3BucketSinkConfiguration; }

    /**
     *
The configuration settings for an Amazon S3 bucket sink.

     */
    inline bool S3BucketSinkConfigurationHasBeenSet() const { return m_s3BucketSinkConfigurationHasBeenSet; }

    /**
     *
The configuration settings for an Amazon S3 bucket sink.

     */
    inline void SetS3BucketSinkConfiguration(const S3BucketSinkConfiguration& value) { m_s3BucketSinkConfigurationHasBeenSet = true; m_s3BucketSinkConfiguration = value; }

    /**
     *
The configuration settings for an Amazon S3 bucket sink.

     */
    inline void SetS3BucketSinkConfiguration(S3BucketSinkConfiguration&& value) { m_s3BucketSinkConfigurationHasBeenSet = true; m_s3BucketSinkConfiguration = std::move(value); }

    /**
     *
The configuration settings for an Amazon S3 bucket sink.

     */
    inline ConcatenationSink& WithS3BucketSinkConfiguration(const S3BucketSinkConfiguration& value) { SetS3BucketSinkConfiguration(value); return *this;}

    /**
     *
The configuration settings for an Amazon S3 bucket sink.

     */
    inline ConcatenationSink& WithS3BucketSinkConfiguration(S3BucketSinkConfiguration&& value) { SetS3BucketSinkConfiguration(std::move(value)); return *this;}

  private:

    ConcatenationSinkType m_type;
    bool m_typeHasBeenSet = false;

    S3BucketSinkConfiguration m_s3BucketSinkConfiguration;
    bool m_s3BucketSinkConfigurationHasBeenSet = false;
  };

} // namespace Model
} // namespace ChimeSDKMediaPipelines
} // namespace Aws


text:
A simple Retrier Service to retry the rest calls with configurable intervals between retries.

## Requirements
* Java 8
* [RabbitMQ](https://www.rabbitmq.com/download.html)
* [Redis](http://redis.io/topics/quickstart)

## Setup

* Update the appropriate configs in retrier.yml
* Start the RabbitMQ server, Redis server, Redis sentinels
* Start the restapi-retrier server
* Create `default` retry workflow using the [Create Retry workflow](#create-retry-workflow) API

## APIs

### Create Retry workflow

```
POST http://localhost:8200/retry_workflow

HEADERS:
Content-Type: application/json

{
    "name": "test",
    "retry_delays": [5000,10000,15000]
}
```
`name` : Name of the retry workflow

`retry_delays` : Array of retry intervals, specified in milliseconds. The number of retries will be equal to the number of elements in this array.

### Schedule a Retry Request

```
POST http://localhost:8200/retry

HEADERS:
Content-Type: application/json
x-retry-workflow: test

{
    "message_id" : "foo",
    "group_id" : "bar",
    "retry_request": {
        "request_type": "POST",
        "request_body": {
            "key":"success",
            "test":"test"
        },
        "url": "http://localhost/",
        "headers": {"header1":["success"]}
    },
    "retry_failure_request": {
        "request_type": "POST",
        "request_body":  {
            "key":"failed",
            "abc":"abc"
        },
        "url": "http://localhost/",
        "headers": {"header1":["failed"]}
    }
}
```

`x-retry-workflow`: Name of the retry workflow to use for retrying. If this header is not passed, `default` workflow will be used by default. So ensure you create default workflow during inital setup.

`message_id`: unique id for a message.

`group_id` **(Currently grouping is not supported)**: ID to group the messages.
Eg: If the first message in the group fails in the first retry and is moved to the second retry queue, subsequent messages with same group id will be directly moved to the second retry queue where the first message exists. This way the ordering of messages within a group will be maintained.

`retry_request`: The request which has to be retried.

      `request_type`: Allowed request types "POST", "PUT", "GET".

      `request_body`: JSON request body.

      `url`: Request end point.

      `headers`: Request headers.

`retry_failure_request`: The fallback request which has to be executed if the all the retries fail.

## Implementation Details

### Retry Workflow
Retry workflow is a series of rabbitmq queues that the retry request flows through.
There are two types of queues in the retry workflow:
* Delay Queue (*prefixed with DQ*)
* Retry Queue (*prefixed with RQ*)

### Delay Queue
It is the queue where the delay will be introduced between subsequent retries. It uses `x-dead-letter-exchange` and `x-message-ttl` to delay the messages before pushing them to the next retry queue. For more information on this, check [this link](http://yuserinterface.com/dev/2013/01/08/how-to-schedule-delay-messages-with-rabbitmq-using-a-dead-letter-exchange/). There won't be any consumers for this queue.

### Retry Queue
There will be consumers running for Retry Queues. Consumers will pick the message from this queue and make the http call with headers and body specified in the `retry_request`. If the response recieved is 2xx, then `ack` will be sent to the queue. Else `nack` will be sent to the queue and the message will be moved to the next *Delay queue* through `dead-letter-exchange`.

If the retry queue is final queue in the workflow, in case non-2xx response on the `retry_request`, the `retry_failure_request` will be executed. If `retry_failure_request` is not specified, the message will be ignored and `nack` will be sent. Since there won't be any `dead-letter-exchange` associated with the last queue in workflow, this message will be discarded.

Note: In both Delay queues and Retry queues `x-dead-letter-routing-key` will be set to name of the next retry queue/delay queue respectively, as "queue_name" is being used as the routing key to push to the queue.

![retry_workflow](retry_workflow.png?raw=true)

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## License

MIT License: See the [License file](LICENSE.md)


text:
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.firestore.core;

import static com.google.firebase.firestore.util.Assert.hardAssert;

/**
 * Generates monotonically increasing target IDs for sending targets to the watch stream.
 *
 *
The client constructs two generators, one for the query cache (via forTargetCache()), and one
 * for limbo documents (via forSyncEngine()). These two generators produce non-overlapping IDs (by
 * using even and odd IDs respectively).
 *
 *
By separating the target ID space, the query cache can generate target IDs that persist across
 * client restarts, while sync engine can independently generate in-memory target IDs that are
 * transient and can be reused after a restart.
 */
// TODO(mrschmidt): Explore removing this class in favor of generating these IDs directly in
// SyncEngine and LocalStore.
public class TargetIdGenerator {

  /**
   * Creates and returns the TargetIdGenerator for the local store.
   *
   * @return A shared instance of TargetIdGenerator.
   */
  public static TargetIdGenerator forTargetCache(int after) {
    TargetIdGenerator generator = new TargetIdGenerator(QUERY_CACHE_ID, after);
    // Make sure that the next call to `nextId()` returns the first value after 'after'.
    generator.nextId();
    return generator;
  }

  /**
   * Creates and returns the TargetIdGenerator for the sync engine.
   *
   * @return A shared instance of TargetIdGenerator.
   */
  public static TargetIdGenerator forSyncEngine() {
    // Sync engine assigns target IDs for limbo document detection.
    return new TargetIdGenerator(SYNC_ENGINE_ID, 1);
  }

  private static final int QUERY_CACHE_ID = 0;
  private static final int SYNC_ENGINE_ID = 1;

  private static final int RESERVED_BITS = 1;

  private int nextId;
  private int generatorId;

  /** Instantiates a new TargetIdGenerator, using the seed as the first target ID to return. */
  TargetIdGenerator(int generatorId, int seed) {
    hardAssert(
        (generatorId & RESERVED_BITS) == generatorId,
        "Generator ID %d contains more than %d reserved bits",
        generatorId,
        RESERVED_BITS);
    this.generatorId = generatorId;
    seek(seed);
  }

  private void seek(int targetId) {
    hardAssert(
        (targetId & RESERVED_BITS) == this.generatorId,
        "Cannot supply target ID from different generator ID");
    this.nextId = targetId;
  }

  /** @return the next id in the sequence */
  public int nextId() {
    int nextId = this.nextId;
    this.nextId += 1 << RESERVED_BITS;
    return nextId;
  }
}


text:
<cdk-tree [dataSource]="dataSource" [treeControl]="treeControl">
  <!-- This is the tree node template for leaf nodes -->
  <cdk-nested-tree-node *cdkTreeNodeDef="let node" class="example-tree-node">
    <!-- use a disabled button to provide padding for tree leaf -->
    <button mat-icon-button disabled></button>
    {{node.name}}
  </cdk-nested-tree-node>
  <!-- This is the tree node template for expandable nodes -->
  <cdk-nested-tree-node *cdkTreeNodeDef="let node; when: hasChild" class="example-tree-node">
    <button mat-icon-button [attr.aria-label]="'toggle ' + node.name" cdkTreeNodeToggle>
      <mat-icon class="mat-icon-rtl-mirror">
        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
      </mat-icon>
    </button>
    {{node.name}}
    <div [class.example-tree-invisible]="!treeControl.isExpanded(node)">
      <ng-container cdkTreeNodeOutlet></ng-container>
    </div>
  </cdk-nested-tree-node>
</cdk-tree>


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

<title>FormatFile</title>
<meta name="date" content="2014-09-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.positional.mapping.api

Class FormatFile

java.lang.Object

com.positional.mapping.api.FormatFile

public class FormatFile
extends java.lang.Object

Author:

Gloaguen Joel

Constructor Summary

Constructors

Constructor and Description

FormatFile()

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getName()

Getter name

boolean
isHeader()

Getter header

void
setHeader(boolean header)

Setter header

void
setName(java.lang.String name)

Setter name

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FormatFile

public FormatFile()

Method Detail

getName

public java.lang.String getName()

Getter name

Returns:

the name

setName

public void setName(java.lang.String name)

Setter name

Parameters:

name - the name to set

isHeader

public boolean isHeader()

Getter header

Returns:

the header

setHeader

public void setHeader(boolean header)

Setter header

Parameters:

header - the header to set

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
/**
 * Based on
 * https://github.com/HaliteChallenge/Halite/blob/master/environment/networking/Networking.cpp
 */
#include "NetworkAgent.hpp"
#include "chickenpoker/ChpState.hpp"
#include "logging/log.h"

#include <chrono>
#include <thread>
#include <mutex>
#include <sstream>

// TODO check which includes are necessary
#ifdef _WIN32
    #include <windows.h>
    #include <tchar.h>
    #include <stdio.h>
    #include <strsafe.h>
#else
    #include <signal.h>
    #include <time.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <sys/select.h>
#ifdef __linux__
    #include <sys/prctl.h>
#endif
    #include <unistd.h>
#endif

std::mutex cout_mutex;

// constructor
NetworkAgent::NetworkAgent(unsigned int const agent_id, std::string const& cmd)
    : Agent(agent_id) {
    LOG(INFO) << "Creating NetworkAgent, running: " << cmd;
    this->start_subprocess(cmd);
};

std::string to_string(int n) {
    std::ostringstream oss;
    oss << n;
    return oss.str();
};

std::string to_string(std::vector<unsigned int> v) {
    std::ostringstream oss;
    for (auto n : v) {
        oss << n << " ";
    }
    return oss.str();
};

/** Message the subprocess to reset for a new episode and send the initial state. */
void NetworkAgent::initialize_episode(InitialState& initial_state) {
        unsigned int const MAX_INIT_TIME_MILLIS(10000); // 10 sec
        std::string reset, player_id, bets, player_ids;
        reset = "RESET";
        sendString(reset);
        player_id = to_string(this->get_id());
        bets = to_string(initial_state.bets);
        player_ids = to_string(initial_state.player_ids);
        sendString(player_id);
        sendString(bets);
        sendString(player_ids);
        LOG(INFO) << "Network Agent eps init sending id " << player_id << " and bets " << bets << ".";
        std::string const botname = this->getString(MAX_INIT_TIME_MILLIS);
        LOG(INFO) << "Network Agent bot name: " << botname;
    };

/** React with an action to the observed state. */
Action NetworkAgent::receive_state(AgentState& agentState) {
    unsigned int const MAX_TIME_MILLIS(3000); // 3 sec.
    LOG(DEBUG) << "network agent receive_state";
    // Convert the state to a string
    std::string state_msg = agentState.serialize();

    LOG(DEBUG) << "network agent sendString: " << state_msg;
    // Send the state_string
    this->sendString(state_msg);
    // Receive the action as string
    std::string action_msg = this->getString(MAX_TIME_MILLIS);
    // Deserialize and return the action
    LOG(INFO) << "network agent deserialize action; " << action_msg;
    Action action = Action::deserialize(*this, action_msg);
    return action;
};

// Start the subprocess
void NetworkAgent::start_subprocess(std::string command) {
#ifdef _WIN32

    command = "/C " + command;
    WinConnection parentConnection, childConnection;

    SECURITY_ATTRIBUTES saAttr;
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;

    //Child stdout pipe
    if(!CreatePipe(&parentConnection.read, &childConnection.write, &saAttr, 0)) {
        LOG(ERROR) << "Could not create pipe";
        throw 1;
    }
    if(!SetHandleInformation(parentConnection.read, HANDLE_FLAG_INHERIT, 0)) {
        throw 1;
    }

    //Child stdin pipe
    if(!CreatePipe(&childConnection.read, &parentConnection.write, &saAttr, 0)) {
        LOG(ERROR) << "Could not create pipe";
        throw 1;
    }
    if(!SetHandleInformation(parentConnection.write, HANDLE_FLAG_INHERIT, 0)) {
        throw 1;
    }

    //MAKE SURE THIS MEMORY IS ERASED
    PROCESS_INFORMATION piProcInfo;
    ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));

    STARTUPINFO siStartInfo;
    ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
    siStartInfo.cb = sizeof(STARTUPINFO);
    siStartInfo.hStdError = childConnection.write;
    siStartInfo.hStdOutput = childConnection.write;
    siStartInfo.hStdInput = childConnection.read;
    siStartInfo.dwFlags |= STARTF_USESTDHANDLES;

    //C:/xampp/htdocs/Halite/Halite/Debug/ExampleBot.exe
    //C:/Users/Michael/Anaconda3/python.exe
    //C:/Program Files/Java/jre7/bin/java.exe -cp C:/xampp/htdocs/Halite/AIResources/Java MyBot
    bool success = CreateProcess(
        "C:\\windows\\system32\\cmd.exe",
        LPSTR(command.c_str()),     //command line
        NULL,          //process security attributes
        NULL,          //primary thread security attributes
        TRUE,          //handles are inherited
        0,             //creation flags
        NULL,          //use parent's environment
        NULL,          //use parent's current directory
        &siStartInfo,  //STARTUPINFO pointer
        &piProcInfo
    );  //receives PROCESS_INFORMATION
    if(!success) {
        LOG(ERROR) << "Could not start process";
        throw 1;
    }
    else {
        CloseHandle(piProcInfo.hProcess);
        CloseHandle(piProcInfo.hThread);

        this->process = piProcInfo.hProcess;
        this->connection = parentConnection;
    }

#else
    pid_t pid;
    int writePipe[2];
    int readPipe[2];

    if(pipe(writePipe)) {
        LOG(ERROR) << "Error creating pipe";
        throw 1;
    }
    if(pipe(readPipe)) {
        LOG(ERROR) << "Error creating pipe";
        throw 1;
    }

    pid_t ppid_before_fork = getpid();

    //Fork a child process
    pid = fork();
    if(pid == 0) { //This is the child
        setpgid(getpid(), getpid());

#ifdef __linux__
        // install a parent death signal
        // http://stackoverflow.com/a/36945270
        int r = prctl(PR_SET_PDEATHSIG, SIGTERM);
        if (r == -1) {
            LOG(ERROR) << "Error installing parent death signal";
            throw 1;
        }
        if (getppid() != ppid_before_fork) {
            exit(1);
        }
#endif

        dup2(writePipe[0], STDIN_FILENO);

        dup2(readPipe[1], STDOUT_FILENO);
        dup2(readPipe[1], STDERR_FILENO);

        execl("/bin/sh", "sh", "-c", command.c_str(), (char*) NULL);

        //Nothing past the execl should be run

        exit(1);
    } else if(pid < 0) {
        LOG(ERROR) << "Fork failed";
        throw 1;
    }

    this->connection.read = readPipe[0];
    this->connection.write = writePipe[1];

    this->process = pid;

#endif
}

void NetworkAgent::sendString(std::string& msg) {
    //End message with newline character
    msg += '\n';

#ifdef _WIN32
//    WinConnection connection = this->connection;

    DWORD charsWritten;
    bool success;
    success = WriteFile(connection.write, msg.c_str(), msg.length(), &charsWritten, NULL);
    if(!success || charsWritten == 0) {
        LOG(ERROR) << "Problem writing to pipe";
        throw 1;
    }

#else
    //UniConnection connection = this->connection;
    ssize_t charsWritten = write(connection.write, msg.c_str(), msg.length());
    if(charsWritten < msg.length()) {
        LOG(ERROR) << "Problem writing to pipe";
        throw 1;
    }
#endif
};

std::string NetworkAgent::getString(unsigned int const timeoutMillis) {

    std::string newString;
    int timeoutMillisRemaining = timeoutMillis;
    std::chrono::high_resolution_clock::time_point tp = std::chrono::high_resolution_clock::now();

#ifdef _WIN32
    // WinConnection connection = connections[playerTag - 1];

    DWORD charsRead;
    bool success;
    char buffer;

    //Keep reading char by char until a newline
    while(true) {
        timeoutMillisRemaining = timeoutMillis - std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - tp).count();
        if(timeoutMillisRemaining < 0) {
            throw newString;
        }
        //Check to see that there are bytes in the pipe before reading
        //Throw error if no bytes in alloted time
        //Check for bytes before sampling clock, because reduces latency (vast majority the pipe is alread full)
        DWORD bytesAvailable = 0;
        PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
        if(bytesAvailable < 1) {
            std::chrono::high_resolution_clock::time_point initialTime = std::chrono::high_resolution_clock::now();
            while (bytesAvailable < 1) {
                if(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - initialTime).count() > timeoutMillisRemaining) {
                    throw newString;
                }
                PeekNamedPipe(connection.read, NULL, 0, NULL, &bytesAvailable, NULL);
            }
        }

        success = ReadFile(connection.read, &buffer, 1, &charsRead, NULL);
        if(!success || charsRead < 1) {
            std::string errorMessage = "Bot #" + std::to_string(playerTag) + " timed out or errored (Windows)\n";
            std::lock_guard<std::mutex> guard(cout_mutex);
            LOG(ERROR) << errorMessage;
            throw newString;
        }
        if(buffer == '\n') {
            break;
        }
        else {
            newString += buffer;
        }
    }
#else
    // UniConnection connection = connections[playerTag - 1];

    fd_set set;
    FD_ZERO(&set); /* clear the set */
    FD_SET(connection.read, &set); /* add our file descriptor to the set */
    char buffer;

    //Keep reading char by char until a newline
    while(true) {

        //Check if there are bytes in the pipe
        timeoutMillisRemaining = timeoutMillis - std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - tp).count();
        if(timeoutMillisRemaining < 0) {
            throw newString;
        }
        struct timeval timeout;
        timeout.tv_sec = timeoutMillisRemaining / 1000.0;
        timeout.tv_usec = (timeoutMillisRemaining % 1000)*1000;
        int selectionResult = select(connection.read+1, &set, NULL, NULL, &timeout);

        if(selectionResult > 0) {
            read(connection.read, &buffer, 1);

            if(buffer == '\n') {
                break;
            } else {
                newString += buffer;
            }
        } else {
            std::string errorMessage = "Bot #" + std::to_string(this->get_id()) + " timeout or error (Unix) " + std::to_string(selectionResult) + '\n';
            std::lock_guard<std::mutex> guard(cout_mutex);
            LOG(ERROR) << errorMessage;
            throw newString;
        }
    }
#endif
    //Python turns \n into \r\n
    if(newString.back() == '\r') {
        newString.pop_back();
    }

    return newString;
};


text:
MyBatis does four main things:

1. It executes SQL safely and abstracts away all the intricacies of JDBC
2. It maps parameter objects to JDBC prepared statement parameters
3. It maps rows in JDBC result sets to objects
4. It can generate dynamic SQL with special tags in XML, or through the use of various templating engines

This library takes full advantage of the first three capabilities in MyBatis and essentially becomes another
templating engine for generating dynamic SQL.

For example, MyBatis can execute an SQL string formatted like this:

```sql
  select id, description from table_codes where id = #{id,jdbcType=INTEGER}
```

This is standard SQL with a MyBatis twist - the parameter notation `#{id,jdbcType=INTEGER}`
tells MyBatis to take the `id` property of a parameter object and use it as a JDBC prepared statement
parameter.

Now suppose we have two Java classes like this:

```java
public class TableCode {
  private Integer id;
  private String description;
  ... getters/setters
}

public class Parameter {
  private String sql = "select id, description from table_codes where id = #{id,jdbcType=INTEGER}";
  private Integer id;

  public Parameter(Integer id) {
    this.id = id;
  }

  public Integer getId() {
    return id;
  }

  public String getSql() {
    return sql;
  }
}
```
These classes can be used in conjunction with a MyBatis mapper like this:

```java
public interface Mapper {

  @Select({
    "${sql}"
  })
  TableCode getTableCode(Parameter parameter);
}
```

Using this mapper with MyBatis looks like this:

```java
  try(SqlSession sqlSession = sqlSessionFactory.openSession()) {
    Mapper mapper = sqlSession.getMapper(Mapper.class);
    Parameter parameter = new Parameter(2);
    TableCode tableCode = mapper.getTableCode(parameter);
    assertThat(tableCode.getId()).isEqualTo(2);
  }
```

The parameter object has a property called `sql`. That SQL string will be prepared as a JDBC prepared statement
in MyBatis. The SQL string also references a property called `id`. That property - from the same parameter object -
will be used as the value of the prepared statement parameter.

So the main idea is this - this library builds a version of the `Parameter` class shown above. The class includes
the full SQL statement to execute, formatted for MyBatis, and any parameters referenced by the statement.
There are different versions of these classes for the different types of SQL statements. But in every case, the class
is designed to be the one single parameter for a MyBatis mapper method.

## What About SQL Injection?

It is true that mappers written this way are open to SQL injection. This is also true of using any of the
various SQL provider classes in MyBatis (`@SelectProvider`, etc.) So you must be careful that these types of mappers are not exposed to any general user input.

If you follow these practices, you will lower the risk of SQL injection:

1. Always use MyBatis annotated mappers
2. Use the `SqlProviderAdapter` utility class in conjunction with the MyBatis provider annotations (`@InsertProvider`, `@SelectProvider`, etc.)


text:
<?php

namespace Scribe\Jabiru\Tests\Jabiru\Extension;

use Scribe\Jabiru\Jabiru;
use Scribe\Jabiru\Renderer\XhtmlRenderer;
use Scribe\Jabiru\Extension\Html\AttributesExtension;
use Symfony\Component\Finder\Finder;

/**
 * Tests Scribe\Jabiru\Extensions\Html\*
 *
 * @group Html
 */
class HtmlExtensionsTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @dataProvider htmlProvider
     */
    public function testHtmlPatterns($name, $textile, $expected)
    {
        $jabiru = new Jabiru(new XhtmlRenderer());
        $jabiru->addExtensions([
            new AttributesExtension()
        ]);

        $expected = str_replace("\r\n", "\n", $expected);
        $expected = str_replace("\r", "\n", $expected);
        $html     = $jabiru->render($textile);

        $this->assertEquals($expected, $html, sprintf('%s failed', $name));
    }

    /**
     * @return array
     */
    public function htmlProvider()
    {
        $finder = Finder::create()
            ->in([__DIR__.'/../Resources/html', __DIR__.'/../Resources/core'])
            ->files()
            ->name('*.md')
            ->notName('link-automatic-email.md');

        return $this->processPatterns($finder);
    }

    /**
     * @param Finder|\Symfony\Component\Finder\SplFileInfo[] $finder
     *
     * @return array
     */
    protected function processPatterns(Finder $finder)
    {
        $patterns = [];

        foreach ($finder as $file) {
            $name       = preg_replace('/\.(md|out)$/', '', $file->getFilename());
            $expected   = trim(file_get_contents(preg_replace('/\.md$/', '.out', $file->getPathname())));
            $expected   = str_replace("\r\n", "\n", $expected);
            $expected   = str_replace("\r", "\n", $expected);
            $patterns[] = [$name, $file->getContents(), $expected];
        }

        return $patterns;
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>The video Element</title>

video

The most basic use of the video element. (Not a best practice as there is no fallback content for browsers that do not
      support the codec or the video element itself.)

<video src="video/wine_pouring.mp4" controls></video>

    <video src="video/wine_pouring.mp4" controls></video>

Create video element, but do not load any data.

<video src="video/wine_pouring.mp4" controls preload="none"></video>

    <video src="video/wine_pouring.mp4" controls preload="none"></video>

Create video element, and only load metadata.

<video src="video//wine_pouring.mp4" controls preload="metadata"></video>

    <video src="video//wine_pouring.mp4" controls preload="metadata"></video>

Because of the differences in behavior between browser implementations when it comes to preload="metadata",
      and the default behavior when specifying preload="none" it's best to always specify the width and height of
      the video element when played.

<video src="video/wine_pouring.mp4" controls preload="none" width="480" height="270"></video>
<video src="video/wine_pouring.mp4" controls preload="metadata" width="480" height="270"></video>

    <video src="video/wine_pouring.mp4" controls preload="none" width="480" height="270"></video>
    <video src="video/wine_pouring.mp4" controls preload="metadata" width="480" height="270"></video>

Also note that by default, the video element is displayed inline. This means that two video elements
      will be displayed horizontally, instead of stacked vertically, dependant on the individual video size and the width of
      the browser window.

Showing a static image instead of the default gray or black block, is as simple as using the poster attribute
      and specifying an image.

<video src="video/wine_pouring.mp4" controls preload="none" width="480" height="270" poster="video/poster.png"></video>

    <video src="video/wine_pouring.mp4" controls preload="none" width="480" height="270" poster="video/poster.png"></video>

Looping a video using the loop boolean attribute.

<video src="video/record_stock.mp4" controls width="490" height="270" loop></video>

    <video src="video/record_stock.mp4" controls width="490" height="270" loop></video>

You can mute the audio track by setting the mute boolean attribute. This does not however prevent the user from
    enabling audio manually.

<video src="video/record_stock.mp4" controls width="490" height="270" muted></video>

    <video src="video/record_stock.mp4" controls width="490" height="270" muted></video>

When a video is loaded by the user agent it goes through various steps before the video is loaded and played. One of these steps is called the resource selection algorithm. As the name suggests, this is where the user agent will select which of the specififed media elements it will play, based on outcomes such as whether the media type can be played by the user agent or, whether loading of the media resource was successfull or failed.

There are a couple of ways a media resource location can be specified to the user agent. It can be specified as a media provider object, which can be one of MediaStream, MediaSource, Blob or, File.

It can also be specified using the src attribute of the video element or, specifying one or more resource locations using nested source elements.

Once the user agent has selected the media resource to load, it calls the resource fetch algorithm. This algorithm has one of two paths it can follow and, for all but when called with an object, as defined above, this will be called with a URL and follow the "mode is remote" path.

In general a user of the video element will not be overly concerned about this process. However, if you wish to do more with video data that is loaded via a cross-origin request, you need to be aware of this process and in particular, the crossorigin attribute and it's role.

The crossorigin attribute has one of two possible values:

anonymous

use-credentials

It is important to note that what follows relates to the Fetch standard which is still in process. When you use the crossorigin attribute it sets the use-URL-credentials flag and maps anonymous to "same-origin" and use-credentails to "include" for the crendentials mode. If you omit the crossorigin attribute, use-URL-credentials is unset and, the default for credentials mode is assumed, which is omit.

The use or omision of the crossorigin attribute then also plays a role in the Access-Control-Allow-Credentials Fetch header in determining whether access to a resource should be allowed if credentials mode is set to "include"[use-credentials].

Using crossorigin when loading data from third parties is especially important if you want to use the data obtained for anything more than basic interactions. If a video has associated metadata related to subtitle tracks or chapter titles for example, it will not be loaded if a CORS resource sharing check is not passed. As such, if you require access to this metadata and it is protected you will need to set crossorigin to "use-credentials".

Another example of where the use of this attribute is important is when painting the video data to a canvas. If the CORS resource sharing check fails in this scenario, the origin-clean flag of the canvas will be set to false,tainting the canvas, and subsequent calls to the element's toDataURL(), toBlob(), and getImageData() functions will result in a SecurityError to prevent leaking cross-origin data.

<video src="video/record_stock.mp4" controls width="490" height="270" crossorigin="use-credentials"></video>


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.yaml.snakeyaml.parser (SnakeYAML 1.11 API)
</TITLE>

<META NAME="keywords" CONTENT="org.yaml.snakeyaml.parser package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.yaml.snakeyaml.parser

Interfaces

Parser

Classes

ParserImpl

Exceptions

ParserException


text:
//---------------------------------------------------------------------------//
//!
//! \file   DataGen_StandardElectronPhotonRelaxationDataGenerator.hpp
//! \author Alex Robinson
//! \brief  The standard electron-photon-relaxation data generator class decl.
//!
//---------------------------------------------------------------------------//

#ifndef DATA_GEN_STANDARD_ELECTRON_PHOTON_RELAXATION_DATA_GENERATOR_HPP
#define DATA_GEN_STANDARD_ELECTRON_PHOTON_RELAXATION_DATA_GENERATOR_HPP

// Std Lib Includes
#include <utility>

// Trilinos Includes
#include <Teuchos_RCP.hpp>
#include <Teuchos_Array.hpp>

// FRENSIE Includes
#include "DataGen_ElectronPhotonRelaxationDataGenerator.hpp"
#include "MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.hpp"
#include "Data_ENDLFileHandler.hpp"
#include "Data_XSSEPRDataExtractor.hpp"
#include "Utility_OneDDistribution.hpp"

namespace DataGen{

//! The standard electron-photon-relaxation data generator class
class StandardElectronPhotonRelaxationDataGenerator : public ElectronPhotonRelaxationDataGenerator
{

public:

  //! Constructor
  StandardElectronPhotonRelaxationDataGenerator(
	   const unsigned atomic_number,
	   const Teuchos::RCP<const Data::XSSEPRDataExtractor>& ace_epr_data,
       const Teuchos::RCP<Data::ENDLFileHandler>& eedl_file_handler,
	   const double min_photon_energy,
	   const double max_photon_energy,
       const double min_electron_energy,
       const double max_electron_energy,
       const double cutoff_angle,
	   const double occupation_number_evaluation_tolerance,
	   const double subshell_incoherent_evaluation_tolerance,
	   const double grid_convergence_tol = 0.001,
	   const double grid_absolute_diff_tol = 1e-13,
	   const double grid_distance_tol = 1e-13 );

  //! Destructor
  ~StandardElectronPhotonRelaxationDataGenerator()
  { /* ... */ }

  //! Populate the electron-photon-relaxation data container
  void populateEPRDataContainer(
			   Data::ElectronPhotonRelaxationVolatileDataContainer&
			   data_container ) const;

protected:

  // Set the atomic data
  void setRelaxationData( Data::ElectronPhotonRelaxationVolatileDataContainer&
			  data_container ) const;

  // Set the Compton profile data
  void setComptonProfileData(
			   Data::ElectronPhotonRelaxationVolatileDataContainer&
			   data_container ) const;

  // Set the occupation number data
  void setOccupationNumberData(
			   Data::ElectronPhotonRelaxationVolatileDataContainer&
			   data_container ) const;

  // Set the Waller-Hartree scattering function data
  void setWallerHartreeScatteringFunctionData(
			   Data::ElectronPhotonRelaxationVolatileDataContainer&
			   data_container ) const;

  // Set the Waller-Hartree atomic form factor data
  void setWallerHartreeAtomicFormFactorData(
			   Data::ElectronPhotonRelaxationVolatileDataContainer&
			   data_container ) const;

  // Set the photon data
  void setPhotonData( Data::ElectronPhotonRelaxationVolatileDataContainer&
		      data_container ) const;

  // Set the electron data
  void setElectronData( Data::ElectronPhotonRelaxationVolatileDataContainer&
			data_container ) const;

private:

  // Test if a value is greater than or equal to one
  static bool greaterThanOrEqualToOne( const double value );

  // Test if a value is greater than one
  static bool greaterThanOne( const double value );

  // The if a value is not equal to zero
  static bool notEqualZero( const double value );

  // Set the transition data
  void setTransitionData( const unsigned subshell,
			  const unsigned transitions,
			  const unsigned subshell_data_start_index,
			  Data::ElectronPhotonRelaxationVolatileDataContainer&
			  data_container ) const;

  // Extract the half Compton profile from the ACE table
  void extractHalfComptonProfile(
			   const unsigned subshell,
			   std::vector<double>& half_momentum_grid,
			   std::vector<double>& half_profile ) const;

  // Set the screened rutherford data
  void setScreenedRutherfordData(
    const Teuchos::RCP<const Utility::OneDDistribution>&
        cutoff_elastic_cross_section,
    const Teuchos::RCP<const Utility::OneDDistribution>&
        total_elastic_cross_section,
    const std::vector<double>& elastic_energy_grid,
    const std::map<double,std::vector<double> >& elastic_pdf,
    Data::ElectronPhotonRelaxationVolatileDataContainer& data_container ) const;

  // Extract the average photon heating numbers
  template<typename InterpPolicy>
  void extractCrossSection(
	  Teuchos::ArrayView<const double> raw_energy_grid,
	  Teuchos::ArrayView<const double> raw_cross_section,
	  Teuchos::RCP<const Utility::OneDDistribution>& cross_section ) const;

  // Extract electron cross sections
  template<typename InterpPolicy>
  void extractElectronCrossSection(
        std::vector<double>& raw_energy_grid,
        std::vector<double>& raw_cross_section,
        Teuchos::RCP<const Utility::OneDDistribution>& cross_section ) const;

  // Extract the subshell photoelectric cross sections
  void extractSubshellPhotoelectricCrossSections( Teuchos::Array<std::pair<unsigned,Teuchos::RCP<const Utility::OneDDistribution> > >& cross_sections ) const;

  // Create the subshell impulse approx incoherent cross section evaluators
  void createSubshellImpulseApproxIncoherentCrossSectionEvaluators(
     const Data::ElectronPhotonRelaxationVolatileDataContainer& data_container,
     Teuchos::Array<std::pair<unsigned,Teuchos::RCP<const MonteCarlo::SubshellIncoherentPhotonScatteringDistribution> > >& evaluators ) const;

  // Initialize the photon union energy grid
  void initializePhotonUnionEnergyGrid(
     const Data::ElectronPhotonRelaxationVolatileDataContainer& data_container,
     std::list<double>& union_energy_grid ) const;

  // Create the cross section on the union energy grid
  void createCrossSectionOnUnionEnergyGrid(
   const std::list<double>& union_energy_grid,
   const Teuchos::RCP<const Utility::OneDDistribution>& original_cross_section,
   std::vector<double>& cross_section,
   unsigned& threshold_index ) const;

  // Create the cross section on the union energy grid
  void createCrossSectionOnUnionEnergyGrid(
	     const std::list<double>& union_energy_grid,
	     const Teuchos::RCP<const MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>&
	     original_cross_section,
	     std::vector<double>& cross_section,
	     unsigned& threshold_index ) const;

  // Merge the electron union energy grid
  void mergeElectronUnionEnergyGrid(
    const std::vector<double>& energy_grid,
    std::list<double>& union_energy_grid ) const;

  // Calculate the total photoelectric cross section
  void calculateTotalPhotoelectricCrossSection(
	                   Data::ElectronPhotonRelaxationVolatileDataContainer&
			   data_container ) const;

  // Calculate the total impulse approx. incoherent cross section
  void calculateImpulseApproxTotalIncoherentCrossSection(
		           Data::ElectronPhotonRelaxationVolatileDataContainer&
			   data_container ) const;

  // Calculate the Waller-Hartree total cross section
  void calculateWallerHartreeTotalCrossSection(
		          Data::ElectronPhotonRelaxationVolatileDataContainer&
			  data_container ) const;

  // Calculate the impulse approx total cross section
  void calculateImpulseApproxTotalCrossSection(
		          Data::ElectronPhotonRelaxationVolatileDataContainer&
			  data_container ) const;

  // The threshold energy nudge factor
  static const double s_threshold_energy_nudge_factor;

  // The ACE data
  Teuchos::RCP<const Data::XSSEPRDataExtractor> d_ace_epr_data;

  // The EEDL data
  Teuchos::RCP<Data::ENDLFileHandler> d_eedl_file_handler;

  // The min photon energy
  double d_min_photon_energy;

  // The max photon energy
  double d_max_photon_energy;

  // The min electron energy
  double d_min_electron_energy;

  // The max electron energy
  double d_max_electron_energy;

  // The cutoff angle below which screened rutherford is used
  double d_cutoff_angle;

  // The occupation number evaluation tolerance
  double d_occupation_number_evaluation_tolerance;

  // The subshell incoherent evaluation tolerance
  double d_subshell_incoherent_evaluation_tolerance;

  // The grid convergence tolerance
  double d_grid_convergence_tol;

  // The grid absolute difference tolerance
  double d_grid_absolute_diff_tol;

  // The grid distance tolerance
  double d_grid_distance_tol;
};

// Test if a value is greater than or equal to one
inline bool
StandardElectronPhotonRelaxationDataGenerator::greaterThanOrEqualToOne(
							   const double value )
{
  return value >= 1.0;
}

// Test if a value is greater than one
inline bool
StandardElectronPhotonRelaxationDataGenerator::greaterThanOne(
							   const double value )
{
  return value > 1.0;
}

// The if a value is not equal to zero
inline bool StandardElectronPhotonRelaxationDataGenerator::notEqualZero(
							   const double value )
{
  return value != 0.0;
}

} // end DataGen namespace

//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//

#include "DataGen_StandardElectronPhotonRelaxationDataGenerator_def.hpp"

//---------------------------------------------------------------------------//

#endif // end DATA_GEN_STANDARD_ELECTRON_PHOTON_RELAXATION_DATA_GENERATOR_HPP

//---------------------------------------------------------------------------//
// end DataGen_StandardElectronPhotonRelaxationDataGenerator.hpp
//---------------------------------------------------------------------------//


text:
import DomainResourceSerializer from 'ember-fhir/serializers/domain-resource';

export default DomainResourceSerializer.extend({
  attrs: {
    identifier: { embedded: 'always' },
    name: { embedded: 'always' },
    telecom: { embedded: 'always' },
    address: { embedded: 'always' },
    maritalStatus: { embedded: 'always' },
    photo: { embedded: 'always' },
    contact: { embedded: 'always' },
    animal: { embedded: 'always' },
    communication: { embedded: 'always' },
    generalPractitioner: { embedded: 'always' },
    managingOrganization: { embedded: 'always' },
    link: { embedded: 'always' }
  }
});


text:
<?php

namespace TestApp\Model\Entity;

use Cake\ORM\Entity;

/**
 * Tests entity class used for asserting correct loading
 */
class Article extends Entity
{

}


text:
package hudson;

import hudson.PluginManager.PluginInstanceStore;
import hudson.model.Hudson;
import hudson.model.UpdateCenter;
import hudson.model.UpdateSite;
import hudson.util.VersionNumber;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Closeable;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Manifest;
import java.util.logging.Logger;
import static java.util.logging.Level.WARNING;

import org.apache.commons.logging.LogFactory;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;

/**
 * Represents a Hudson plug-in and associated control information
 * for Hudson to control {@link Plugin}.
 *
 *

 * A plug-in is packaged into a jar file whose extension is <tt>".hpi"</tt>,
 * A plugin needs to have a special manifest entry to identify what it is.
 *
 *

 * At the runtime, a plugin has two distinct state axis.
 *

 *
Enabled/Disabled. If enabled, Hudson is going to use it
 *      next time Hudson runs. Otherwise the next run will ignore it.
 *
Activated/Deactivated. If activated, that means Hudson is using
 *      the plugin in this session. Otherwise it's not.
 *

 *

 * For example, an activated but disabled plugin is still running but the next
 * time it won't.
 *
 * @author Kohsuke Kawaguchi
 */
public final class PluginWrapper {
    /**
     * {@link PluginManager} to which this belongs to.
     */
    public final PluginManager parent;

    /**
     * Plugin manifest.
     * Contains description of the plugin.
     */
    private final Manifest manifest;

    /**
     * {@link ClassLoader} for loading classes from this plugin.
     * Null if disabled.
     */
    public final ClassLoader classLoader;

    /**
     * Base URL for loading static resources from this plugin.
     * Null if disabled. The static resources are mapped under
     * <tt>hudson/plugin/SHORTNAME/</tt>.
     */
    public final URL baseResourceURL;

    /**
     * Used to control enable/disable setting of the plugin.
     * If this file exists, plugin will be disabled.
     */
    private final File disableFile;

    /**
     * Used to control the unpacking of the bundled plugin.
     * If a pin file exists, Hudson assumes that the user wants to pin down a particular version
     * of a plugin, and will not try to overwrite it. Otherwise, it'll be overwritten
     * by a bundled copy, to ensure consistency across upgrade/downgrade.
     * @since 1.325
     */
    private final File pinFile;

    /**
     * Short name of the plugin. The artifact Id of the plugin.
     * This is also used in the URL within Hudson, so it needs
     * to remain stable even when the *.hpi file name is changed
     * (like Maven does.)
     */
    private final String shortName;

    /**
     * True if this plugin is activated for this session.
     * The snapshot of <tt>disableFile.exists()</tt> as of the start up.
     */
    private final boolean active;

    private final List<Dependency> dependencies;
    private final List<Dependency> optionalDependencies;

    /**
     * Is this plugin bundled in hudson.war?
     */
    /*package*/ boolean isBundled;

    static final class Dependency {
        public final String shortName;
        public final String version;
        public final boolean optional;

        public Dependency(String s) {
            int idx = s.indexOf(':');
            if(idx==-1)
                throw new IllegalArgumentException("Illegal dependency specifier "+s);
            this.shortName = s.substring(0,idx);
            this.version = s.substring(idx+1);

            boolean isOptional = false;
            String[] osgiProperties = s.split(";");
            for (int i = 1; i < osgiProperties.length; i++) {
                String osgiProperty = osgiProperties[i].trim();
                if (osgiProperty.equalsIgnoreCase("resolution:=optional")) {
                    isOptional = true;
                }
            }
            this.optional = isOptional;
        }

        @Override
        public String toString() {
            return shortName + " (" + version + ")";
        }
    }

    /**
     * @param archive
     *      A .hpi archive file jar file, or a .hpl linked plugin.
     *  @param manifest
     *  	The manifest for the plugin
     *  @param baseResourceURL
     *  	A URL pointing to the resources for this plugin
     *  @param classLoader
     *  	a classloader that loads classes from this plugin and its dependencies
     *  @param disableFile
     *  	if this file exists on startup, the plugin will not be activated
     *  @param dependencies a list of mandatory dependencies
     *  @param optionalDependencies a list of optional dependencies
     */
	public PluginWrapper(PluginManager parent, File archive, Manifest manifest, URL baseResourceURL,
			ClassLoader classLoader, File disableFile,
			List<Dependency> dependencies, List<Dependency> optionalDependencies) {
        this.parent = parent;
		this.manifest = manifest;
		this.shortName = computeShortName(manifest, archive);
		this.baseResourceURL = baseResourceURL;
		this.classLoader = classLoader;
		this.disableFile = disableFile;
        this.pinFile = new File(archive.getPath() + ".pinned");
		this.active = !disableFile.exists();
		this.dependencies = dependencies;
		this.optionalDependencies = optionalDependencies;
	}

    /**
     * Returns the URL of the index page jelly script.
     */
    public URL getIndexPage() {
        return classLoader.getResource("index.jelly");
    }

    private String computeShortName(Manifest manifest, File archive) {
        // use the name captured in the manifest, as often plugins
        // depend on the specific short name in its URLs.
        String n = manifest.getMainAttributes().getValue("Short-Name");
        if(n!=null)     return n;

        // maven seems to put this automatically, so good fallback to check.
        n = manifest.getMainAttributes().getValue("Extension-Name");
        if(n!=null)     return n;

        // otherwise infer from the file name, since older plugins don't have
        // this entry.
        return getBaseName(archive);
    }

    /**
     * Gets the "abc" portion from "abc.ext".
     */
    static String getBaseName(File archive) {
        String n = archive.getName();
        int idx = n.lastIndexOf('.');
        if(idx>=0)
            n = n.substring(0,idx);
        return n;
    }

    public List<Dependency> getDependencies() {
        return dependencies;
    }

    public List<Dependency> getOptionalDependencies() {
        return optionalDependencies;
    }

    /**
     * Returns the short name suitable for URL.
     */
    public String getShortName() {
        return shortName;
    }

    /**
     * Gets the instance of {@link Plugin} contributed by this plugin.
     */
    public Plugin getPlugin() {
        return Hudson.lookup(PluginInstanceStore.class).store.get(this);
    }

    /**
     * Gets the URL that shows more information about this plugin.
     * @return
     *      null if this information is unavailable.
     * @since 1.283
     */
    public String getUrl() {
        // first look for the manifest entry. This is new in maven-hpi-plugin 1.30
        String url = manifest.getMainAttributes().getValue("Url");
        if(url!=null)      return url;

        // fallback to update center metadata
        UpdateSite.Plugin ui = getInfo();
        if(ui!=null)    return ui.wiki;

        return null;
    }

    @Override
    public String toString() {
        return "Plugin:" + getShortName();
    }

    /**
     * Returns a one-line descriptive name of this plugin.
     */
    public String getLongName() {
        String name = manifest.getMainAttributes().getValue("Long-Name");
        if(name!=null)      return name;
        return shortName;
    }

    /**
     * Returns the version number of this plugin
     */
    public String getVersion() {
        String v = manifest.getMainAttributes().getValue("Plugin-Version");
        if(v!=null)      return v;

        // plugins generated before maven-hpi-plugin 1.3 should still have this attribute
        v = manifest.getMainAttributes().getValue("Implementation-Version");
        if(v!=null)      return v;

        return "???";
    }

    /**
     * Returns the version number of this plugin
     */
    public VersionNumber getVersionNumber() {
        return new VersionNumber(getVersion());
    }

    /**
     * Returns true if the version of this plugin is older than the given version.
     */
    public boolean isOlderThan(VersionNumber v) {
        try {
            return getVersionNumber().compareTo(v) < 0;
        } catch (IllegalArgumentException e) {
            // if we can't figure out our current version, it probably means it's very old,
            // since the version information is missing only from the very old plugins
            return true;
        }
    }

    /**
     * Terminates the plugin.
     */
    public void stop() {
        LOGGER.info("Stopping "+shortName);
        try {
            getPlugin().stop();
        } catch(Throwable t) {
            LOGGER.log(WARNING, "Failed to shut down "+shortName, t);
        }
        // Work around a bug in commons-logging.
        // See http://www.szegedi.org/articles/memleak.html
        LogFactory.release(classLoader);
    }

    public void releaseClassLoader() {
        if (classLoader instanceof Closeable)
            try {
                ((Closeable) classLoader).close();
            } catch (IOException e) {
                LOGGER.log(WARNING, "Failed to shut down classloader",e);
            }
    }

    /**
     * Enables this plugin next time Hudson runs.
     */
    public void enable() throws IOException {
        if(!disableFile.delete())
            throw new IOException("Failed to delete "+disableFile);
    }

    /**
     * Disables this plugin next time Hudson runs.
     */
    public void disable() throws IOException {
        // creates an empty file
        OutputStream os = new FileOutputStream(disableFile);
        os.close();
    }

    /**
     * Returns true if this plugin is enabled for this session.
     */
    public boolean isActive() {
        return active;
    }

    public boolean isBundled() {
        return isBundled;
    }

    /**
     * If true, the plugin is going to be activated next time
     * Hudson runs.
     */
    public boolean isEnabled() {
        return !disableFile.exists();
    }

    public Manifest getManifest() {
        return manifest;
    }

    public void setPlugin(Plugin plugin) {
        Hudson.lookup(PluginInstanceStore.class).store.put(this,plugin);
        plugin.wrapper = this;
    }

    public String getPluginClass() {
        return manifest.getMainAttributes().getValue("Plugin-Class");
    }

    /**
     * Makes sure that all the dependencies exist, and then accept optional dependencies
     * as real dependencies.
     *
     * @throws IOException
     *             thrown if one or several mandatory dependencies doesn't exists.
     */
    /*package*/ void resolvePluginDependencies() throws IOException {
        List<String> missingDependencies = new ArrayList<String>();
        // make sure dependencies exist
        for (Dependency d : dependencies) {
            if (parent.getPlugin(d.shortName) == null)
                missingDependencies.add(d.toString());
        }
        if (!missingDependencies.isEmpty())
            throw new IOException("Dependency "+Util.join(missingDependencies, ", ")+" doesn't exist");

        // add the optional dependencies that exists
        for (Dependency d : optionalDependencies) {
            if (parent.getPlugin(d.shortName) != null)
                dependencies.add(d);
        }
    }

    /**
     * If the plugin has {@link #getUpdateInfo() an update},
     * returns the {@link UpdateSite.Plugin} object.
     *
     * @return
     *      This method may return null — for example,
     *      the user may have installed a plugin locally developed.
     */
    public UpdateSite.Plugin getUpdateInfo() {
        UpdateCenter uc = Hudson.getInstance().getUpdateCenter();
        UpdateSite.Plugin p = uc.getPlugin(getShortName());
        if(p!=null && p.isNewerThan(getVersion())) return p;
        return null;
    }

    /**
     * returns the {@link UpdateSite.Plugin} object, or null.
     */
    public UpdateSite.Plugin getInfo() {
        UpdateCenter uc = Hudson.getInstance().getUpdateCenter();
        return uc.getPlugin(getShortName());
    }

    /**
     * Returns true if this plugin has update in the update center.
     *
     *

     * This method is conservative in the sense that if the version number is incomprehensible,
     * it always returns false.
     */
    public boolean hasUpdate() {
        return getUpdateInfo()!=null;
    }

//
//
// Action methods
//
//
    public HttpResponse doMakeEnabled() throws IOException {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
        enable();
        return HttpResponses.ok();
    }

    public HttpResponse doMakeDisabled() throws IOException {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
        disable();
        return HttpResponses.ok();
    }

    public HttpResponse doPin() throws IOException {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
        new FileOutputStream(pinFile).close();
        return HttpResponses.ok();
    }

    public HttpResponse doUnpin() throws IOException {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);
        pinFile.delete();
        return HttpResponses.ok();
    }

    private static final Logger LOGGER = Logger.getLogger(PluginWrapper.class.getName());

}


text:
package org.apache.jackrabbit.oak.plugins.segment;

import java.util.Collections;
import java.util.UUID;

import javax.jcr.Value;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.commons.SimpleValueFactory;
import org.apache.jackrabbit.oak.api.Descriptors;
import org.apache.jackrabbit.oak.osgi.OsgiWhiteboard;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The SegmentDiscoveryLiteService is taking care of providing a repository
 * descriptor that contains the current cluster-view details.
 *

 * Note that since currently the SegmentNodeStore is not cluster-based,
 * the provided clusterView is a hard-coded one consisting only of the
 * local instance. But it is nevertheless useful for upper layer discovery.oak.
 *

 * @see DocumentDiscoveryLiteService for a more in-depth description of the discovery-lite descriptor
 */
@Component(immediate = true)
@Service(value = { SegmentDiscoveryLiteService.class })
public class SegmentDiscoveryLiteService {

    static final String COMPONENT_NAME = "org.apache.jackrabbit.oak.plugins.segment.SegmentDiscoveryLiteService";

    /**
     * Name of the repository descriptor via which the clusterView is published
     * - which is the raison d'etre of the DocumentDiscoveryLiteService
     * TODO: move this constant to a generic place for both segment and document
     **/
    public static final String OAK_DISCOVERYLITE_CLUSTERVIEW = "oak.discoverylite.clusterview";

    private static final Logger logger = LoggerFactory.getLogger(SegmentDiscoveryLiteService.class);

    /** This provides the 'clusterView' repository descriptors **/
    private class DiscoveryLiteDescriptor implements Descriptors {

        final SimpleValueFactory factory = new SimpleValueFactory();

        @Override
        public String[] getKeys() {
            return new String[] { OAK_DISCOVERYLITE_CLUSTERVIEW };
        }

        @Override
        public boolean isStandardDescriptor(String key) {
            if (!OAK_DISCOVERYLITE_CLUSTERVIEW.equals(key)) {
                return false;
            }
            return true;
        }

        @Override
        public boolean isSingleValueDescriptor(String key) {
            if (!OAK_DISCOVERYLITE_CLUSTERVIEW.equals(key)) {
                return false;
            }
            return true;
        }

        @Override
        public Value getValue(String key) {
            if (!OAK_DISCOVERYLITE_CLUSTERVIEW.equals(key)) {
                return null;
            }
            return factory.createValue(getClusterViewAsDescriptorValue());
        }

        @Override
        public Value[] getValues(String key) {
            if (!OAK_DISCOVERYLITE_CLUSTERVIEW.equals(key)) {
                return null;
            }
            return new Value[] { getValue(key) };
        }

    }

    /**
     * Require a static reference to the NodeStore. Note that this implies the
     * service is only active for segmentNS (which is the idea)
     **/
    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY, policy = ReferencePolicy.STATIC)
    private volatile NodeStore nodeStore;

    private final String runtimeClusterId = UUID.randomUUID().toString();

    /**
     * returns the clusterView as a json value for it to be provided via the
     * repository descriptor
     **/
    private String getClusterViewAsDescriptorValue() {
        // since currently segment node store is not running in a cluster
        // we can hard-code a single-vm descriptor here:
        // {"seq":4,"final":true,"me":1,"active":[1],"deactivating":[],"inactive":[2]}
        // OAK-3672 : 'id' is now allowed to be null (supported by upper layers),
        //            and for tarMk we're doing exactly that (id==null) - indicating
        //            to upper layers that we're not really in a cluster and that
        //            this low level descriptor doesn't manage the 'cluster id'
        //            in such a case.
        return "{\"seq\":1,\"final\":true,\"me\":1,\"active\":[1],\"deactivating\":[],\"inactive\":[]}";
    }

    /**
     * On activate the SegmentDiscoveryLiteService registers
     * the descriptor
     */
    @Activate
    public void activate(ComponentContext context) {
        logger.trace("activate: start");

        //TODO: i have a feeling this could be done nicer
        // but doing a reference to the ProxyNodeStore wouldn't be accurate enough
        // and since the SegmentNodeStore is not directly registered with osgi
        // can't refer to that - so that's why there's currently this ugly fallback
        final boolean weAreOnSegment;
        if (nodeStore instanceof SegmentNodeStore) {
            // this would currently never happen - but would be straight forward,
            // so support it
            weAreOnSegment = true;
        } else if (nodeStore instanceof SegmentNodeStoreService) {
            // this is the normal case for tarMk

            // could also test if it's a ProxyNodeStore - but
            // that one doesn't currently allow access to the delegate
            // so go directly to SegmentNodeStoreService
            weAreOnSegment = true;
        } else {
            // this is the case for DocumentNodeStore for example
            weAreOnSegment = false;
        }

        if (!weAreOnSegment) {
            // then disable the SegmentDiscoveryLiteService
            logger.info("activate: nodeStore is not a SegmentNodeStore, thus disabling: " + COMPONENT_NAME);
            context.disableComponent(COMPONENT_NAME);
            return;
        }

        // register the Descriptors - for Oak to pass it upwards
        if (context != null) {
            OsgiWhiteboard whiteboard = new OsgiWhiteboard(context.getBundleContext());
            whiteboard.register(Descriptors.class, new DiscoveryLiteDescriptor(), Collections.emptyMap());
        }
        logger.trace("activate: end");
    }

}


text:
package macaron

import (
	"fmt"
	"log"
	"net/http"
	"reflect"
	"runtime"
	"time"
)

var (
	ColorLog      = true
	LogTimeFormat = "2006-01-02 15:04:05"
)

func init() {
	ColorLog = runtime.GOOS != "windows"
}

// LoggerInvoker is an inject.FastInvoker wrapper of func(ctx *Context, log *log.Logger).
type LoggerInvoker func(ctx *Context, log *log.Logger)

func (invoke LoggerInvoker) Invoke(params []interface{}) ([]reflect.Value, error) {
	invoke(params[0].(*Context), params[1].(*log.Logger))
	return nil, nil
}

// Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
func Logger() Handler {
	return func(ctx *Context, log *log.Logger) {
		start := time.Now()

		log.Printf("%s: Started %s %s for %s", time.Now().Format(LogTimeFormat), ctx.Req.Method, ctx.Req.RequestURI, ctx.RemoteAddr())

		rw := ctx.Resp.(ResponseWriter)
		ctx.Next()

		content := fmt.Sprintf("%s: Completed %s %v %s in %v", time.Now().Format(LogTimeFormat), ctx.Req.RequestURI, rw.Status(), http.StatusText(rw.Status()), time.Since(start))
		if ColorLog {
			switch rw.Status() {
			case 200, 201, 202:
				content = fmt.Sprintf("\033[1;32m%s\033[0m", content)
			case 301, 302:
				content = fmt.Sprintf("\033[1;37m%s\033[0m", content)
			case 304:
				content = fmt.Sprintf("\033[1;33m%s\033[0m", content)
			case 401, 403:
				content = fmt.Sprintf("\033[4;31m%s\033[0m", content)
			case 404:
				content = fmt.Sprintf("\033[1;31m%s\033[0m", content)
			case 500:
				content = fmt.Sprintf("\033[1;36m%s\033[0m", content)
			}
		}
		log.Println(content)
	}
}