text:
package com.ericsson.ei.services;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ericsson.ei.handlers.EventHandler;
import com.ericsson.ei.handlers.EventToObjectMapHandler;
import com.ericsson.ei.jmespath.JmesPathInterface;
import com.ericsson.ei.queryservice.ProcessAggregatedObject;
import com.fasterxml.jackson.core.JsonProcessingException;

@Component
public class RuleCheckService implements IRuleCheckService {

    @Autowired
    JmesPathInterface jmesPathInterface;

    @Autowired
    EventHandler eventHandler;

    @Autowired
    private ProcessAggregatedObject processAggregatedObject;

    @Autowired
    EventToObjectMapHandler eventToObjectMapHandler;

    private static final Logger LOGGER = LoggerFactory.getLogger(RuleCheckService.class);

    @Override
    public String prepareAggregatedObject(String listRulesJson, String listEventsJson)
            throws JSONException, JsonProcessingException, IOException {
        JSONArray rulesList = new JSONArray(listRulesJson);
        JSONArray eventsList = new JSONArray(listEventsJson);
        eventHandler.getRulesHandler().setParsedJson(rulesList.toString());
        String response = null;
        // Looping all events and add suffix template name to id and links, For
        // identifying the test aggregated events.
        HashSet<String> templateNames = new HashSet<>();
        for (int i = 0; i < eventsList.length(); i++) {
            String templateName = jmesPathInterface
                    .runRuleOnEvent("TemplateName", rulesList.getJSONObject(i).toString()).asText("TEST");
            templateNames.add(templateName);
            if (templateNames.size() == 1) {
                addTemplateNameToIds(eventsList.getJSONObject(i), templateName);
                LOGGER.debug("event to prepare aggregated object :: " + eventsList.getJSONObject(i).toString());
                eventHandler.eventReceived(eventsList.getJSONObject(i).toString());
            }
        }

        String templateName = templateNames.iterator().next();
        if (templateNames.size() == 1) {
            ArrayList<String> responseList = processAggregatedObject.getAggregatedObjectByTemplateName(templateName);
            response = responseList.toString();
        } else {
            response = "Multipul template names are not allowed, Please use single name for all rules.";
        }
        // Delete the aggregated object
        processAggregatedObject.deleteAggregatedObject(templateName);
        // Delete the event object mapper
        eventToObjectMapHandler.deleteEventObjectMap(templateName);
        return response;
    }

    private void addTemplateNameToIds(JSONObject jsonObject, final String templateName) throws JSONException {
        String idTemplateSuffix = jmesPathInterface.runRuleOnEvent("meta.id", jsonObject.toString()).asText() + "_"
                + templateName;
        jsonObject.getJSONObject("meta").put("id", idTemplateSuffix);
        for (int i = 0; i < jsonObject.getJSONArray("links").length(); i++) {
            JSONObject link = jsonObject.getJSONArray("links").getJSONObject(i);
            link.put("target", link.getString("target") + "_" + templateName);
        }
    }
}


text:
from __future__ import print_function
import os
import vtk

# Read the data
os.chdir(os.path.dirname(__file__))
pl3d = vtk.vtkMultiBlockPLOT3DReader()
xyx_file = "volume/combxyz.bin"
q_file = "volume/combq.bin"
pl3d.SetXYZFileName(xyx_file)
pl3d.SetQFileName(q_file)
pl3d.SetScalarFunctionNumber(100)
pl3d.SetVectorFunctionNumber(202)
pl3d.Update()

blocks = pl3d.GetOutput()
b0 = blocks.GetBlock(0)

# Setup VTK environment
renderer = vtk.vtkRenderer()
render_window = vtk.vtkRenderWindow()
render_window.AddRenderer(renderer)
interactor = vtk.vtkRenderWindowInteractor()
interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera())
render_window.SetInteractor(interactor)
renderer.SetBackground(0.2,0.2,0.2)
interactor.Initialize()

# Draw Outline
outline = vtk.vtkStructuredGridOutlineFilter()
outline.SetInputData(b0)
outline_mapper = vtk.vtkPolyDataMapper()
outline_mapper.SetInputConnection(outline.GetOutputPort())
outline_actor = vtk.vtkActor()
outline_actor.SetMapper(outline_mapper)
outline_actor.GetProperty().SetColor(1,1,1)
renderer.AddActor(outline_actor)
renderer.ResetCamera()

# Threshold points
threshold = vtk.vtkThresholdPoints()
threshold.SetInputData(b0)
threshold.ThresholdByUpper(0.5)

# Draw arrows
arrow = vtk.vtkArrowSource()
glyphs = vtk.vtkGlyph3D()
glyphs.SetInputData(b0)
glyphs.SetSourceConnection(arrow.GetOutputPort())
glyphs.SetInputConnection(threshold.GetOutputPort())

glyphs.SetVectorModeToUseVector()
glyphs.SetScaleModeToScaleByVector()
glyphs.SetScaleFactor(0.005)
glyphs.SetColorModeToColorByVector()

# Mapper
glyph_mapper =  vtk.vtkPolyDataMapper()
glyph_mapper.SetInputConnection(glyphs.GetOutputPort())
glyph_actor = vtk.vtkActor()
glyph_actor.SetMapper(glyph_mapper)

glyph_mapper.UseLookupTableScalarRangeOn()
renderer.AddActor(glyph_actor)

# Set color lookuptable
glyphs.Update()
s0,sf = glyphs.GetOutput().GetScalarRange()
lut = vtk.vtkColorTransferFunction()
lut.AddRGBPoint(s0, 1,0,0)
lut.AddRGBPoint(sf, 0,1,0)
glyph_mapper.SetLookupTable(lut)

interactor.Start()

redpajama_set_name: RedPajamaGithub


text:
<?php

class BlowAuth
{
    public $oauth_version = '1.0';
    public $signature_method = 'HMAC-SHA1';

    public $scope_url = null;

    protected $oauth_base_url;
    protected $api_base_url;

    protected $consumer_key;
    protected $consumer_secret;

    protected $token;
    protected $token_secret;

    protected $curl_timeout_ms = 10000;
    protected $curl_connecttimeout_ms = 10000;

    protected $request_token_url;
    protected $access_token_url;
    protected $authenticate_url;
    protected $authorize_url;

    public function getRequestToken($oauth_callback = null)
    {
        $params = array();
        if (!is_null($oauth_callback)) {
            $params['oauth_callback'] = $oauth_callback;
        }

        if (!is_null($this->scope_url)) {
            $params['scope'] = $this->scope_url;
        }

        $response = $this->makeOAuthRequest($this->request_token_url, 'GET', $params);
        $raw_credentials = explode('&', $response);

        $credentials = array();
        foreach ($raw_credentials as $cred_str) {
            $curr_cred = explode('=', $cred_str);
            $credentials[$curr_cred[0]] = rawurldecode($curr_cred[1]);
        }

        return $credentials;
    }

    public function getAccessToken($oauth_verifier)
    {
        $params = array(
            'oauth_verifier'        => $oauth_verifier,
        );
        $response = $this->makeOAuthRequest($this->access_token_url, 'GET', $params);

        $raw_credentials = explode('&', $response);

        $credentials = array();
        foreach ($raw_credentials as $cred_str) {
            $curr_cred = explode('=', $cred_str);
            $credentials[$curr_cred[0]] = rawurldecode($curr_cred[1]);
        }

        return $credentials;
    }

    public function request($api_method, $http_method = 'GET', $extra_params = array(), $POST_body = '', $exclude_non_oauth_params_from_sig = false)
    {
        $request_url = "{$this->api_base_url}/{$api_method}";
        return $this->makeOAuthRequest($request_url, $http_method, $extra_params, $POST_body, $exclude_non_oauth_params_from_sig);
    }

    protected function makeOAuthRequest($url, $method, $extra_params = array(), $POST_body = '', $exclude_non_oauth_params_from_sig = false)
    {
        $base_params = array(
            'oauth_consumer_key'        => $this->consumer_key,
            'oauth_nonce'               => $this->getOAuthNonce(),
            'oauth_signature_method'    => $this->signature_method,
            'oauth_timestamp'           => $this->getOAuthTimestamp(),
            'oauth_version'             => $this->oauth_version,
        );

        if (isset($this->token)) {
            $base_params['oauth_token'] = $this->token;
        }

        $params = array_merge($base_params, $extra_params);

        $params['oauth_signature'] = $this->getOAuthSignature($method, $url, $params, $exclude_non_oauth_params_from_sig);

        $ci = curl_init();

        $auth_header_params_str = '';
        foreach ($base_params as $name => $value) {
            $auth_header_params_str .= " $name=\"" . rawurlencode($value) . "\",";
        }
        $auth_header_params_str .= ' oauth_signature="' . rawurlencode($params['oauth_signature']) . '"';
        $header_arr = array("Authorization: OAuth $auth_header_params_str");

        // TODO: do it this way with PHP 5.3.6
        //$query_str = http_build_query($extra_params, '', '&', 'PHP_QUERY_RFC3986');
        if (!empty($extra_params)) {
            $query_str = str_replace('+', '%20', http_build_query($extra_params));
        }

            //curl_setopt($ci, CURLOPT_HEADER, true);

        if ($method == 'POST') {
            curl_setopt($ci, CURLOPT_POST, TRUE);
            if (!empty($extra_params)) {
                curl_setopt($ci, CURLOPT_POSTFIELDS, $query_str);
                // in case of twitter media upload, we need the raw array
                if (isset($extra_params['media[]'])) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $extra_params);
                    $header_arr[] = 'Expect:';
                }
            } else if ($POST_body) {
                // I think this header was for some LinkedIn method. if it turns out
                // that some LI method doesn't work, pass the below header in with the
                // request() function call
                //$header_arr[] = 'Content-Type: text/xml';
                curl_setopt($ci, CURLOPT_POSTFIELDS, $POST_body);
                // TODO: set CURLOPT_HEADER only in the LinkedIn case.
                // The meaningful info for these types of requests are in the
                // response headers, not the response body.
                curl_setopt($ci, CURLOPT_HEADER, true);
            }
        } else if ($method == 'GET' && isset($query_str)) {
            $url .= "?$query_str";
        }

        curl_setopt($ci, CURLOPT_HTTPHEADER, $header_arr);
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_TIMEOUT_MS, $this->curl_timeout_ms);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT_MS, $this->curl_connecttimeout_ms);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ci);
        curl_close ($ci);

        return $response;
    }

    protected function getOAuthNonce()
    {
        $mt = microtime();
        $rand = mt_rand();

        return md5($mt . $rand);
    }

    protected function getOAuthTimestamp()
    {
        return time();
    }

    protected function getOAuthSignature($method, $url, $params, $exclude_non_oauth_params_from_sig = false)
    {
        ksort($params);
        if ($exclude_non_oauth_params_from_sig) {
            foreach ($params as $key => $val) {
                if (strpos($key, 'oauth_') !== 0) {
                    unset($params[$key]);
                }
            }
        }

        $base_string = $method . '&'
                       . rawurlencode($url) . '&'
                       // TODO: get rid of str replace and use $enc_type after PHP 5.3.6
                       . $this->OAuthRawUrlEncode(str_replace('+', '%20', http_build_query($params)));

        $oauth_token_secret = '';
        if (isset($this->token_secret)) {
            $oauth_token_secret = $this->token_secret;
        }

        $key = rawurlencode($this->consumer_secret) . '&' . rawurlencode($oauth_token_secret);
        return base64_encode(hash_hmac('sha1', $base_string, $key, true));
    }

    public function getAuthorizeUrl($credentials)
    {
        $query_str = "oauth_token={$credentials['oauth_token']}";
        return $this->authorize_url . "?$query_str";
    }

    public function getAuthenticateUrl($credentials)
    {
        $query_str = "oauth_token={$credentials['oauth_token']}";
        return $this->authenticate_url . "?$query_str";
    }

    private function OAuthRawUrlEncode($text) {
        $tildefied_text = str_replace('%7E', '~', $text);
        return str_replace('%7E', '~', rawurlencode($tildefied_text));
    }

}

?>


text:
FILE* log;

typedef enum{
  GRASS,
  BLOCK,
  WALL,
  BOMB,
  BOX
}TILES;

//Entities
typedef struct _Entity{
  int x;
  int y;
  ALLEGRO_BITMAP* sprite;
}ENTITY;

typedef struct _Explosion{
  ENTITY entity;
  short radius;
  short currFrame;
  short currDelay;
  short frameDelay;
  short maxFrame;
  bool isLive;
  int horizontalB;
  int horizontalF;
  int verticalB;
  int verticalF;
}EXPLOSION;

typedef struct _Bomb{
  ENTITY entity;
  EXPLOSION  explosion;
  short maxTime;
  short currTime;
  short radius;
  bool isLive;

}BOMBS;

typedef struct _Player{
  ENTITY entity;
  BOMBS bombs[5];
  short maxBombs;
  bool isAlive;
}PLAYER;

void TryToMovePlayer(ENTITY *player,int key, TILES map[15][13],PLAYER* pl);
void MoveHorizontal(ENTITY* player,bool forward, TILES map[15][13]);
void MoveVertical(ENTITY* player,bool forward, TILES map[15][13]);
void CheckIfAlive(PLAYER* player, EXPLOSION explosion);
void InitPlayer(PLAYER* player);

void CreateMap(TILES map[15][13]);//Creates the map
void DrawMap(TILES map[15][13],ALLEGRO_BITMAP* tileMap); //Draws Map

void InitBombs(BOMBS bombs[5],ALLEGRO_BITMAP* bombSprite,ALLEGRO_BITMAP* expSprite,bool first);
void PlaceBomb(PLAYER* player, TILES map[15][13]);
void DrawBomb(BOMBS bombs[5]);
void UpdateBomb(BOMBS bombs[5],TILES map[15][13],PLAYER* player);
void ExplodeBomb(BOMBS *bomb,TILES map[15][13],PLAYER* player);

void CreateExplosion(BOMBS bomb, EXPLOSION* explosion);
void UpdateExplosion(BOMBS bombs[5]);
void DrawExplosion(BOMBS bombs[5]);


text:
package featurescomparison.workingwithdocuments.formattext.java;

import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class ApacheFormattedText
{
	public static void main(String[] args) throws Exception
	{
		String dataPath = "src/featurescomparison/workingwithdocuments/formattext/data/";

		// Create a new document from scratch
        XWPFDocument doc = new XWPFDocument();

        // create paragraph
        XWPFParagraph para = doc.createParagraph();

        // create a run to contain the content
        XWPFRun rh = para.createRun();

        // Format as desired
    	rh.setFontSize(15);
    	rh.setFontFamily("Verdana");
        rh.setText("This is the formatted Text");
        rh.setColor("fff000");
        para.setAlignment(ParagraphAlignment.RIGHT);

        // write the file
        FileOutputStream out = new FileOutputStream(dataPath + "Apache_FormattedText_Out.docx");
        doc.write(out);
        out.close();

        System.out.println("Process Completed Successfully");
	}
}


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class engineering
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.DataView1 = New System.Data.DataView
        Me.TextBox1 = New System.Windows.Forms.TextBox
        Me.Database1DataSet = New WindowsApplication1.Database1DataSet
        Me.Gsf2BindingSource = New System.Windows.Forms.BindingSource(Me.components)
        Me.Gsf2TableAdapter = New WindowsApplication1.Database1DataSetTableAdapters.gsf2TableAdapter
        Me.TableAdapterManager = New WindowsApplication1.Database1DataSetTableAdapters.TableAdapterManager
        CType(Me.DataView1, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.Database1DataSet, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.Gsf2BindingSource, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'DataView1
        '
        Me.DataView1.Table = Me.Database1DataSet.gsf2
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(36, 47)
        Me.TextBox1.Multiline = True
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.Size = New System.Drawing.Size(178, 198)
        Me.TextBox1.TabIndex = 0
        '
        'Database1DataSet
        '
        Me.Database1DataSet.DataSetName = "Database1DataSet"
        Me.Database1DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema
        '
        'Gsf2BindingSource
        '
        Me.Gsf2BindingSource.DataMember = "gsf2"
        Me.Gsf2BindingSource.DataSource = Me.Database1DataSet
        '
        'Gsf2TableAdapter
        '
        Me.Gsf2TableAdapter.ClearBeforeFill = True
        '
        'TableAdapterManager
        '
        Me.TableAdapterManager.BackupDataSetBeforeUpdate = False
        Me.TableAdapterManager.gsf2TableAdapter = Me.Gsf2TableAdapter
        Me.TableAdapterManager.gsfTableAdapter = Nothing
        Me.TableAdapterManager.UpdateOrder = WindowsApplication1.Database1DataSetTableAdapters.TableAdapterManager.UpdateOrderOption.InsertUpdateDelete
        '
        'engineering
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(455, 266)
        Me.Controls.Add(Me.TextBox1)
        Me.Name = "engineering"
        Me.Text = "engineering"
        CType(Me.DataView1, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.Database1DataSet, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.Gsf2BindingSource, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents DataView1 As System.Data.DataView
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents Database1DataSet As WindowsApplication1.Database1DataSet
    Friend WithEvents Gsf2BindingSource As System.Windows.Forms.BindingSource
    Friend WithEvents Gsf2TableAdapter As WindowsApplication1.Database1DataSetTableAdapters.gsf2TableAdapter
    Friend WithEvents TableAdapterManager As WindowsApplication1.Database1DataSetTableAdapters.TableAdapterManager
End Class


text:
class OperationsController < ApplicationController
  def new
    player = Player.find(params[:player_id])

    game = player.game.with_lock do
      operation = player.operations.create!(operation_params)

      game = operation.player.game
      AdvanceGame.new(game).call
      game
    end

    redirect_to game
  end

  private

  def operation_params
    params.permit(:operation_type, :suit, :rank)
  end
end


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

	<Sentence>
		<value>The connective tissue of the eyelid becomes weaker, which causes the lid to turn out so that the edge of the lower lid is no longer against the eyeball.</value>
		<pattern_crowdsource> The [[connective tissue|C0009780]] of the [[eyelid|C1280734]] becomes weaker, which causes the lid to turn out so that the edge of the lower lid is no longer against the eyeball.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>connective tissue</surface-form>
				<RDF-ID>C0009780</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eyelid</surface-form>
				<RDF-ID>C1280734</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>weaker</surface-form>
				<RDF-ID>C0004093</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>turn</surface-form>
				<RDF-ID>C0541749</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>out</surface-form>
				<RDF-ID>C0439787</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>lower</surface-form>
				<RDF-ID>C0441994</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>longer</surface-form>
				<RDF-ID>C0205166</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eyeball</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0009780 PART_OF C1280734</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Symptoms include:  - Dry, painful eyes  - Excess tearing of the eye (epiphora)  - Eyelid turns outward  - Long-term (chronic) conjunctivitis  - Keratitis  - Redness of the lid and white part of the eye</value>
		<pattern_crowdsource> Symptoms include:  - Dry, painful eyes  - [[Excess tearing|C0152227]] of the [[eye|C0015392]] (epiphora)  - Eyelid turns outward  - Long-term (chronic) conjunctivitis  - Keratitis  - Redness of the lid and white part of the eye		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Symptoms</surface-form>
				<RDF-ID>C1457887</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>painful</surface-form>
				<RDF-ID>C0030193</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Dry, painful eyes</surface-form>
				<RDF-ID>C0314719</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Excess tearing</surface-form>
				<RDF-ID>C0152227</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>epiphora</surface-form>
				<RDF-ID>C0152227</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Eyelid</surface-form>
				<RDF-ID>C1280734</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>outward</surface-form>
				<RDF-ID>C0439788</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Long-term</surface-form>
				<RDF-ID>C0443252</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>chronic</surface-form>
				<RDF-ID>C0205191</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>conjunctivitis</surface-form>
				<RDF-ID>C0009763</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Keratitis</surface-form>
				<RDF-ID>C0022568</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Redness</surface-form>
				<RDF-ID>C0332575</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>white</surface-form>
				<RDF-ID>C0007457</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>part</surface-form>
				<RDF-ID>C0449719</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0015392 LOCATION_OF C0152227</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Call your health care provider if you have symptoms of ectropion.</value>
		<pattern_crowdsource> Call your [[health care provider|C0018724]] if you have [[symptoms|C1457887]] of ectropion.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>health care provider</surface-form>
				<RDF-ID>C0018724</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>symptoms</surface-form>
				<RDF-ID>C1457887</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>ectropion</surface-form>
				<RDF-ID>C0013592</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C1457887 PROCESS_OF C0018724</triple>
		</triples>
	</Sentence>

</Document>


text:
<?php

/**
 * Gets/sets various internal readline variables
 *
 * @phpstub
 *
 * @param string $varname
 * @param string $newvalue
 *
 * @return mixed If called with no parameters, this function returns an array of
 *               values for all the setting readline uses.  The elements will
 *               be indexed by the following values: done, end, erase_empty_line,
 *               library_version, line_buffer, mark, pending_input, point, prompt,
 *               readline_name, and terminal_name.
 */
function readline_info($varname = NULL, $newvalue = NULL)
{
}


text:
namespace em = enterprise_management;

namespace chromeos {

class LoginScreenPolicyTest : public policy::DevicePolicyCrosBrowserTest {
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    command_line->AppendSwitch(switches::kLoginManager);
    command_line->AppendSwitch(::switches::kEnableManagedUsers);
  }

  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    InstallOwnerKey();
    MarkAsEnterpriseOwned();
    DevicePolicyCrosBrowserTest::SetUpInProcessBrowserTestFixture();
  }
};

IN_PROC_BROWSER_TEST_F(LoginScreenPolicyTest, DisableSupervisedUsers) {
  EXPECT_FALSE(chromeos::UserManager::Get()->AreLocallyManagedUsersAllowed());

  scoped_refptr<content::MessageLoopRunner> runner(
      new content::MessageLoopRunner);
  scoped_ptr<CrosSettings::ObserverSubscription> subscription(
      chromeos::CrosSettings::Get()->AddSettingsObserver(
          chromeos::kAccountsPrefSupervisedUsersEnabled,
          runner->QuitClosure()));

  em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
  proto.mutable_supervised_users_settings()->set_supervised_users_enabled(true);
  RefreshDevicePolicy();

  runner->Run();

  EXPECT_TRUE(chromeos::UserManager::Get()->AreLocallyManagedUsersAllowed());
}

}  // namespace chromeos


text:
#include "tensorflow/core/framework/graph_to_functiondef.h"

#include "tensorflow/cc/framework/ops.h"
#include "tensorflow/cc/ops/function_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/framework/function_testlib.h"
#include "tensorflow/core/graph/graph_constructor.h"
#include "tensorflow/core/graph/graph_def_builder.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/util/equal_graph_def.h"

namespace tensorflow {
namespace {

FunctionDef RemoveDebugInfo(const FunctionDef& def) {
  FunctionDef copy = def;
  for (auto& node_def : *copy.mutable_node_def()) {
    node_def.clear_experimental_debug_info();
  }
  return copy;
}

bool EqualFunctionDef(const FunctionDef& a, const FunctionDef& b,
                      string* diff) {
  // TODO(phawkins) use a more sophisticated equality test.
  if (a.DebugString() != b.DebugString()) {
    if (diff) {
      *diff = strings::StrCat("Definition mismatch for function ",
                              a.signature().name(), ":\n", a.DebugString(),
                              "\n ---- vs. ----\n", b.DebugString());
    }
    return false;
  }
  return true;
}

TEST(GraphToFunctionDefTest, Basics) {
  Scope root = Scope::NewRootScope().ExitOnError();
  auto a = ops::_Arg(root.WithOpName("A"), DT_FLOAT, 0);
  auto b = ops::_Arg(root.WithOpName("B"), DT_FLOAT, 1);
  auto c = ops::_Arg(root.WithOpName("C"), DT_FLOAT, 2);
  auto d = ops::Add(root.WithOpName("D"), a, b);
  auto e = ops::Add(root.WithOpName("b"), d, c);
  auto f = ops::Neg(root.WithOpName("h"), e);
  auto g = ops::AddN(root.WithOpName("G"), std::initializer_list<Output>{e, f});
  auto h = ops::_Retval(root.WithOpName("H"), g, 0);

  GraphDef graph_def;
  TF_EXPECT_OK(root.ToGraphDef(&graph_def));

  std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
  GraphConstructorOptions options;
  TF_EXPECT_OK(ConvertGraphDefToGraph(options, graph_def, graph.get()));

  FunctionDef fdef;
  TF_EXPECT_OK(GraphToFunctionDef(*graph, "test_fn", &fdef));

  FunctionDef fdef_expected = FunctionDefHelper::Create(
      "test_fn",                             // function name
      {"a: float", "b: float", "c: float"},  // inputs
      {"h_0: float"},                        // outputs
      {},                                    // attrs
      {
          // nodes in the function body
          {{"D"}, "Add", {"a", "b"}, {{"T", DT_FLOAT}}},
          {{"b_0"}, "Add", {"D:z:0", "c"}, {{"T", DT_FLOAT}}},
          {{"h"}, "Neg", {"b_0:z:0"}, {{"T", DT_FLOAT}}},
          {{"G"}, "AddN", {"b_0:z:0", "h:y:0"}, {{"N", 2}, {"T", DT_FLOAT}}},
      },
      {{"h_0", "G:sum:0"}});  // return values

  string diff;
  bool fdefs_equal =
      EqualFunctionDef(fdef_expected, RemoveDebugInfo(fdef), &diff);
  EXPECT_TRUE(fdefs_equal) << diff;
}

// Regression test for a crash if there was a control edge to a _Retval node.
TEST(GraphToFunctionDefTest, ControlDependencies) {
  Scope root = Scope::NewRootScope().ExitOnError();
  auto a = ops::_Arg(root.WithOpName("a"), DT_FLOAT, 0);
  auto b = ops::Neg(root.WithOpName("b").WithControlDependencies(a), a);
  auto c = ops::_Retval(root.WithOpName("c").WithControlDependencies(b), b, 0);

  GraphDef graph_def;
  TF_EXPECT_OK(root.ToGraphDef(&graph_def));

  std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
  GraphConstructorOptions options;
  TF_EXPECT_OK(ConvertGraphDefToGraph(options, graph_def, graph.get()));

  FunctionDef fdef;
  TF_EXPECT_OK(GraphToFunctionDef(*graph, "test_fn", &fdef));

  FunctionDef fdef_expected = FunctionDefHelper::Create(
      "test_fn",     // function name
      {"a: float"},  // inputs
      {"c: float"},  // outputs
      {},            // attrs
      {
          // nodes in the function body
          {{"b"}, "Neg", {"a", "^a"}, {{"T", DT_FLOAT}}},
      },
      {{"c", "b:y:0"}});  // return values

  string diff;
  bool fdefs_equal =
      EqualFunctionDef(fdef_expected, RemoveDebugInfo(fdef), &diff);
  EXPECT_TRUE(fdefs_equal) << diff;
}

TEST(GraphToFunctionDefTest, ControlOutputs) {
  Scope root = Scope::NewRootScope().ExitOnError();
  auto a = ops::_Arg(root.WithOpName("a"), DT_FLOAT, 0);
  auto b = ops::Neg(root.WithOpName("b"), a);
  auto c = ops::_Retval(root.WithOpName("c"), b, 0);

  GraphDef graph_def;
  TF_EXPECT_OK(root.ToGraphDef(&graph_def));

  std::unique_ptr<Graph> graph(new Graph(OpRegistry::Global()));
  GraphConstructorOptions options;
  TF_EXPECT_OK(ConvertGraphDefToGraph(options, graph_def, graph.get()));

  // Add a 'b' node to the control return set.
  const auto control_ret = [](const Node* n) -> absl::optional<string> {
    if (n->name() == "b") return absl::make_optional<string>("must_execute");
    return absl::nullopt;
  };

  FunctionDef fdef;
  TF_EXPECT_OK(GraphToFunctionDef(*graph, "test_fn", control_ret, &fdef));

  FunctionDef fdef_expected =
      FunctionDefHelper::Create("test_fn",     // function name
                                {"a: float"},  // inputs
                                {"c: float"},  // outputs
                                {},            // attrs
                                {
                                    // nodes in the function body
                                    {{"b"}, "Neg", {"a"}, {{"T", DT_FLOAT}}},
                                },
                                {{"c", "b:y:0"}},          // return values
                                {{"must_execute", "b"}});  // control returns

  string diff;
  bool fdefs_equal =
      EqualFunctionDef(fdef_expected, RemoveDebugInfo(fdef), &diff);
  EXPECT_TRUE(fdefs_equal) << diff;
}

}  // namespace
}  // namespace tensorflow


text:
/**
 * Wrapper around server to allow babel/jsx/es6 > compilation.
 */
require('babel-core/register');
const logger = require('winston');
const server = require('./server.jsx');
const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {
  logger.info(`Server listening on, ${PORT}`);
});


text:
/*
20110505 rsz Created.
*/
#include <stdio.h>
#include "ezOptionParser.hpp"

using namespace ez;

int main(int argc, const char * argv[]) {
	ezOptionParser opt;

	opt.overview = "Full demo of all the features.";
	opt.syntax = "full [OPTIONS]";
	opt.example = "full -h\n\n";
	opt.footer = "full v0.1.4 Copyright (C) 2011 Remik Ziemlinski\nThis program is free and without warranty.\n";

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Print this usage message in one of three different layouts. The choices are:\n0 - aligned (default)\n1 - interleaved\n2 - staggered", // Help description.
		"-h",     // Flag token.
		"-help", // Flag token.
		"--help", // Flag token.
		"--usage" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		0, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Do not print all input arguments for test. By default, all the inputs will be pretty printed to show which category they belong to (first, options, last) and what their values are. This shows that flag names can be arbitrary and don't need to begin with a single or double dash (-,--).", // Help description.
		"+d",     // Flag token.
		"+dbg",  // Flag token.
		"+debug" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Test integer input.", // Help description.
		"-n",     // Flag token.
		"-int", 	// Flag token.
		"--int", 	// Flag token.
		"--integer" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Test long input.", // Help description.
		"-l",     // Flag token.
		"-lng", 	// Flag token.
		"-long", 	// Flag token.
		"--long" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Test unsigned long input.", // Help description.
		"-u",     // Flag token.
		"-ulong", // Flag token.
		"--ulong" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Test float input.", // Help description.
		"-f",     // Flag token.
		"-flt", 	// Flag token.
		"-float", // Flag token.
		"--float" // Flag token.
	);

	opt.add(
		"0", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Test double input.", // Help description.
		"-d",     // Flag token.
		"-dbl", 	// Flag token.
		"-double", // Flag token.
		"--double" // Flag token.
	);

	opt.add(
		"A default string.", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Test string input.", // Help description.
		"-s",     // Flag token.
		"-str", 	// Flag token.
		"-string", 	// Flag token.
		"--string" // Flag token.
	);

	opt.add(
		"0,1,2,3,4,5,6,7,8,9,10", // Default.
		0, // Required?
		1, // Number of args expected.
		',', // Delimiter if expecting multiple args.
		"Test integer list input delimited with comma.", // Help description.
		"-nl",     // Flag token.
		"-nlist", 	// Flag token.
		"-intlist", 	// Flag token.
		"--intlist" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		':', // Delimiter if expecting multiple args.
		"Test long list input delimited by colon.", // Help description.
		"-ll",     // Flag token.
		"-llist", 	// Flag token.
		"-longlist", 	// Flag token.
		"--longlist" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		',', // Delimiter if expecting multiple args.
		"Test unsigned long list input.", // Help description.
		"-ul",     // Flag token.
		"-ulist", 	// Flag token.
		"-ulonglist", 	// Flag token.
		"--ulonglist" // Flag token.
	);

	opt.add(
		"-2.1e-20,-.2,-.001,0,1,1e10", // Default.
		0, // Required?
		1, // Number of args expected.
		',', // Delimiter if expecting multiple args.
		"Test float list input.", // Help description.
		"-fl",     // Flag token.
		"-flist", 	// Flag token.
		"-floatlist", 	// Flag token.
		"--floatlist" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		',', // Delimiter if expecting multiple args.
		"Test double list input.", // Help description.
		"-dl",     // Flag token.
		"-dlist", 	// Flag token.
		"-dbllist", 	// Flag token.
		"--doublelist" // Flag token.
	);

	opt.add(
		"\"string list item1\",item2,\"list # item3\",2000/1/1", // Default.
		0, // Required?
		1, // Number of args expected.
		',', // Delimiter if expecting multiple args.
		"Test string list input.", // Help description.
		"-sl",     // Flag token.
		"-slist", 	// Flag token.
		"-strlist", 	// Flag token.
		"--strlist" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Import additional arguments from file. Multiple files can be imported by using multiple instances of this option. The file options will add to those set on the command line. If you want them to overwrite the command line options, then use +import.", // Help description.
		"-i",     // Flag token.
		"-import" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Import additional arguments from file. Multiple files can be imported by using multiple instances of this option. The last file will overwrite all options set previously by either command line or another file. If you want them to add to previously set options, then use -import.", // Help description.
		"+i",     // Flag token.
		"+import" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Export only set arguments to file.", // Help description.
		"-e",     // Flag token.
		"-export" // Flag token.
	);

	opt.add(
		"", // Default.
		0, // Required?
		1, // Number of args expected.
		0, // Delimiter if expecting multiple args.
		"Export all arguments, including defaults, to file.", // Help description.
		"+e",     // Flag token.
		"+export" // Flag token.
	);

	opt.parse(argc, argv);

	if (opt.isSet("-h")) {
		std::string usage;
		int layout;
		opt.get("-h")->getInt(layout);
		switch(layout) {
		case 0:
			opt.getUsage(usage,80,ezOptionParser::ALIGN);
			break;
		case 1:
			opt.getUsage(usage,80,ezOptionParser::INTERLEAVE);
			break;
		case 2:
			opt.getUsage(usage,80,ezOptionParser::STAGGER);
			break;
		}
		std::cout << usage;
		return 1;
	}

	if (opt.isSet("-i")) {
		// Import one or more files that use # as comment char.
		std::vector< std::vector<std::string> > files;
		opt.get("-i")->getMultiStrings(files);

		for(int j=0; j < files.size(); ++j)
			if (! opt.importFile(files[j][0].c_str(), '#'))
				std::cerr << "ERROR: Failed to open file " << files[j][0] << std::endl;
	}

	if (opt.isSet("+i")) {
		// Import one or more files that use # as comment char.
		std::vector< std::vector<std::string> > files;
		opt.get("+i")->getMultiStrings(files);

		if(!files.empty()) {
			std::string file = files[files.size()-1][0];
			opt.resetArgs();
			if (! opt.importFile(file.c_str(), '#'))
				std::cerr << "ERROR: Failed to open file " << file << std::endl;
		}
	}

	if (opt.isSet("-e")) {
		std::string outfile;
		opt.get("-e")->getString(outfile);
		opt.exportFile(outfile.c_str(), false);
	}

	if (opt.isSet("+e")) {
		std::string outfile;
		opt.get("+e")->getString(outfile);
		opt.exportFile(outfile.c_str(), true);
	}

	if (!opt.isSet("+d")) {
		std::string pretty;
		opt.prettyPrint(pretty);
		std::cout << pretty;
	}

	return 0;
}


text:
module.exports = function ($) {

	var mainDatabase = function () {
		var db = $.database.main;
		var mainDb = {};

		mainDb.model = function (modelName) {
			return db.models[modelName];
		}

		return mainDb;
	}

	return function (dbName) {
		switch (dbName) {
			case 'main':
				return mainDatabase();
			break;
		}
	}
}


text:
import { Link } from 'gatsby'
import PropTypes from 'prop-types'
import React from 'react'

const isPartiallyActive = ({ isPartiallyCurrent }) => {
  return isPartiallyCurrent
    ? { className: 'nav__link nav__link--active' }
    : { className: 'nav__link' }
}

const PartialNavLink = props => (
  <Link getProps={isPartiallyActive} {...props}>
    {props.children}
  </Link>
)

const Header = ({ siteTitle }) => (
  <header className="mb-8">
      <h1 className="text-xl mb-4">
        <Link to="/" className="no-underline text-grey-900">{siteTitle}</Link>
      </h1>

      <nav class="nav">
        <Link to="/projects/"
          className="nav__link"
          activeClassName="nav__link--active">Projects</Link>
        <PartialNavLink to="/journal/"
          className="nav__link"
          activeClassName="nav__link--active">Journal</PartialNavLink>
        <PartialNavLink to="/til/"
          className="nav__link"
          activeClassName="nav__link--active">TIL</PartialNavLink>
        <PartialNavLink to="/blog/"
          className="nav__link"
          activeClassName="nav__link--active">Archive</PartialNavLink>
      </nav>
  </header>
)

Header.propTypes = {
  siteTitle: PropTypes.string,
}

Header.defaultProps = {
  siteTitle: ``,
}

export default Header


text:
Returns the first value exclusive ORed with the second.

## Usage:

**xor value1 value2**

## Arguments:

**value1** - The value1 argument. (must be: logic number char tuple binary image)

**value2** - The value2 argument. (must be: logic number char tuple binary image)

## Description:

For integers, each bit is exclusively-or'd. For logic values, this is the same as the not-equal function.

```
print 122 xor 1
123
```

```
print true xor false
true
```

```
print false xor false
false
```

```
print 1.2.3.4 xor 1.0.0.0
0.2.3.4
```

## Related:

[**and**](http://www.rebol.com/docs/words/wand.html) - Returns the first value ANDed with the second.
[**not**](http://www.rebol.com/docs/words/wnot.html) - Returns the logic complement.
[**or**](http://www.rebol.com/docs/words/wor.html) - Returns the first value ORed with the second.


text:
404

Oops 404! That page can't be found.

      Sorry, but the page you are looking for was either not found or does not exist.

      Try refreshing the page or click the button below to go back to the Homepage.

           Go back to Homepage


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebsitePanel.WebDav.Core.Config.WebConfigSections
{
    public class WebdavRootElement : ConfigurationElement
    {
        private const string ValueKey = "value";

        [ConfigurationProperty(ValueKey, IsKey = true, IsRequired = true)]
        public string Value
        {
            get { return (string)this[ValueKey]; }
            set { this[ValueKey] = value; }
        }
    }
}


text:
class AddShareUrlToArtworks < ActiveRecord::Migration
  def change
    add_column :artworks, :share_url, :string
  end
end


text:
package com.tolgaduran.moviedb.adapter;

import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.tolgaduran.moviedb.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.tolgaduran.moviedb.Constants;
import com.tolgaduran.moviedb.utils.RoundedTransformation;
import com.tolgaduran.moviedb.utils.ViewHolderUtil;

import java.util.Locale;

public class SeasonsTVArrayAdapter extends
        RecyclerView.Adapter<SeasonsTVArrayAdapter.ViewHolder> {

    private final Cursor cursor;
    private Context context;
    private ViewHolderUtil.SetOnClickListener listener;

    public SeasonsTVArrayAdapter(Cursor cursor) {
        this.cursor = cursor;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(R.layout.list_item_tv_seasons, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, int position) {
        cursor.moveToPosition(position);

        final String POSTER_BASE_URL = "http://image.tmdb.org/t/p/w185";
        final String url = POSTER_BASE_URL + cursor.getString(Constants.TV_SEASON_COL_POSTER_PATH);
        Picasso
                .with(context)
                .load(url)
                .networkPolicy(NetworkPolicy.OFFLINE)
                .transform(new RoundedTransformation(10, 10))
                .fit()
                .centerCrop()
                .into(viewHolder.imageView, new Callback() {
                    @Override
                    public void onSuccess() {
                    }

                    @Override
                    public void onError() {
                        Picasso
                                .with(context)
                                .load(url)
                                .error(R.mipmap.ic_launcher)
                                .fit()
                                .centerCrop()
                                .into(viewHolder.imageView, new Callback() {
                                    @Override
                                    public void onSuccess() {
                                    }

                                    @Override
                                    public void onError() {
                                    }
                                });
                    }
                });
        viewHolder.imageView.setAdjustViewBounds(true);
        viewHolder.name.setText(String.format(Locale.ENGLISH, "EPISODE COUNT: %s", cursor.getString(Constants.TV_SEASON_COL_EPISODE_COUNT)));
        viewHolder.count.setText(String.format(Locale.ENGLISH, "%d.", cursor.getInt(Constants.TV_SEASON_COL_SEASON_NUMBER) + 1));
        viewHolder.setItemClickListener(listener);
    }

    @Override
    public int getItemCount() {
        if (cursor != null) {
            return cursor.getCount();
        }
        return 0;
    }

    public Cursor getCursor() {
        return cursor;
    }

    public void setOnClickListener(ViewHolderUtil.SetOnClickListener clickListener) {
        this.listener = clickListener;
    }

    public interface SetOnClickListener extends ViewHolderUtil.SetOnClickListener {
        void onItemClick(int position);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        final ImageView imageView;
        final TextView name;
        final TextView count;
        private ViewHolderUtil.SetOnClickListener listener;

        ViewHolder(final View view) {
            super(view);
            imageView = (ImageView) view.findViewById(R.id.similar_movie_poster);
            name = (TextView) view.findViewById(R.id.name);
            count = (TextView) view.findViewById(R.id.season_count);
            view.setClickable(true);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onItemClick(getAdapterPosition());
                    }
                }
            });
        }

        void setItemClickListener(ViewHolderUtil.SetOnClickListener itemClickListener) {
            this.listener = itemClickListener;
        }

    }
}


text:
curl -L -X GET 'https://maps.googleapis.com/maps/api/directions/json?origin=Toledo&destination=Madrid&key=YOUR_API_KEY'
# [END maps_http_directions_region_toledo_default]


text:
layout: post
title: "Slides for EDAMAME mothur talk"
author: "PD. Schloss"
date: "August 14, 2014"
comments: true
---

Pat will be giving a talk about mothur at Explorations in Data Analyses for Metagenomic Advances in Microbial Ecology (EDAMAME) Workshop this friday. You can learn more about the workshop through the [EDAMAME website](http://edamame-course.org).

His slides are available through his [github website](http://pschloss.github.io/talks/2014_08_15_mothur)


text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>AMC TWD</title>

    <link rel="stylesheet" type="text/css" href="http://www.thequotablewalkingdead.com/assets/css/styles_feeling_responsive.css">

		<link href='http://fonts.googleapis.com/css?family=Lato:400,700,400italic%7CVolkhov' rel='stylesheet' type='text/css'>

<title>AMC TWD - The Quotable Walking Dead, AMC TWD fan site</title>
<meta property="og:title" content="AMC TWD" />
<meta name="description" content="»A Fan site dedicated to AMC TWD." />
<meta property="og:description" content="»A Fan site dedicated to AMC TWD." />
<link rel="canonical" href="http://www.thequotablewalkingdead.com/blog/" />
<meta property="og:url" content="http://www.thequotablewalkingdead.com/blog/" />
<meta property="og:site_name" content="The Quotable Walking Dead, AMC TWD fan site" />
<meta property="og:image" content="http://www.thequotablewalkingdead.com/images/rick-blog.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@thequotablewd" />
<meta name="twitter:creator" content="@thequotablewalkingdead" />

	<link type="text/plain" rel="author" href="http://www.thequotablewalkingdead.com/humans.txt">

	<link rel="icon" sizes="32x32" href="http://www.thequotablewalkingdead.com/assets/img/favicon-32x32.png">

	<link rel="icon" sizes="192x192" href="http://www.thequotablewalkingdead.com/assets/img/touch-icon-192x192.png">

	<link rel="apple-touch-icon-precomposed" sizes="180x180" href="http://www.thequotablewalkingdead.com/assets/img/apple-touch-icon-180x180-precomposed.png">

	<link rel="apple-touch-icon-precomposed" sizes="152x152" href="http://www.thequotablewalkingdead.com/assets/img/apple-touch-icon-152x152-precomposed.png">

	<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://www.thequotablewalkingdead.com/assets/img/apple-touch-icon-144x144-precomposed.png">

	<link rel="apple-touch-icon-precomposed" sizes="120x120" href="http://www.thequotablewalkingdead.com/assets/img/apple-touch-icon-120x120-precomposed.png">

	<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://www.thequotablewalkingdead.com/assets/img/apple-touch-icon-114x114-precomposed.png">

	<link rel="apple-touch-icon-precomposed" sizes="76x76" href="http://www.thequotablewalkingdead.com/assets/img/apple-touch-icon-76x76-precomposed.png">

	<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://www.thequotablewalkingdead.com/assets/img/apple-touch-icon-72x72-precomposed.png">

	<link rel="apple-touch-icon-precomposed" href="http://www.thequotablewalkingdead.com/assets/img/apple-touch-icon-precomposed.png">

	<meta name="msapplication-TileImage" content="http://www.thequotablewalkingdead.com/assets/img/msapplication_tileimage.png">

	<meta name="msapplication-TileColor" content="#fabb00">

 The Quotable Walking Dead, AMC TWD fan site

Nav

Home

Blog

Gear

Thangs

news – AMC TWD

Three Jeffrey Dean Morgan Facts

        These are some surprising facts about the actor playing our favorite villain.

        Read More ›

video – AMC TWD

Negan's Bat - DIY Prop

        Want to make an awesome prop for your cosplay or costume party?

        Read More ›

video – AMC TWD

Do Psychopaths Survive Better?

        Seems like cannibals, murderers, and sadists survive better in the world of the TWD than normal folks. But is it really true?

        Read More ›

news – AMC TWD

Glenn Returns To AMC TWD Season 8

        Seeing Glenn die was tough. I mean really tough. It was like a hard punch to the gut.

        Read More ›

    Blog Archive

        

About This Site

              »A Fan site dedicated to AMC TWD.
              More ›

Services

                    Contact

                    sitemap.xml

Acknowledgements

                  Icons by Daniel Bruce

                  Built on Foundation

                  Using Backstretch by Scott Robbin


text:
var drawTriangles = require('./')
require('canvas-testbed')(render)

var path = [ [25, 25], [40, 30], [50, 75], [125, 15] ]

//get a thick polyline
var mesh = require('extrude-polyline')({
    thickness: 20,
    miterLimit: 1.5
}).build(path)

function render(ctx, width, height) {
    ctx.clearRect(0,0,width,height)

    ctx.beginPath()
    drawTriangles(ctx, mesh.positions, mesh.cells)
    ctx.strokeStyle = 'black'
    ctx.lineJoin = 'bevel'
    ctx.stroke()
}


text:
'use strict';

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

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _enhancer = require('./enhancer');

var _enhancer2 = _interopRequireDefault(_enhancer);

var _types = require('./types');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

/* eslint react/prop-types: 0 */
var Circle = function (_Component) {
  (0, _inherits3['default'])(Circle, _Component);

  function Circle() {
    (0, _classCallCheck3['default'])(this, Circle);
    return (0, _possibleConstructorReturn3['default'])(this, (Circle.__proto__ || Object.getPrototypeOf(Circle)).apply(this, arguments));
  }

  (0, _createClass3['default'])(Circle, [{
    key: 'getPathStyles',
    value: function getPathStyles() {
      var _props = this.props,
          percent = _props.percent,
          strokeWidth = _props.strokeWidth,
          _props$gapDegree = _props.gapDegree,
          gapDegree = _props$gapDegree === undefined ? 0 : _props$gapDegree,
          gapPosition = _props.gapPosition;

      var radius = 50 - strokeWidth / 2;
      var beginPositionX = 0;
      var beginPositionY = -radius;
      var endPositionX = 0;
      var endPositionY = -2 * radius;
      switch (gapPosition) {
        case 'left':
          beginPositionX = -radius;
          beginPositionY = 0;
          endPositionX = 2 * radius;
          endPositionY = 0;
          break;
        case 'right':
          beginPositionX = radius;
          beginPositionY = 0;
          endPositionX = -2 * radius;
          endPositionY = 0;
          break;
        case 'bottom':
          beginPositionY = radius;
          endPositionY = 2 * radius;
          break;
        default:
      }
      var pathString = 'M 50,50 m ' + beginPositionX + ',' + beginPositionY + '\n     a ' + radius + ',' + radius + ' 0 1 1 ' + endPositionX + ',' + -endPositionY + '\n     a ' + radius + ',' + radius + ' 0 1 1 ' + -endPositionX + ',' + endPositionY;
      var len = Math.PI * 2 * radius;
      var trailPathStyle = {
        strokeDasharray: len - gapDegree + 'px ' + len + 'px',
        strokeDashoffset: '-' + gapDegree / 2 + 'px',
        transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s'
      };
      var strokePathStyle = {
        strokeDasharray: percent / 100 * (len - gapDegree) + 'px ' + len + 'px',
        strokeDashoffset: '-' + gapDegree / 2 + 'px',
        transition: 'stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s'
      };
      return { pathString: pathString, trailPathStyle: trailPathStyle, strokePathStyle: strokePathStyle };
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props2 = this.props,
          prefixCls = _props2.prefixCls,
          strokeWidth = _props2.strokeWidth,
          trailWidth = _props2.trailWidth,
          strokeColor = _props2.strokeColor,
          trailColor = _props2.trailColor,
          strokeLinecap = _props2.strokeLinecap,
          style = _props2.style,
          className = _props2.className,
          restProps = (0, _objectWithoutProperties3['default'])(_props2, ['prefixCls', 'strokeWidth', 'trailWidth', 'strokeColor', 'trailColor', 'strokeLinecap', 'style', 'className']);

      var _getPathStyles = this.getPathStyles(),
          pathString = _getPathStyles.pathString,
          trailPathStyle = _getPathStyles.trailPathStyle,
          strokePathStyle = _getPathStyles.strokePathStyle;

      delete restProps.percent;
      delete restProps.gapDegree;
      delete restProps.gapPosition;
      return _react2['default'].createElement(
        'svg',
        (0, _extends3['default'])({
          className: prefixCls + '-circle ' + className,
          viewBox: '0 0 100 100',
          style: style
        }, restProps),
        _react2['default'].createElement('path', {
          className: prefixCls + '-circle-trail',
          d: pathString,
          stroke: trailColor,
          strokeWidth: trailWidth || strokeWidth,
          fillOpacity: '0',
          style: trailPathStyle
        }),
        _react2['default'].createElement('path', {
          className: prefixCls + '-circle-path',
          d: pathString,
          strokeLinecap: strokeLinecap,
          stroke: strokeColor,
          strokeWidth: strokeWidth,
          fillOpacity: '0',
          ref: function ref(path) {
            _this2.path = path;
          },
          style: strokePathStyle
        })
      );
    }
  }]);
  return Circle;
}(_react.Component);

Circle.propTypes = (0, _extends3['default'])({}, _types.propTypes, {
  gapPosition: _propTypes2['default'].oneOf(['top', 'bottom', 'left', 'right'])
});

Circle.defaultProps = (0, _extends3['default'])({}, _types.defaultProps, {
  gapPosition: 'top'
});

exports['default'] = (0, _enhancer2['default'])(Circle);
module.exports = exports['default'];


text:
require 'spec_helper'

describe RunnerEntity do
  let(:project) { create(:project) }
  let(:runner) { create(:ci_runner, :project, projects: [project]) }
  let(:entity) { described_class.new(runner, request: request, current_user: user) }
  let(:request) { double('request') }
  let(:user) { create(:admin) }

  before do
    allow(request).to receive(:current_user).and_return(user)
    allow(request).to receive(:project).and_return(project)
  end

  describe '#as_json' do
    subject { entity.as_json }

    it 'contains required fields' do
      expect(subject).to include(:id, :description)
      expect(subject).to include(:edit_path)
    end
  end
end


text:
class ExampleObject : public GameObject {
 public:
  ExampleObject(Cache<sf::Texture>&);
  ~ExampleObject() override;

  void Update(int32_t) override;
  void Draw(sf::RenderWindow&, int32_t) override;
};

#endif


text:
package org.dom4j.util;

/**
 *

 * SingletonStrategy is an interface used to provide common
 * factory access for the same object based on an implementation strategy for
 * singleton. Right now there are two that accompany this interface:
 * SimpleSingleton and PerThreadSingleton. This will replace previous usage of
 * ThreadLocal to allow for alternate strategies.
 *

 *
 * @author David Lucas
 * @version $Revision: 1.2 $
 */
public interface SingletonStrategy {
    /**
     * return a singleton instance of the class specified in setSingletonClass
     */
    Object instance();

    /**
     * reset the instance to a new instance for the implemented strategy
     */
    void reset();

    /**
     * set a singleton class name that will be used to create the singleton
     * based on the strategy implementation of this interface. The default
     * constructor of the class will be used and must be public.
     */
    void setSingletonClassName(String singletonClassName);
}

/*
 * Redistribution and use of this software and associated documentation
 * ("Software"), with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * 1. Redistributions of source code must retain copyright statements and
 * notices. Redistributions must also contain a copy of this document.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. The name "DOM4J" must not be used to endorse or promote products derived
 * from this Software without prior written permission of MetaStuff, Ltd. For
 * written permission, please contact dom4j-info@metastuff.com.
 *
 * 4. Products derived from this Software may not be called "DOM4J" nor may
 * "DOM4J" appear in their names without prior written permission of MetaStuff,
 * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd.
 *
 * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org
 *
 * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved.
 */


text:
//
//  FBSession+ReactiveExtensions.m
//  Pods
//
//  Created by Stefano Comba on 27/03/14.
//
//

#import "FBSDKLoginManager+RACExtensions.h"
#import "FBSDKAccessToken.h"
@implementation FBSDKLoginManager (RACExtensions)

- (RACSignal*) rac_loginWithReadPermissions:(NSArray*) permissions {
    __weak FBSDKLoginManager *loginManager = self;

    return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        if ([FBSDKAccessToken currentAccessToken] != nil) {
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
        }
        else {
            [loginManager logInWithReadPermissions:permissions handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
                if (!error){
                    [subscriber sendNext: result];
                    [subscriber sendCompleted];
                }
                else {
                    [subscriber sendError:error];
                }
            }];
        }
        return [RACDisposable disposableWithBlock:^{
//            [[FBSession activeSession] closeAndClearTokenInformation];
        }];
    }] subscribeOn:[RACScheduler mainThreadScheduler]];
}

/*
- (RACSignal*) rac_publishWithPermissions:(NSArray *) permissions defaultAudience:(FBSessionDefaultAudience) defaultAudience {
    __weak FBSession* session = self;
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {

        [session requestNewPublishPermissions:permissions defaultAudience:defaultAudience completionHandler:^(FBSession *session, NSError *error) {
            if (error) {
                [subscriber sendError:error];
            }
            else {
                [subscriber sendNext:session];
                [subscriber sendCompleted];
            }
        }];

       return [RACDisposable disposableWithBlock:^{

       }];
    }];
}
 */
@end


text:
package org.apache.hadoop.hbase.zookeeper;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Abortable;
import org.apache.hadoop.hbase.AuthUtil;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.security.Superusers;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooDefs.Perms;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Acts as the single ZooKeeper Watcher.  One instance of this is instantiated
 * for each Master, RegionServer, and client process.
 *
 *
This is the only class that implements {@link Watcher}.  Other internal
 * classes which need to be notified of ZooKeeper events must register with
 * the local instance of this watcher via {@link #registerListener}.
 *
 *
This class also holds and manages the connection to ZooKeeper.  Code to
 * deal with connection related events and exceptions are handled here.
 */
@InterfaceAudience.Private
public class ZKWatcher implements Watcher, Abortable, Closeable {
  private static final Logger LOG = LoggerFactory.getLogger(ZKWatcher.class);

  // Identifier for this watcher (for logging only).  It is made of the prefix
  // passed on construction and the zookeeper sessionid.
  private String prefix;
  private String identifier;

  // zookeeper quorum
  private String quorum;

  // zookeeper connection
  private final RecoverableZooKeeper recoverableZooKeeper;

  // abortable in case of zk failure
  protected Abortable abortable;
  // Used if abortable is null
  private boolean aborted = false;

  private final ZNodePaths znodePaths;

  // listeners to be notified
  private final List<ZKListener> listeners = new CopyOnWriteArrayList<>();

  private final Configuration conf;

  /* A pattern that matches a Kerberos name, borrowed from Hadoop's KerberosName */
  private static final Pattern NAME_PATTERN = Pattern.compile("([^/@]*)(/([^/@]*))?@([^/@]*)");

  /**
   * Instantiate a ZooKeeper connection and watcher.
   * @param identifier string that is passed to RecoverableZookeeper to be used as
   *                   identifier for this instance. Use null for default.
   * @throws IOException if the connection to ZooKeeper fails
   * @throws ZooKeeperConnectionException if the client can't connect to ZooKeeper
   */
  public ZKWatcher(Configuration conf, String identifier,
                   Abortable abortable) throws ZooKeeperConnectionException, IOException {
    this(conf, identifier, abortable, false);
  }

  /**
   * Instantiate a ZooKeeper connection and watcher.
   * @param conf the configuration to use
   * @param identifier string that is passed to RecoverableZookeeper to be used as identifier for
   *          this instance. Use null for default.
   * @param abortable Can be null if there is on error there is no host to abort: e.g. client
   *          context.
   * @param canCreateBaseZNode true if a base ZNode can be created
   * @throws IOException if the connection to ZooKeeper fails
   * @throws ZooKeeperConnectionException if the client can't connect to ZooKeeper
   */
  public ZKWatcher(Configuration conf, String identifier,
                   Abortable abortable, boolean canCreateBaseZNode)
    throws IOException, ZooKeeperConnectionException {
    this(conf, identifier, abortable, canCreateBaseZNode, false);
  }

  /**
   * Instantiate a ZooKeeper connection and watcher.
   * @param conf the configuration to use
   * @param identifier string that is passed to RecoverableZookeeper to be used as identifier for
   *          this instance. Use null for default.
   * @param abortable Can be null if there is on error there is no host to abort: e.g. client
   *          context.
   * @param canCreateBaseZNode true if a base ZNode can be created
   * @param clientZK whether this watcher is set to access client ZK
   * @throws IOException if the connection to ZooKeeper fails
   * @throws ZooKeeperConnectionException if the connection to Zookeeper fails when create base
   *           ZNodes
   */
  public ZKWatcher(Configuration conf, String identifier, Abortable abortable,
      boolean canCreateBaseZNode, boolean clientZK)
      throws IOException, ZooKeeperConnectionException {
    this.conf = conf;
    if (clientZK) {
      String clientZkQuorumServers = ZKConfig.getClientZKQuorumServersString(conf);
      String serverZkQuorumServers = ZKConfig.getZKQuorumServersString(conf);
      if (clientZkQuorumServers != null) {
        if (clientZkQuorumServers.equals(serverZkQuorumServers)) {
          // Don't allow same settings to avoid dead loop when master trying
          // to sync meta information from server ZK to client ZK
          throw new IllegalArgumentException(
              "The quorum settings for client ZK should be different from those for server");
        }
        this.quorum = clientZkQuorumServers;
      } else {
        this.quorum = serverZkQuorumServers;
      }
    } else {
      this.quorum = ZKConfig.getZKQuorumServersString(conf);
    }
    this.prefix = identifier;
    // Identifier will get the sessionid appended later below down when we
    // handle the syncconnect event.
    this.identifier = identifier + "0x0";
    this.abortable = abortable;
    this.znodePaths = new ZNodePaths(conf);
    PendingWatcher pendingWatcher = new PendingWatcher();
    this.recoverableZooKeeper = ZKUtil.connect(conf, quorum, pendingWatcher, identifier);
    pendingWatcher.prepare(this);
    if (canCreateBaseZNode) {
      try {
        createBaseZNodes();
      } catch (ZooKeeperConnectionException zce) {
        try {
          this.recoverableZooKeeper.close();
        } catch (InterruptedException ie) {
          LOG.debug("Encountered InterruptedException when closing {}", this.recoverableZooKeeper);
          Thread.currentThread().interrupt();
        }
        throw zce;
      }
    }
  }

  private void createBaseZNodes() throws ZooKeeperConnectionException {
    try {
      // Create all the necessary "directories" of znodes
      ZKUtil.createWithParents(this, znodePaths.baseZNode);
      ZKUtil.createAndFailSilent(this, znodePaths.rsZNode);
      ZKUtil.createAndFailSilent(this, znodePaths.drainingZNode);
      ZKUtil.createAndFailSilent(this, znodePaths.tableZNode);
      ZKUtil.createAndFailSilent(this, znodePaths.splitLogZNode);
      ZKUtil.createAndFailSilent(this, znodePaths.backupMasterAddressesZNode);
      ZKUtil.createAndFailSilent(this, znodePaths.masterMaintZNode);
    } catch (KeeperException e) {
      throw new ZooKeeperConnectionException(
          prefix("Unexpected KeeperException creating base node"), e);
    }
  }

  /**
   * On master start, we check the znode ACLs under the root directory and set the ACLs properly
   * if needed. If the cluster goes from an unsecure setup to a secure setup, this step is needed
   * so that the existing znodes created with open permissions are now changed with restrictive
   * perms.
   */
  public void checkAndSetZNodeAcls() {
    if (!ZKUtil.isSecureZooKeeper(getConfiguration())) {
      LOG.info("not a secure deployment, proceeding");
      return;
    }

    // Check the base znodes permission first. Only do the recursion if base znode's perms are not
    // correct.
    try {
      List<ACL> actualAcls = recoverableZooKeeper.getAcl(znodePaths.baseZNode, new Stat());

      if (!isBaseZnodeAclSetup(actualAcls)) {
        LOG.info("setting znode ACLs");
        setZnodeAclsRecursive(znodePaths.baseZNode);
      }
    } catch(KeeperException.NoNodeException nne) {
      return;
    } catch(InterruptedException ie) {
      interruptedExceptionNoThrow(ie, false);
    } catch (IOException|KeeperException e) {
      LOG.warn("Received exception while checking and setting zookeeper ACLs", e);
    }
  }

  /**
   * Set the znode perms recursively. This will do post-order recursion, so that baseZnode ACLs
   * will be set last in case the master fails in between.
   * @param znode the ZNode to set the permissions for
   */
  private void setZnodeAclsRecursive(String znode) throws KeeperException, InterruptedException {
    List<String> children = recoverableZooKeeper.getChildren(znode, false);

    for (String child : children) {
      setZnodeAclsRecursive(ZNodePaths.joinZNode(znode, child));
    }
    List<ACL> acls = ZKUtil.createACL(this, znode, true);
    LOG.info("Setting ACLs for znode:{} , acl:{}", znode, acls);
    recoverableZooKeeper.setAcl(znode, acls, -1);
  }

  /**
   * Checks whether the ACLs returned from the base znode (/hbase) is set for secure setup.
   * @param acls acls from zookeeper
   * @return whether ACLs are set for the base znode
   * @throws IOException if getting the current user fails
   */
  private boolean isBaseZnodeAclSetup(List<ACL> acls) throws IOException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Checking znode ACLs");
    }
    String[] superUsers = conf.getStrings(Superusers.SUPERUSER_CONF_KEY);
    // Check whether ACL set for all superusers
    if (superUsers != null && !checkACLForSuperUsers(superUsers, acls)) {
      return false;
    }

    // this assumes that current authenticated user is the same as zookeeper client user
    // configured via JAAS
    String hbaseUser = UserGroupInformation.getCurrentUser().getShortUserName();

    if (acls.isEmpty()) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("ACL is empty");
      }
      return false;
    }

    for (ACL acl : acls) {
      int perms = acl.getPerms();
      Id id = acl.getId();
      // We should only set at most 3 possible ACLs for 3 Ids. One for everyone, one for superuser
      // and one for the hbase user
      if (Ids.ANYONE_ID_UNSAFE.equals(id)) {
        if (perms != Perms.READ) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("permissions for '%s' are not correct: have 0x%x, want 0x%x",
              id, perms, Perms.READ));
          }
          return false;
        }
      } else if (superUsers != null && isSuperUserId(superUsers, id)) {
        if (perms != Perms.ALL) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("permissions for '%s' are not correct: have 0x%x, want 0x%x",
              id, perms, Perms.ALL));
          }
          return false;
        }
      } else if ("sasl".equals(id.getScheme())) {
        String name = id.getId();
        // If ZooKeeper recorded the Kerberos full name in the ACL, use only the shortname
        Matcher match = NAME_PATTERN.matcher(name);
        if (match.matches()) {
          name = match.group(1);
        }
        if (name.equals(hbaseUser)) {
          if (perms != Perms.ALL) {
            if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("permissions for '%s' are not correct: have 0x%x, want 0x%x",
                id, perms, Perms.ALL));
            }
            return false;
          }
        } else {
          if (LOG.isDebugEnabled()) {
            LOG.debug("Unexpected shortname in SASL ACL: {}", id);
          }
          return false;
        }
      } else {
        if (LOG.isDebugEnabled()) {
          LOG.debug("unexpected ACL id '{}'", id);
        }
        return false;
      }
    }
    return true;
  }

  /*
   * Validate whether ACL set for all superusers.
   */
  private boolean checkACLForSuperUsers(String[] superUsers, List<ACL> acls) {
    for (String user : superUsers) {
      boolean hasAccess = false;
      // TODO: Validate super group members also when ZK supports setting node ACL for groups.
      if (!AuthUtil.isGroupPrincipal(user)) {
        for (ACL acl : acls) {
          if (user.equals(acl.getId().getId())) {
            if (acl.getPerms() == Perms.ALL) {
              hasAccess = true;
            } else {
              if (LOG.isDebugEnabled()) {
                LOG.debug(String.format(
                  "superuser '%s' does not have correct permissions: have 0x%x, want 0x%x",
                  acl.getId().getId(), acl.getPerms(), Perms.ALL));
              }
            }
            break;
          }
        }
        if (!hasAccess) {
          return false;
        }
      }
    }
    return true;
  }

  /*
   * Validate whether ACL ID is superuser.
   */
  public static boolean isSuperUserId(String[] superUsers, Id id) {
    for (String user : superUsers) {
      // TODO: Validate super group members also when ZK supports setting node ACL for groups.
      if (!AuthUtil.isGroupPrincipal(user) && new Id("sasl", user).equals(id)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public String toString() {
    return this.identifier + ", quorum=" + quorum + ", baseZNode=" + znodePaths.baseZNode;
  }

  /**
   * Adds this instance's identifier as a prefix to the passed str
   * @param str String to amend.
   * @return A new string with this instance's identifier as prefix: e.g.
   *         if passed 'hello world', the returned string could be
   */
  public String prefix(final String str) {
    return this.toString() + " " + str;
  }

  /**
   * Get the znodes corresponding to the meta replicas from ZK
   * @return list of znodes
   * @throws KeeperException if a ZooKeeper operation fails
   */
  public List<String> getMetaReplicaNodes() throws KeeperException {
    List<String> childrenOfBaseNode = ZKUtil.listChildrenNoWatch(this, znodePaths.baseZNode);
    return filterMetaReplicaNodes(childrenOfBaseNode);
  }

  /**
   * Same as {@link #getMetaReplicaNodes()} except that this also registers a watcher on base znode
   * for subsequent CREATE/DELETE operations on child nodes.
   */
  public List<String> getMetaReplicaNodesAndWatchChildren() throws KeeperException {
    List<String> childrenOfBaseNode =
        ZKUtil.listChildrenAndWatchForNewChildren(this, znodePaths.baseZNode);
    return filterMetaReplicaNodes(childrenOfBaseNode);
  }

  /**
   * @param nodes Input list of znodes
   * @return Filtered list of znodes from nodes that belong to meta replica(s).
   */
  private List<String> filterMetaReplicaNodes(List<String> nodes) {
    if (nodes == null || nodes.isEmpty()) {
      return new ArrayList<>();
    }
    List<String> metaReplicaNodes = new ArrayList<>(2);
    String pattern = conf.get(ZNodePaths.META_ZNODE_PREFIX_CONF_KEY, ZNodePaths.META_ZNODE_PREFIX);
    for (String child : nodes) {
      if (child.startsWith(pattern)) {
        metaReplicaNodes.add(child);
      }
    }
    return metaReplicaNodes;
  }

  /**
   * Register the specified listener to receive ZooKeeper events.
   * @param listener the listener to register
   */
  public void registerListener(ZKListener listener) {
    listeners.add(listener);
  }

  /**
   * Register the specified listener to receive ZooKeeper events and add it as
   * the first in the list of current listeners.
   * @param listener the listener to register
   */
  public void registerListenerFirst(ZKListener listener) {
    listeners.add(0, listener);
  }

  public void unregisterListener(ZKListener listener) {
    listeners.remove(listener);
  }

  /**
   * Clean all existing listeners
   */
  public void unregisterAllListeners() {
    listeners.clear();
  }

  /**
   * Get a copy of current registered listeners
   */
  public List<ZKListener> getListeners() {
    return new ArrayList<>(listeners);
  }

  /**
   * @return The number of currently registered listeners
   */
  public int getNumberOfListeners() {
    return listeners.size();
  }

  /**
   * Get the connection to ZooKeeper.
   * @return connection reference to zookeeper
   */
  public RecoverableZooKeeper getRecoverableZooKeeper() {
    return recoverableZooKeeper;
  }

  public void reconnectAfterExpiration() throws IOException, KeeperException, InterruptedException {
    recoverableZooKeeper.reconnectAfterExpiration();
  }

  /**
   * Get the quorum address of this instance.
   * @return quorum string of this zookeeper connection instance
   */
  public String getQuorum() {
    return quorum;
  }

  /**
   * Get the znodePaths.
   *

   * Mainly used for mocking as mockito can not mock a field access.
   */
  public ZNodePaths getZNodePaths() {
    return znodePaths;
  }

  /**
   * Method called from ZooKeeper for events and connection status.
   *

   * Valid events are passed along to listeners.  Connection status changes
   * are dealt with locally.
   */
  @Override
  public void process(WatchedEvent event) {
    LOG.debug(prefix("Received ZooKeeper Event, " +
        "type=" + event.getType() + ", " +
        "state=" + event.getState() + ", " +
        "path=" + event.getPath()));

    switch(event.getType()) {

      // If event type is NONE, this is a connection status change
      case None: {
        connectionEvent(event);
        break;
      }

      // Otherwise pass along to the listeners

      case NodeCreated: {
        for(ZKListener listener : listeners) {
          listener.nodeCreated(event.getPath());
        }
        break;
      }

      case NodeDeleted: {
        for(ZKListener listener : listeners) {
          listener.nodeDeleted(event.getPath());
        }
        break;
      }

      case NodeDataChanged: {
        for(ZKListener listener : listeners) {
          listener.nodeDataChanged(event.getPath());
        }
        break;
      }

      case NodeChildrenChanged: {
        for(ZKListener listener : listeners) {
          listener.nodeChildrenChanged(event.getPath());
        }
        break;
      }
      default:
        throw new IllegalStateException("Received event is not valid: " + event.getState());
    }
  }

  // Connection management

  /**
   * Called when there is a connection-related event via the Watcher callback.
   *

   * If Disconnected or Expired, this should shutdown the cluster. But, since
   * we send a KeeperException.SessionExpiredException along with the abort
   * call, it's possible for the Abortable to catch it and try to create a new
   * session with ZooKeeper. This is what the client does in HCM.
   *

   * @param event the connection-related event
   */
  private void connectionEvent(WatchedEvent event) {
    switch(event.getState()) {
      case SyncConnected:
        this.identifier = this.prefix + "-0x" +
          Long.toHexString(this.recoverableZooKeeper.getSessionId());
        // Update our identifier.  Otherwise ignore.
        LOG.debug("{} connected", this.identifier);
        break;

      // Abort the server if Disconnected or Expired
      case Disconnected:
        LOG.debug(prefix("Received Disconnected from ZooKeeper, ignoring"));
        break;

      case Expired:
        String msg = prefix(this.identifier + " received expired from " +
          "ZooKeeper, aborting");
        // TODO: One thought is to add call to ZKListener so say,
        // ZKNodeTracker can zero out its data values.
        if (this.abortable != null) {
          this.abortable.abort(msg, new KeeperException.SessionExpiredException());
        }
        break;

      case ConnectedReadOnly:
      case SaslAuthenticated:
      case AuthFailed:
        break;

      default:
        throw new IllegalStateException("Received event is not valid: " + event.getState());
    }
  }

  /**
   * Forces a synchronization of this ZooKeeper client connection.
   *

   * Executing this method before running other methods will ensure that the
   * subsequent operations are up-to-date and consistent as of the time that
   * the sync is complete.
   *

   * This is used for compareAndSwap type operations where we need to read the
   * data of an existing node and delete or transition that node, utilizing the
   * previously read version and data.  We want to ensure that the version read
   * is up-to-date from when we begin the operation.
   */
  public void sync(String path) throws KeeperException {
    this.recoverableZooKeeper.sync(path, null, null);
  }

  /**
   * Handles KeeperExceptions in client calls.
   *

   * This may be temporary but for now this gives one place to deal with these.
   *

   * TODO: Currently this method rethrows the exception to let the caller handle
   *

   * @param ke the exception to rethrow
   * @throws KeeperException if a ZooKeeper operation fails
   */
  public void keeperException(KeeperException ke) throws KeeperException {
    LOG.error(prefix("Received unexpected KeeperException, re-throwing exception"), ke);
    throw ke;
  }

  /**
   * Handles InterruptedExceptions in client calls.
   * @param ie the InterruptedException instance thrown
   * @throws KeeperException the exception to throw, transformed from the InterruptedException
   */
  public void interruptedException(InterruptedException ie) throws KeeperException {
    interruptedExceptionNoThrow(ie, true);
    // Throw a system error exception to let upper level handle it
    KeeperException keeperException = new KeeperException.SystemErrorException();
    keeperException.initCause(ie);
    throw keeperException;
  }

  /**
   * Log the InterruptedException and interrupt current thread
   * @param ie The IterruptedException to log
   * @param throwLater Whether we will throw the exception latter
   */
  public void interruptedExceptionNoThrow(InterruptedException ie, boolean throwLater) {
    LOG.debug(prefix("Received InterruptedException, will interrupt current thread"
        + (throwLater ? " and rethrow a SystemErrorException" : "")),
      ie);
    // At least preserve interrupt.
    Thread.currentThread().interrupt();
  }

  /**
   * Close the connection to ZooKeeper.
   *
   */
  @Override
  public void close() {
    try {
      recoverableZooKeeper.close();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }

  public Configuration getConfiguration() {
    return conf;
  }

  @Override
  public void abort(String why, Throwable e) {
    if (this.abortable != null) {
      this.abortable.abort(why, e);
    } else {
      this.aborted = true;
    }
  }

  @Override
  public boolean isAborted() {
    return this.abortable == null? this.aborted: this.abortable.isAborted();
  }
}


text:
class AddScheduledAtToStepByStepPages < ActiveRecord::Migration[5.2]
  def change
    add_column :step_by_step_pages, :scheduled_at, :datetime
  end
end


text:
FROM php:7.1-fpm-stretch

LABEL maintainer="fabien@myprod.net"

RUN apt-get update && apt-get install -y --no-install-recommends \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libmcrypt-dev \
        libpng-dev \
        libzip-dev \
        libicu-dev \
        libxml2-dev \
        libxslt-dev \
        libssh2-1-dev \
        ssh \
        git \
        unzip \
        ca-certificates \
        gnupg \
    && echo "deb http://apt.postgresql.org/pub/repos/apt/ stretch-pgdg main" > /etc/apt/sources.list.d/pgdg.list \
    && curl https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - \
    && apt-get update && apt-get install -y --no-install-recommends \
        libpq-dev \
    && rm -rf /var/lib/apt/lists/* \
    && pecl install -a ssh2-1.1.2 \
    && pecl install -a apcu-5.1.18 \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-configure pgsql --with-pgsql=/usr/local/pgsql \
    && docker-php-ext-install -j$(nproc) mcrypt gd opcache mbstring \
    && docker-php-ext-install pdo pdo_mysql pdo_pgsql pgsql \
    && docker-php-ext-install zip bcmath intl exif soap xsl sockets \
    && docker-php-ext-enable ssh2 apcu

# Composer installation
RUN curl -sS https://getcomposer.org/installer | php \
    -- --install-dir=${COMPOSER_HOME:-/usr/local/bin} \
    --filename=composer

# PHP Application configuration (php.ini override + FPM pool configuration)
ADD php-custom.ini /usr/local/etc/php/conf.d/
ADD www.conf /usr/local/etc/php-fpm.d/

RUN usermod -u ${DOCKER_USER_ID:-1000} www-data \
    && mkdir -p ${APP_BASE_DIR:-/var/www/}

WORKDIR ${APP_BASE_DIR:-/var/www/}


text:
using System;
using System.Collections.Generic;
namespace WhippedCream.Data.User
{

    public partial class Name
    {
        public string First { get; set; }
        public string Middle { get; set; }
        public string Last { get; set; }
        public string Suffix { get; set; }
        public string Prefix { get; set; }

        #region Members overriden from System.Object

        public override bool Equals(object obj)
        {
            return obj is Name ? Equals(obj as Name) : false;
        }

        /// <summary>
        /// The Implementation of this algorithm was taken
        /// from [here](http://www.isthe.com/chongo/tech/comp/fnv/).
        /// </summary>
        public override int GetHashCode()
        {
            int hash = 13;
            unchecked
            {
                hash = (hash * 16777619) ^ (First == null ? 0 : First.GetHashCode());
                hash = (hash * 16777619) ^ (Middle == null ? 0 : Middle.GetHashCode());
                hash = (hash * 16777619) ^ (Last == null ? 0 : Last.GetHashCode());
                hash = (hash * 16777619) ^ (Suffix == null ? 0 : Suffix.GetHashCode());
                hash = (hash * 16777619) ^ (Prefix == null ? 0 : Prefix.GetHashCode());
            }
            return hash;
        }

        public override string ToString()
        {
            return base.ToString();
        }

        #endregion

        #region IEquatable<Name> Members

        public bool Equals(Name rhs)
        {
            if(rhs == null)
                return false;

            return System.Collections.Generic.EqualityComparer<Name>.Equals(First, rhs.First) && System.Collections.Generic.EqualityComparer<Name>.Equals(Middle, rhs.Middle) && System.Collections.Generic.EqualityComparer<Name>.Equals(Last, rhs.Last) && System.Collections.Generic.EqualityComparer<Name>.Equals(Suffix, rhs.Suffix) && System.Collections.Generic.EqualityComparer<Name>.Equals(Prefix, rhs.Prefix);
        }

        #endregion
    }
}