text:
Google Health Check Plugin
====================

This plugin provides simple health checks and extension points for additional health checks.

Usage
===
From the Manage Jenkins page, go to Manage Health Checks. Add a Health Zone to create a logical group of health checks. Within a Health Zone, add a Health Check for each health condition to be tracked. As of this writing, the plugin includes two health check types:
* Minimum number of executors - fails if insufficient executors are available. Optionally allows labels to be specified, in which case only executors with at least one of those labels will count toward the minimum.
* Classes loaded - fails if the specified classes were not loaded by the Jenkins class loader.
The HealthCheck extension point provides an opportunity for plugin developers to create additional types of health checks.

After health checks are configured, the Health Check Summary page in Jenkins' left navigation menu shows a summary of the current health zones; viewing each zone allows verification of each health check's current state.

Development
===========

How to build
--------------

	mvn clean verify

Creates the plugin HPI package for use with Jenkins.

License
-------

	(The Apache v2 License)

    Copyright 2015 Google Inc. All Rights Reserved.

    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.

redpajama_set_name: RedPajamaGithub


text:
var toc = require('markdown-toc');
var assign = require('object-assign');
var cheerio = require('cheerio');

exports.insert = function (data) {

  var options = assign({}, this.config.toc);

  // add class option
  if (options.class) {
    data.content = data.content.replace("", '

');
  }

  data.content = toc.insert(data.content, options);
  return data;
};

exports.heading = function (data) {
  var options = assign({}, this.config.toc);

  var $ = cheerio.load(data.content, { decodeEntities: ( options.decodeEntities !== undefined ? options.decodeEntities : false ) });
  var headings = $('h1, h2, h3, h4, h5, h6');

  headings.each(function () {
    var $title = $(this);
    var title = $title.text();
    var id = toc.slugify(title, options);
    // $title.attr('id', id);
    $title.children('a').remove();
    $title.html( '' + $title.html() + '' );
    $title.removeAttr('id');

    if (options.anchor) {
      var anchorOpts = assign(
        {
          position: 'after',
          symbol: '#',
          style: 'header-anchor'
        }, options.anchor);

      //  Put the anchor after the title by default, unless says otherwise
      var link = '' + anchorOpts.symbol + '';
      if (anchorOpts.position === 'before') {
        $title.prepend(link);
      } else {
        $title.append(link);
      }
    }
  });

  data.content = $.html();

  // add class option
  if (options.class) {
    data.content = data.content.replace('

', '
').replace('

', '
');
  }

  return data;
};


text:
import React, { useState, useEffect } from 'react';
import { Project } from '../domain';
import { ProjectBarItem } from './ProjectBarItem';

export interface ProjectBarProps {
  runningProjects: Project[];
  maxItems?: number;
}

export const ProjectBar: React.FC<ProjectBarProps> = ({maxItems, runningProjects} = {maxItems: 10, runningProjects: []}) => {
  const [projectItems, setProjectItems] = useState<Project[]>([]);
  const projectCompareFn = (a: Project, b: Project) =>
    a.currentExecutionCycle && b.currentExecutionCycle
      ? b.currentExecutionCycle.startedAt.getTime() - a.currentExecutionCycle.startedAt.getTime()
      : b.id - a.id

  useEffect(() => {
    console.debug('ProjectBar#useEffect(runningProjects)');
    const sortedByStartedAt = [...runningProjects].sort(projectCompareFn);
    setProjectItems(sortedByStartedAt);
  }, [runningProjects]);

  const activeProject: Project | null = projectItems.length > 0 ? projectItems[0] : null;
  const otherRunningProjects: Project[] = projectItems.slice(1, maxItems);
  const dropdownProjects: Project[] = projectItems.slice(maxItems);

  return (
    <>
    {activeProject &&
    <ProjectBarItem
      key={projectItems[0].code}
      project={projectItems[0]}
    />}

    {otherRunningProjects.map(project => (
    <ProjectBarItem
      key={project.code}
      project={project}
    />
    ))}

    {dropdownProjects.length > 0 &&

      More

      {dropdownProjects.map(project => (
        <ProjectBarItem
          key={project.code}
          project={project}
        />
      ))}

}
    </>
  );
}


text:
package com.google.android.exoplayer.demo.debug;

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import com.google.android.exoplayer.demo.Demo;
import com.google.android.exoplayer.demo.R;
import com.google.android.exoplayer.demo.debug.model.MasterManifest;
import com.google.android.exoplayer.demo.debug.util.ManifestProvider;
import com.google.android.exoplayer.demo.debug.view.MasterManifestView;
import com.google.android.exoplayer.hls.HlsPlaylist;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

import static android.view.View.GONE;

public class MasterManifestDialogFragment extends DialogFragment implements MasterManifestView {

    public static final String MASTER_MANIFEST = "masterManifest";

    @Inject ManifestProvider manifestProvider;

    @Bind(R.id.type) TextView type;
    @Bind(R.id.baseUri) TextView baseUri;
    @Bind(R.id.audioSubtitle) View audioSubtitle;
    @Bind(R.id.variantSubtitle) View variantSubtitle;
    @Bind(R.id.subtitleSubtitle) View subtitleSubtitle;
    @Bind(R.id.muxedAudioLanguage) TextView muxedAudioLanguage;
    @Bind(R.id.muxedCaptionLanguate) TextView muxedCaptionLanguage;
    @Bind(R.id.variantContainer) ViewGroup variantContainer;
    @Bind(R.id.audioContainer) ViewGroup audioContainer;
    @Bind(R.id.subtitleContainer) ViewGroup subtitleContainer;

    private final List<VariantPresenter> variantPresenters = new ArrayList<>();
    private MasterManifestPresenter presenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((Demo) getActivity().getApplication()).getObjectGraph().inject(this);
        presenter = new MasterManifestPresenter((MasterManifest) getArguments().getSerializable(MASTER_MANIFEST));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_master_manifest, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.attachView(this);
        presenter.present();
    }

    @Override
    public void onPause() {
        presenter.detachView();
        for (VariantPresenter presenter : variantPresenters) {
            presenter.detachView();
        }
        variantPresenters.clear();
        variantContainer.removeAllViews();
        subtitleContainer.removeAllViews();
        audioContainer.removeAllViews();

        super.onPause();
    }

    @Override
    public void displayType(int type) {
        String typeText = getResources().getString(R.string.manifest_type, type == HlsPlaylist.TYPE_MASTER ? "MASTER" : "MEDIA");
        this.type.setText(typeText);
    }

    @Override
    public void displayBaseUri(String baseUri) {
        this.baseUri.setText(getResources().getString(R.string.manifest_base_uri, baseUri));
    }

    @Override
    public void displayMuxedAudioLanguage(String muxedAudioLanguage) {
        this.muxedAudioLanguage.setText(getResources().getString(R.string.manifest_muxed_audio_lang, muxedAudioLanguage));
    }

    @Override
    public void displayMuxedCaptionLanguage(String muxedCaptionLanguage) {
        this.muxedCaptionLanguage.setText(getResources().getString(R.string.manifest_muxed_caption_lang, muxedCaptionLanguage));
    }

    @Override
    public void hideVariantsSubtitle() {
        variantSubtitle.setVisibility(GONE);
    }

    @Override
    public void hideSubtitlesSubtitle() {
        subtitleSubtitle.setVisibility(GONE);
    }

    @Override
    public void hideAudioSubtitle() {
        audioSubtitle.setVisibility(GONE);
    }

    @Override
    public void displayVariants(List<MasterManifest.Variant> variants) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        for (MasterManifest.Variant variant : variants) {
            View divider = inflater.inflate(R.layout.divider, variantContainer, false);
            variantContainer.addView(divider);
            VariantLayout content = (VariantLayout) inflater.inflate(R.layout.view_variant, variantContainer, false);
            VariantPresenter presenter = new VariantPresenter(variant, manifestProvider);
            presenter.attachView(content);
            presenter.present();
            variantPresenters.add(presenter);
            variantContainer.addView(content);
        }
    }

    @Override
    public void displaySubtitleVariants(List<MasterManifest.Variant> variants) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        for (MasterManifest.Variant variant : variants) {
            View divider = inflater.inflate(R.layout.divider, subtitleContainer, false);
            subtitleContainer.addView(divider);
            VariantLayout content = (VariantLayout) inflater.inflate(R.layout.view_variant, subtitleContainer, false);
            VariantPresenter presenter = new VariantPresenter(variant, manifestProvider);
            presenter.attachView(content);
            presenter.present();
            variantPresenters.add(presenter);
            subtitleContainer.addView(content);
        }
    }

    @Override
    public void displayAudioVariants(List<MasterManifest.Variant> variants) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        for (MasterManifest.Variant variant : variants) {
            View divider = inflater.inflate(R.layout.divider, audioContainer, false);
            audioContainer.addView(divider);
            VariantLayout content = (VariantLayout) inflater.inflate(R.layout.view_variant, audioContainer, false);
            VariantPresenter presenter = new VariantPresenter(variant, manifestProvider);
            presenter.attachView(content);
            presenter.present();
            variantPresenters.add(presenter);
            audioContainer.addView(content);
        }
    }
}


text:
package librunner

import (
	"fmt"
	"os"
	"strconv"
	"sync"
	"syscall"
	"time"

	"github.com/coreos/go-systemd/activation"
	exterrors "github.com/mgoltzsche/ctnr/pkg/errors"
	"github.com/mgoltzsche/ctnr/pkg/log"
	"github.com/mgoltzsche/ctnr/run"
	"github.com/opencontainers/runc/libcontainer"
	"github.com/opencontainers/runc/libcontainer/configs"
	"github.com/opencontainers/runtime-spec/specs-go"
	"github.com/pkg/errors"
)

type Process struct {
	args      []string
	container *Container
	process   libcontainer.Process
	io        run.ContainerIO
	tty       *tty
	terminal  bool
	running   bool
	mutex     *sync.Mutex
	wait      *sync.WaitGroup
	log       log.Loggers
	err       error
}

func NewProcess(container *Container, p *specs.Process, io run.ContainerIO, loggers log.Loggers) (r *Process, err error) {
	// Create container process (see https://github.com/opencontainers/runc/blob/v1.0.0-rc4/utils_linux.go: startContainer->runner.run->newProcess)
	r = &Process{
		args:      p.Args,
		container: container,
		io:        io,
		terminal:  p.Terminal,
		mutex:     &sync.Mutex{},
		wait:      &sync.WaitGroup{},
		log:       loggers,
		process: libcontainer.Process{
			Args:            p.Args,
			Env:             p.Env,
			User:            fmt.Sprintf("%d:%d", p.User.UID, p.User.GID),
			Cwd:             p.Cwd,
			Stdout:          io.Stdout,
			Stderr:          io.Stderr,
			Stdin:           io.Stdin,
			AppArmorProfile: p.ApparmorProfile,
			Label:           p.SelinuxLabel,
			NoNewPrivileges: &p.NoNewPrivileges,
		},
	}
	lp := r.process
	for _, gid := range p.User.AdditionalGids {
		lp.AdditionalGroups = append(lp.AdditionalGroups, strconv.FormatUint(uint64(gid), 10))
	}
	if p.Capabilities != nil {
		lp.Capabilities = &configs.Capabilities{
			Bounding:    p.Capabilities.Bounding,
			Effective:   p.Capabilities.Effective,
			Inheritable: p.Capabilities.Inheritable,
			Permitted:   p.Capabilities.Permitted,
			Ambient:     p.Capabilities.Ambient,
		}
	}
	if p.Rlimits != nil {
		for _, rlimit := range p.Rlimits {
			rl, err := createLibContainerRlimit(rlimit)
			if err != nil {
				return nil, errors.New("new process: " + err.Error())
			}
			lp.Rlimits = append(lp.Rlimits, rl)
		}
	}
	if os.Getenv("LISTEN_FDS") != "" {
		// Add systemd file descriptors
		lp.ExtraFiles = activation.Files(false)
	}
	return
}

func (p *Process) Start() (err error) {
	if len(p.args) == 0 {
		return errors.New("start process: no args specified")
	}
	p.log.Debug.WithField("args", p.args).Println("Starting process")

	p.mutex.Lock()
	defer p.mutex.Unlock()
	defer exterrors.Wrapd(&err, "run process")

	if p.running {
		return errors.New("process already started")
	}

	// Configure stdIO/terminal
	p.tty, err = setupIO(&p.process, p.container.container, p.terminal, false, "")
	if err != nil {
		return
	}

	// Run container process
	if err = p.container.container.Run(&p.process); err != nil {
		p.tty.Close()
		return
	}
	p.running = true

	p.wait.Add(1)
	go p.handleTermination()
	return nil
}

func (p *Process) handleTermination() {
	defer p.wait.Done()

	// Wait for process
	_, err := p.process.Wait()

	err = run.NewExitError(err, p.container.ID())
	logger := p.log.Debug
	if exiterr, ok := err.(*run.ExitError); ok {
		logger = logger.WithField("code", exiterr.Code())
	}
	logger.WithField("args", p.args).Println("Process terminated")

	p.mutex.Lock()
	defer p.mutex.Unlock()

	// Register process error
	p.err = err

	// Release TTY
	// TODO: reject tty CLI option when process is detached and no console socket provided
	err = p.tty.Close() // ATTENTION: deadlock when detached process and tty enabled
	p.err = exterrors.Append(p.err, err)
	p.tty = nil
	p.running = false
}

func (c *Process) Stop() {
	if c.running {
		return
	}

	go c.stop()
}

func (p *Process) stop() bool {
	// Terminate container orderly
	p.mutex.Lock()

	if !p.running {
		p.mutex.Unlock()
		return false
	}

	p.log.Debug.WithField("args", p.args).Println("Stopping process")

	if err := p.process.Signal(syscall.SIGINT); err != nil {
		p.log.Debug.Println("Failed to send SIGINT to process:", err)
	}
	p.mutex.Unlock()

	quit := make(chan bool, 1)
	go func() {
		p.wait.Wait()
		quit <- true
	}()
	select {
	case <-time.After(time.Duration(10000000)): // TODO: read value from OCI runtime configuration
		// Kill container after timeout
		if p.running {
			p.log.Warn.WithField("args", p.args).Println("Killing process (stop timeout exceeded)")
			if err := p.process.Signal(syscall.SIGKILL); err != nil {
				errlog := p.log.Error
				if pid, e := p.process.Pid(); e == nil {
					errlog = errlog.WithField("pid", pid)
				}
				errlog.Println("Failed to kill process:", err)
			}
			p.wait.Wait()
		}
		<-quit
	case <-quit:
	}
	close(quit)
	return true
}

// Waits for the container process to terminate and returns the process' error if any
func (p *Process) Wait() (err error) {
	p.wait.Wait()
	p.mutex.Lock()
	defer p.mutex.Unlock()
	err = p.err
	p.err = nil
	return err
}

func (p *Process) Close() (err error) {
	p.stop()
	p.mutex.Lock()
	defer p.mutex.Unlock()
	if p.running {
		err = p.err
		p.err = nil
		if p.tty != nil {
			err = exterrors.Append(err, p.tty.Close())
			p.tty = nil
		}
	}
	return
}


text:
- https://xicode.se **magistern** (Teacher)
- https://devmaster64.com **devmaster64** (Software Developer)
- https://mickie1.gitlab.io/blog/ **mickie** (Engineer)
- https://calloc.net **Vaibhav Yenamandra** (Software Engineer)
- https://potatofrom.space **Kevin Liu** (Software)
- https://horochx.org **horochx** (Software Developer)
- https://feng.si **Si Feng** (Software Engineer)
- https://ben-on-vms.com **Benedikt Frenzel** (Technical Support Engineer)
- https://johngazzini.com **John Gazzini** (Software Engineer)
- https://geekx.tech/ **Sagar Ladla** (Student Developer & Cyber Security Specialist)
- https://tears.io/ **Alex** (SRE)
- https://ayushkarn.me/ **Ayush Karn** (Student Developer)
- https://ssgram.dev **Ramaseshan Parthasarathy** (Software Developer)
- https://zaine.me **Amine Zaine** (Cloud Engineer)
- https://notes.dmaitre.phyip3.dur.ac.uk/computing-club/ **Ryan Moodie** (Physics PhD student)
- https://thecodecousins.com **Stanley Nguyen** (Software Engineer) & **Hoang Do** (Software & IoT Engineer)
- https://schacherbauer.dev **Markus Schacherbauer** (Student Developer)
- https://rinma.dev **Marvin Dalheimer** (Software Developer)
- https://lunar.computer **Lunar Computer** (DevOps Engineer)
- https://naxxfish.net **Chris Roberts** (Broadcast Systems Engineer)
- https://security.jtang.dev **Jonathan Tang** (Student & Software Engineer)
- https://andreacaravano.net **Andrea Caravano** (Student)
- https://dawsonverboven.com/ **Dawson Verboven** (Student & Software Developer)
- https://qbunt.com **Jeremy Bunting** (Software Engineer)
- https://smeik.org **Smeik** (Embedded Developer)
- https://code.willstocks.co.uk **Will Stocks** (Blogger & Developer)
- https://blog.vnandag.me **Nanda Gopal** (Student Developer)
- https://m47r1x.github.io **Neo** (Citizen of Zion)
- https://bgameiro.me/ **Bernardo Gameiro** (Engineer Physicist student)
- https://return-to-libc.com/ **elraro** (Cyber Security Specialist)
- https://pablart.com/ **Pablo Diaz-Gutierrez** (Software Engineer, General Tinkerer)
- https://waterloos.niflheimr.blue/ **cindrmon** (Student and Aspiring Software Engineer)
- https://monocle.rpod.club/ **classx** (DevOps Engineer)
- https://wjdevschool.com/ **Wojciech Bogócki** (Making Things & Teaching / W&J Dev School)
- https://erisianrite.com/ **ErisianRite** (Coding, Engineering, Tools for Thought)
- https://dongzhi.me **Joe** (Software Developer)
- https://isaes.com.tr/ **Isa Es** (Software Engineer)
- https://conight.com **Conight Wang** (Software Engineer)
- https://blog.m5e.de/ **Christoph Miksche** (Software Developer)
- https://mpostument.com/ **Maksym Postument** (DevOps Engineer)
- https://mathiejosh.xyz **Josh Mathie** (Electrical Engineering Technology Student/Sales and Engineering Tech)
- https://yuji.ne.jp/ **YUJI** (Student & Software Developer)
- https://blog.puvvadi.me **KD Puvvadi** (Software Dev & Cloud Orchestrator)
- https://hidden.land/ **Louisload** (Game Developer & Musician)
- https://linuxbase.nl **Michael Trip** (DevOps Engineer)
- https://markopolo123.github.io **Markopolo** (DevOps Engineer)
- https://openfoxblog.leven.dev/ **Damon Leven** (Student & Software Developer)
- https://blog.sethforprivacy.com **Seth For Privacy** (Security, privacy, and cryptocurrency writer, podcaster)
- https://thesprawl.city **crish** (Software and stuff)
- https://justinnuwin.com **Justin Nguyen** (Software & Hardware Developer)
- https://blog.woosal.com/ **Vusal Ismayilov** (Computer Engineering Student)
- https://itsembedded.com/  **Norbert Kremeris** (digital logic design and verification engineer)
- https://nereuxofficial.github.io **Nereuxofficial** (Software Developer & Student)
- https://biplav.xyz **Biplav's Blog** (Student)
- https://santiago.wtf **Nicholas Santiago** (DevOps Engineer)
- https://2200g.github.io/ **2200g** (Blogger/Student)
- https://cristiioan.me **Cristian Margine** (Student)
- https://they.mint.lgbt **Joey Aliaga** (Software Developer & Student)
- https://tatewilhelm.me **Tate Wilhelm** (Student, Programmer & Tinkerer)
- https://mikefoden.com **Mike Foden** (Software Developer)
- https://undemalum.github.io/portfolio/ **Mateusz Konat** (Student)
- https://ku0hn.radio **Ben Kuhn** (Ham Radio Operator, InfoSec Engineer, Tinkerer)
- https://bg117.xyz/projects **bg117** (Student and Hobby Programmer)
- https://www.grumpymetalguy.com **GrumpyMetalGuy** (General Grumper and Developer)
- https://blog.jontes.page **Jonte** (general tech geek)
- https://nazdarthegame.com/ **Michal Skoula** (Software Developer)

<!--
 TEMPLATE:

 - https://radoslawkoziel.pl **Radek Kozieł** (Software Designer and Developer)

 -->


text:
<?php

namespace PHPExiftool\Driver\Tag\ExifIFD;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class MDSampleInfo extends AbstractTag
{

    protected $Id = 33449;

    protected $Name = 'MDSampleInfo';

    protected $FullName = 'Exif::Main';

    protected $GroupName = 'ExifIFD';

    protected $g0 = 'EXIF';

    protected $g1 = 'IFD0';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'MD Sample Info';

    protected $local_g1 = 'ExifIFD';

}


text:
using UnityEngine;
using System.Collections;

public class TerrainManager : TileGen {

	// Use this for initialization
	void Start () {

		//Generate (detailScale,heightScale,0,0);

		//Generate (detailScale,heightScale,transform.position.x,transform.position.z);
		for (int x=0; x < 25;x++){

		for (int z=0; z < 25;z++){
					Generate (detailScale,heightScale,x,z);
//			Generate (detailScale,heightScale,-x,z);
//				Generate (detailScale,heightScale,x,-z);
//				Generate (detailScale,heightScale,-x,-z);

			}

		}

//		Generate (detailScale,heightScale,0f,0f);
//		Generate (detailScale,heightScale,100f,0f);
//		Generate (detailScale,heightScale,100f,100f);
//		Generate (detailScale,heightScale,0f,-100f);
//		Generate (detailScale,heightScale,-100f,0f);
//		Generate (detailScale,heightScale,-100f,-100f);

	}

	// Update is called once per frame
	void Update () {

	}
}


text:
package org.xtreemfs.common.monitoring;

import javax.management.MBeanServer;

import org.xtreemfs.common.monitoring.StatusMonitor.ServiceTypes;
import org.xtreemfs.common.monitoring.generatedcode.Dir;

import com.sun.management.snmp.SnmpStatusException;

/**
 * This class represents the monitoring information exposed by the SNMP agent regarding to the
 * Directory Service.
 *
 */
@SuppressWarnings("serial")
public class DirImpl extends Dir {

    private StatusMonitor statusMonitor;

    public DirImpl(XTREEMFS_MIBImpl myMib, StatusMonitor statusMonitor) {
        super(myMib);

        AddressMappingCount = 0;
        ServiceCount = 0;

        this.statusMonitor = statusMonitor;
        // Set a reference to this Object to be able to access it within
        // the application
        statusMonitor.setDirGroup(this);
    }

    public DirImpl(XTREEMFS_MIBImpl myMib, MBeanServer server, StatusMonitor statusMonitor) {
        super(myMib, server);

        AddressMappingCount = 0;
        ServiceCount = 0;

        this.statusMonitor = statusMonitor;
        // Set a reference to this Object to be able to access it within
        // the application
        statusMonitor.setDirGroup(this);
    }

    /**
     * This method will be called when a AddressMapping is registered at the DIR.
     **/
    protected void addressMappingAdded() {
        AddressMappingCount++;
    }

    /**
     * This method will be called when a AddressMapping is deregistered at the DIR.
     **/
    protected void addressMappingDeleted() {
        AddressMappingCount--;
    }

    /**
     * This method will be called when a Service is registered at the DIR.
     **/
    protected void serviceRegistered() {
        ServiceCount++;
    }

    /**
     * This method will be called when a Service is deregistered at the DIR.
     **/
    protected void serviceDeregistered() {
        ServiceCount--;
    }

    @Override
    public Integer getServiceCount() throws SnmpStatusException {
        if (!statusMonitor.getInitiatingService().equals(ServiceTypes.DIR)) {
            throw new SnmpStatusException(SnmpStatusException.noSuchName);
        }
        return ServiceCount;
    }

    @Override
    public Integer getAddressMappingCount() throws SnmpStatusException {
        if (!statusMonitor.getInitiatingService().equals(ServiceTypes.DIR)) {
            throw new SnmpStatusException(SnmpStatusException.noSuchName);
        }
        return AddressMappingCount;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">EncPassChanger</string>
    <string name="app_description">This app allows users of Android 4.0+ to set device encryption password different from screen unlock password</string>

    <string name="go_button">Go!</string>
    <string name="txt_type_old_pass">For security, type your old password</string>
    <string name="hello">Type new password:</string>
    <string name="pass_once_again">And once again, please!</string>

    <string name="su_fail">Getting root rights failed!</string>
    <string name="exec_fail">Execution failure</string>
    <string name="unk_error">(unknown error)</string>
    <string name="verify_error">VolManager does not like this password</string>
    <string name="enc_verify_error">VolManager does not give us encryption state</string>
    <string name="enc_not_enabled">Looks like disk encryption is not turned on!</string>
    <string name="error_when_changing">Error while changing password! Please change Screen Lock password in Settings/Security/Screen Lock!</string>
    <string name="password_changed">Password changed OK! Now you can use this password for decrypting device after boot</string>

    <string name="pass_incorrect">Old password is incorrect!</string>
    <string name="new_pass_incorrect">ERROR! Password was changed, but VDC doesn\'t accept it! Please change password MANUALLY in Settings/Security/Screen Lock!</string>
    <string name="pass_empty">Empty passwords are not allowed!</string>
    <string name="newpass_not_the_same">Please, enter EXACT passwords in "New Password" fields!</string>
    <string name="copyright">© Kibab 2012 | http://kibab.com</string>
    <string name="debuglabel">Debug output</string>
</resources>


text:
import abc
import eventlet
import six

from kombu.mixins import ConsumerMixin

from st2common import log as logging
from st2common.util.greenpooldispatch import BufferedDispatcher

LOG = logging.getLogger(__name__)

class QueueConsumer(ConsumerMixin):
    def __init__(self, connection, queues, handler):
        self.connection = connection
        self._dispatcher = BufferedDispatcher()
        self._queues = queues
        self._handler = handler

    def shutdown(self):
        self._dispatcher.shutdown()

    def get_consumers(self, Consumer, channel):
        consumer = Consumer(queues=self._queues, accept=['pickle'], callbacks=[self.process])

        # use prefetch_count=1 for fair dispatch. This way workers that finish an item get the next
        # task and the work does not get queued behind any single large item.
        consumer.qos(prefetch_count=1)

        return [consumer]

    def process(self, body, message):
        try:
            self._dispatcher.dispatch(self._process_message, body)
        finally:
            message.ack()

    def _process_message(self, body):
        try:
            if not isinstance(body, self._handler.message_type):
                raise TypeError('Received an unexpected type "%s" for payload.' % type(body))

            self._handler.process(body)
        except:
            LOG.exception('%s failed to process message: %s', self.__class__.__name__, body)

@six.add_metaclass(abc.ABCMeta)
class MessageHandler(object):
    message_type = None

    def __init__(self, connection, queues):
        self._queue_consumer = QueueConsumer(connection, queues, self)
        self._consumer_thread = None

    def start(self, wait=False):
        LOG.info('Starting %s...', self.__class__.__name__)
        self._consumer_thread = eventlet.spawn(self._queue_consumer.run)

        if wait:
            self.wait()

    def wait(self):
        self._consumer_thread.wait()

    def shutdown(self):
        LOG.info('Shutting down %s...', self.__class__.__name__)
        self._queue_consumer.shutdown()

    @abc.abstractmethod
    def process(self, message):
        pass


text:
cms.test_utils.project.extensionapp package
===========================================

Subpackages
-----------

.. toctree::

    cms.test_utils.project.extensionapp.migrations_django

Submodules
----------

cms.test_utils.project.extensionapp.admin module
------------------------------------------------

.. automodule:: cms.test_utils.project.extensionapp.admin
    :members:
    :undoc-members:
    :show-inheritance:

cms.test_utils.project.extensionapp.cms_toolbar module
------------------------------------------------------

.. automodule:: cms.test_utils.project.extensionapp.cms_toolbar
    :members:
    :undoc-members:
    :show-inheritance:

cms.test_utils.project.extensionapp.models module
-------------------------------------------------

.. automodule:: cms.test_utils.project.extensionapp.models
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: cms.test_utils.project.extensionapp
    :members:
    :undoc-members:
    :show-inheritance:


text:
Succeeds if the specified parser succeeds, ignoring any whitespace characters beforehand or afterward.

```csharp
public static IParser<T> Trim<T>(this IParser<T> parser)
```

## See Also

* interface [IParser<T>](../IParser-1.md)
* class [Parser](../Parser.md)
* namespace [Faithlife.Parsing](../../Faithlife.Parsing.md)

<!-- DO NOT EDIT: generated by xmldocmd for Faithlife.Parsing.dll -->


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../syn/struct.ParenthesizedGenericArguments.html">
    <title>Redirection</title>

Redirecting to ../../syn/struct.ParenthesizedGenericArguments.html...


text:
.class Landroid/support/v4/provider/TreeDocumentFile;
.super Landroid/support/v4/provider/DocumentFile;
.source "TreeDocumentFile.java"

# instance fields
.field private mContext:Landroid/content/Context;

.field private mUri:Landroid/net/Uri;

# direct methods
.method constructor <init>(Landroid/support/v4/provider/DocumentFile;Landroid/content/Context;Landroid/net/Uri;)V
    .locals 0
    .param p1, "parent"    # Landroid/support/v4/provider/DocumentFile;
    .param p2, "context"    # Landroid/content/Context;
    .param p3, "uri"    # Landroid/net/Uri;

    .prologue
    .line 27
    invoke-direct {p0, p1}, Landroid/support/v4/provider/DocumentFile;-><init>(Landroid/support/v4/provider/DocumentFile;)V

    .line 28
    iput-object p2, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    .line 29
    iput-object p3, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    .line 26
    return-void
.end method

# virtual methods
.method public canRead()Z
    .locals 2

    .prologue
    .line 81
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->canRead(Landroid/content/Context;Landroid/net/Uri;)Z

    move-result v0

    return v0
.end method

.method public canWrite()Z
    .locals 2

    .prologue
    .line 86
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->canWrite(Landroid/content/Context;Landroid/net/Uri;)Z

    move-result v0

    return v0
.end method

.method public createDirectory(Ljava/lang/String;)Landroid/support/v4/provider/DocumentFile;
    .locals 4
    .param p1, "displayName"    # Ljava/lang/String;

    .prologue
    const/4 v1, 0x0

    .line 40
    iget-object v2, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v3, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v2, v3, p1}, Landroid/support/v4/provider/DocumentsContractApi21;->createDirectory(Landroid/content/Context;Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    .line 41
    .local v0, "result":Landroid/net/Uri;
    if-eqz v0, :cond_0

    new-instance v1, Landroid/support/v4/provider/TreeDocumentFile;

    iget-object v2, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    invoke-direct {v1, p0, v2, v0}, Landroid/support/v4/provider/TreeDocumentFile;-><init>(Landroid/support/v4/provider/DocumentFile;Landroid/content/Context;Landroid/net/Uri;)V

    :cond_0
    return-object v1
.end method

.method public createFile(Ljava/lang/String;Ljava/lang/String;)Landroid/support/v4/provider/DocumentFile;
    .locals 4
    .param p1, "mimeType"    # Ljava/lang/String;
    .param p2, "displayName"    # Ljava/lang/String;

    .prologue
    const/4 v1, 0x0

    .line 34
    iget-object v2, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v3, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v2, v3, p1, p2}, Landroid/support/v4/provider/DocumentsContractApi21;->createFile(Landroid/content/Context;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    .line 35
    .local v0, "result":Landroid/net/Uri;
    if-eqz v0, :cond_0

    new-instance v1, Landroid/support/v4/provider/TreeDocumentFile;

    iget-object v2, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    invoke-direct {v1, p0, v2, v0}, Landroid/support/v4/provider/TreeDocumentFile;-><init>(Landroid/support/v4/provider/DocumentFile;Landroid/content/Context;Landroid/net/Uri;)V

    :cond_0
    return-object v1
.end method

.method public delete()Z
    .locals 2

    .prologue
    .line 91
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->delete(Landroid/content/Context;Landroid/net/Uri;)Z

    move-result v0

    return v0
.end method

.method public exists()Z
    .locals 2

    .prologue
    .line 96
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->exists(Landroid/content/Context;Landroid/net/Uri;)Z

    move-result v0

    return v0
.end method

.method public getName()Ljava/lang/String;
    .locals 2

    .prologue
    .line 51
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->getName(Landroid/content/Context;Landroid/net/Uri;)Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public getType()Ljava/lang/String;
    .locals 2

    .prologue
    .line 56
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->getType(Landroid/content/Context;Landroid/net/Uri;)Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public getUri()Landroid/net/Uri;
    .locals 1

    .prologue
    .line 46
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    return-object v0
.end method

.method public isDirectory()Z
    .locals 2

    .prologue
    .line 61
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->isDirectory(Landroid/content/Context;Landroid/net/Uri;)Z

    move-result v0

    return v0
.end method

.method public isFile()Z
    .locals 2

    .prologue
    .line 66
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->isFile(Landroid/content/Context;Landroid/net/Uri;)Z

    move-result v0

    return v0
.end method

.method public lastModified()J
    .locals 2

    .prologue
    .line 71
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->lastModified(Landroid/content/Context;Landroid/net/Uri;)J

    move-result-wide v0

    return-wide v0
.end method

.method public length()J
    .locals 2

    .prologue
    .line 76
    iget-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v0, v1}, Landroid/support/v4/provider/DocumentsContractApi19;->length(Landroid/content/Context;Landroid/net/Uri;)J

    move-result-wide v0

    return-wide v0
.end method

.method public listFiles()[Landroid/support/v4/provider/DocumentFile;
    .locals 6

    .prologue
    .line 101
    iget-object v3, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v4, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v3, v4}, Landroid/support/v4/provider/DocumentsContractApi21;->listFiles(Landroid/content/Context;Landroid/net/Uri;)[Landroid/net/Uri;

    move-result-object v1

    .line 102
    .local v1, "result":[Landroid/net/Uri;
    array-length v3, v1

    new-array v2, v3, [Landroid/support/v4/provider/DocumentFile;

    .line 103
    .local v2, "resultFiles":[Landroid/support/v4/provider/DocumentFile;
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    array-length v3, v1

    if-ge v0, v3, :cond_0

    .line 104
    new-instance v3, Landroid/support/v4/provider/TreeDocumentFile;

    iget-object v4, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    aget-object v5, v1, v0

    invoke-direct {v3, p0, v4, v5}, Landroid/support/v4/provider/TreeDocumentFile;-><init>(Landroid/support/v4/provider/DocumentFile;Landroid/content/Context;Landroid/net/Uri;)V

    aput-object v3, v2, v0

    .line 103
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 106
    :cond_0
    return-object v2
.end method

.method public renameTo(Ljava/lang/String;)Z
    .locals 3
    .param p1, "displayName"    # Ljava/lang/String;

    .prologue
    .line 111
    iget-object v1, p0, Landroid/support/v4/provider/TreeDocumentFile;->mContext:Landroid/content/Context;

    iget-object v2, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    invoke-static {v1, v2, p1}, Landroid/support/v4/provider/DocumentsContractApi21;->renameTo(Landroid/content/Context;Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    .line 112
    .local v0, "result":Landroid/net/Uri;
    if-eqz v0, :cond_0

    .line 113
    iput-object v0, p0, Landroid/support/v4/provider/TreeDocumentFile;->mUri:Landroid/net/Uri;

    .line 114
    const/4 v1, 0x1

    return v1

    .line 116
    :cond_0
    const/4 v1, 0x0

    return v1
.end method


text:
package org.igye.learnpl2.controllers

import java.io.File
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.scene.control.{Button, TextField}
import javafx.scene.input.KeyCode._
import javafx.scene.layout.StackPane
import javafx.stage.{FileChooser, Modality}

import org.apache.commons.lang3.StringUtils
import org.apache.logging.log4j.{LogManager, Logger}
import org.igye.jfxutils.action.ActionType.HANDLER
import org.igye.jfxutils.action.{Action, Shortcut}
import org.igye.jfxutils.annotations.FxmlFile
import org.igye.jfxutils.concurrency.RunInJfxThreadForcibly
import org.igye.jfxutils.fxml.Initable
import org.igye.jfxutils.{JfxUtils, Window}

import scala.concurrent.ExecutionContext.Implicits.global

@FxmlFile("fxml/ChoseFileDialog.fxml")
class ChoseFileDialog extends Window with Initable {
    implicit val log: Logger = LogManager.getLogger()

    private var resultHandler: String => Unit = _

    @FXML
    protected var rootNode: StackPane = _
    @FXML
    protected var filePathTextField: TextField = _
    @FXML
    protected var cancelBtn: Button = _
    @FXML
    protected var openDialogBtn: Button = _
    @FXML
    protected var okBtn: Button = _

    private val fileChooser = new FileChooser()

    private val cancelAction = new Action {
        override val description = "Cancel"
        setShortcut(Shortcut(ESCAPE))
        actionType = HANDLER
        override protected def onAction(): Unit = {
            close()
        }
    }

    private val okAction = new Action {
        override val description = "Choose selected file"
        setShortcut(Shortcut(ENTER))
        actionType = HANDLER
        override protected def onAction(): Unit = {
            close()
            resultHandler(filePathTextField.getText)
        }
    }

    private val actions = List(
        cancelAction,
        okAction
    )

    override def init(): Unit = {
        require(rootNode != null)
        require(filePathTextField != null)
        require(openDialogBtn != null)
        require(cancelBtn != null)
        require(okBtn != null)

        initWindow(rootNode)
        stage.initModality(Modality.APPLICATION_MODAL)

        Action.bind(cancelAction, cancelBtn)
        Action.bind(okAction, okBtn)
        JfxUtils.bindActionsToSceneProp(rootNode.sceneProperty(), actions)

        JfxUtils.bindFileChooser(filePathTextField, 300, 300)
    }

    def openChooseFileDialog(event: ActionEvent): Unit = {
        fileChooser.setInitialDirectory(getInitialDirectory)
        val file = fileChooser.showOpenDialog(stage)
        if (file != null) {
            filePathTextField.setText(file.getAbsolutePath)
        }
    }

    private def getInitialDirectory: File = {
        val file = new File(StringUtils.defaultIfEmpty(filePathTextField.getText, ""))
        if (file.exists()) {
            if (file.isDirectory) {
                file
            } else {
                file.getParentFile
            }
        } else {
            null
        }
    }

    def open(initPath: String, resultHandler: String => Unit): Unit = {
        filePathTextField.setText(initPath)
        this.resultHandler = resultHandler
        open()
        RunInJfxThreadForcibly {
            filePathTextField.positionCaret(filePathTextField.getText.length)
        }
    }
}


text:
int f() {
	try {
		int sockfd = socket(AF_INET, SOCK_STREAM, 0);
		do_stuff(sockfd);
		return sockfd; //if there are no exceptions, the socket is returned
	} catch (int do_stuff_exception) {
		return -1; //return error value, but sockfd may still be open
	}
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: scottw
 * Date: 11/2/11
 * Time: 4:49 PM
 * To change this template use File | Settings | File Templates.
 */

namespace Application\Model;

class AttributeType extends ModelAbstract
{
    const PRIMARY_ID_KEY  = 'attributeTypeId';
    const LABEL_FIELD_NAME = 'name';
    const DATA_TYPE_NAME   = 'attributeType';

    protected static $_dataMapperName = 'AttributeTypeMapper';

    /**
     * @var int
     */
    public $attributeTypeId;
    /**
     * @var array
     */
    protected static $_dataStruct = array(
        'name'		=> null,
        'description' => null
    );

    /**
     * @param null|int|array $data
     */
    public function __construct($data=null) {
        if(is_int($data) &&(intval($data)>0)) {
            $pId = self::_getPrimaryIdKey();
            $data = array($pId => intval($data));
        }
        $this->_data = self::$_dataStruct;
        parent::__construct($data);
    }
}


text:
namespace TestCases.HSSF.Record
{
    using System;
    using NPOI.HSSF.Record;

    using NUnit.Framework;

    /**
     * Tests the serialization and deserialization of the NoteRecord
     * class works correctly.  Test data taken directly from a real
     * Excel file.
     *
     * @author Yegor Kozlov
     */
    [TestFixture]
    public class TestNoteStructureSubRecord
    {
        private byte[] data = new byte[] {
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x80, 0x00, 0x00, 0x00,
            0x00, 0x00, (byte)0xBF, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)0x81, 0x01,
            (byte)0xCC, (byte)0xEC
        };

        public TestNoteStructureSubRecord()
        {

        }
        [Test]
        public void TestRead()
        {

            NoteStructureSubRecord record = new NoteStructureSubRecord(TestcaseRecordInputStream.Create(NoteStructureSubRecord.sid, data),data.Length);

            Assert.AreEqual(NoteStructureSubRecord.sid, record.Sid);
            Assert.AreEqual(data.Length , record.DataSize);

        }
        [Test]
        public void TestWrite()
        {
            NoteStructureSubRecord record = new NoteStructureSubRecord();
            Assert.AreEqual(NoteStructureSubRecord.sid, record.Sid);
            Assert.AreEqual(data.Length , record.DataSize);

            byte[] ser = record.Serialize();
            Assert.AreEqual(ser.Length - 4, data.Length);

        }
        [Test]
        public void TestClone()
        {
            NoteStructureSubRecord record = new NoteStructureSubRecord();
            byte[] src = record.Serialize();

            NoteStructureSubRecord cloned = (NoteStructureSubRecord)record.Clone();
            byte[] cln = cloned.Serialize();

            Assert.AreEqual(record.DataSize, cloned.DataSize);
            Assert.IsTrue(NPOI.Util.Arrays.Equals(src, cln));
        }
    }
}


text:
require 'test_helper'

class PreferenceTest < ActiveSupport::TestCase
  fixtures :users, :preferences

  def setup
    @admin_user = User.find(1)
    @other_user = User.find(2)
  end

  def test_time_zone
    assert_equal 'London', @admin_user.preference.time_zone
  end

  def test_show_project_on_todo_done
    assert @other_user.preference.show_project_on_todo_done
    assert !@admin_user.preference.show_project_on_todo_done
  end

  def test_parse_date
    date = UserTime.new(@admin_user).midnight(Time.new(2007, 05, 20, 0, 0, 0))
    assert_equal date.to_s, @admin_user.preference.parse_date('20/5/2007').to_s
  end

  def test_parse_date_returns_nil_if_string_is_empty
    assert_nil @admin_user.preference.parse_date('')
  end

  def test_parse_date_returns_nil_if_string_is_nil
    assert_nil @admin_user.preference.parse_date(nil)
  end

end


text:
import sqlite3
import json
import logging
import time
import os
import sys
import hashlib
import gzip

class dump_to_db(object):

    def process(self,input,output,key_fields,model,process_history=True):

        conn = sqlite3.connect(output)
        c = conn.cursor()
        c.execute("""CREATE TABLE IF NOT EXISTS data
                     (timestamp real, key text primary key, value text, dirty smallint, remote_key text )""")
        c.execute("""CREATE UNIQUE INDEX IF NOT EXISTS data_idx ON data(key)""")

        history = []
        to_insert = []
        to_update = []
        if input.endswith('.gz'):
            infile = gzip.GzipFile(input)
        else:
            infile = file(input)
        for line in infile:
            line = line.strip()
            data = json.loads(line)
            key = "/".join("%s:%s" % (field,data[field]) for field in key_fields)
            history_key = { field:data[field] for field in key_fields }
            #key = hashlib.md5(key.encode('utf8')).hexdigest()
            current = c.execute("""SELECT value from data where key=?""",(key,)).fetchone()
            if current is None:
                if process_history:
                    history.append({
                        'model': model,
                        'selector': history_key,
                        'selector_key': key,
                        'time' : time.time(),
                        'field': None,
                        'from_value': None,
                        'to_value': None,
                        'created': True
                    })
                    if data.has_key('history'):
                        for h in data['history']:
                            try:
                                date = time.mktime(time.strptime(h['date'],"%d/%m/%Y"))
                                if h['field'] == 'creation':
                                    history.append({
                                        'model': model,
                                        'selector': history_key,
                                        'selector_key': key,
                                        'time' : date,
                                        'field': None,
                                        'from_value': None,
                                        'to_value': None,
                                        'created': True,
                                    })
                                else:
                                    history.append({
                                        'model': model,
                                        'selector': history_key,
                                        'selector_key': key,
                                        'time' : date,
                                        'field': h['field'],
                                        'from_value' : h['from'],
                                        'to_value'   : h['to'],
                                        'created': False
                                    })
                            except Exception, e:
                                logging.warn("%s/%s: Failed to parse history item %r (%r)" % (model,key,h,e) )
                                pass
                        del data['history']
                        line = json.dumps(data, sort_keys=True)
                to_insert.append( (time.time(), key, line, 1, None) )
            else:
                if current[0] != line:
                    if process_history:
                        current = json.loads(current[0])
                        for k,v in data.iteritems():
                            if current.get(k) != v:
                                history.append({
                                    'model': model,
                                    'selector': history_key,
                                    'selector_key': key,
                                    'field': k,
                                    'from_value' : current.get(k),
                                    'to_value'   : v,
                                    'time' : time.time(),
                                    'created': False
                                })
                    to_update.append( (time.time(), line, 1, key))
        if len(to_insert)>0:
            c.executemany("""INSERT OR REPLACE INTO data VALUES(?,?,?,?,?)""", to_insert)
        if len(to_update)>0:
            c.executemany("""UPDATE data SET timestamp=?,value=?,dirty=? WHERE key=?""", to_update)

        os.utime(output, None)

        if len(to_insert)>0 or len(to_update)>0:
            file(output+'.updated', 'w').write('OK')

        logging.debug("Added %s records" % len(to_insert))
        logging.debug("Modified %s records" % len(to_update))

        conn.commit()
        conn.close()

        if len(history) > 0:
            change_history = file('change_history.jsons','a')
            for h in history:
                change_history.write(json.dumps(h,sort_keys=True)+'\n')

if __name__ == "__main__":
    input = sys.argv[1]
    output = sys.argv[2]
    key_fields = sys.argv[3:]
    processor = dump_to_db().process(input,output,key_fields)


text:
"""
This file is part of the tractor library.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.

Created on Jan 06, 2012.
"""

from .api import DummyTractor
from .api import Tractor
from ConfigParser import ParsingError
from ConfigParser import SafeConfigParser
from StringIO import StringIO

__docformat__ = 'reStructuredText en'
__all__ = ['TractorConfig'
           'make_api_from_config',
           'make_api']

class TractorConfig(object):
    """
    Custom config parser for tractor configurations.
    """

    BASE_KEYS = ['realm', 'username', 'password']
    REQUIRED_KEYS = set(BASE_KEYS)
    KEYS = set(BASE_KEYS + ['load_dummy'])

    def __init__(self):
        self.settings = {}

    def parse(self, text):
        """
        Parses the given configuration. Asserts that all required keys and
        no invalid keys were specified in the configuration.

        :param text: configuration to parse
        :type text: string or open file
        """
        if not hasattr(text, 'readline'):
            text = StringIO(text)
        ini_parser = SafeConfigParser()
        ini_parser.readfp(text)
        if 'tractor' in ini_parser.sections():
            found_req_keys = []
            invalid_keys = []
            for key, value in ini_parser.items('tractor'):
                if not key in self.KEYS:
                    invalid_keys.append(key)
                    continue
                if key in self.REQUIRED_KEYS:
                    found_req_keys.append(key)
                self.settings[key] = value
            #
            if invalid_keys:
                raise ParsingError('Found invalid keys in [tractor] '
                                   'config section: %s' % (invalid_keys,))
            diff = self.REQUIRED_KEYS.difference(found_req_keys)
            if diff:
                raise ParsingError('Not all required keys found in [tractor] '
                                   'config section (found: %s, missing: %s).'
                                    % (found_req_keys, list(diff)))

def make_api_from_config(config_file):
    """
    Creates a config file from the settings defined in a section named
    'tractor' in the given config file.

    :returns: :class:`TractorApi` instance
    """
    fp = open(config_file, 'r')
    cnf = TractorConfig()
    cnf.parse(fp)
    return make_api(**cnf.settings)

def make_api(**settings):
    """
    Creates a new tractor API object from the given settings.

    :returns: :class:`TractorApi` instance
    """
    if settings.has_key('load_dummy'):
        load_dummy = settings['load_dummy']
        del settings['load_dummy']
    else:
        load_dummy = False

    if load_dummy:
        return DummyTractor(**settings)
    else:
        return Tractor(**settings)


text:
/**
 * HasDestinationUrlCreative.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.dfp.axis.v201602;

/**
 * A {@code Creative} that has a destination url
 */
public abstract class HasDestinationUrlCreative  extends com.google.api.ads.dfp.axis.v201602.Creative  implements java.io.Serializable {
    /* The URL that the user is directed to if they click on the creative.
     * This
     *                     attribute is required and has a maximum length
     * of 1024 characters. */
    private java.lang.String destinationUrl;

    /* The action that should be performed if the user clicks on the
     * creative.
     *                     This attribute is optional and defaults to {@link
     * DestinationUrlType#CLICK_TO_WEB}. */
    private com.google.api.ads.dfp.axis.v201602.DestinationUrlType destinationUrlType;

    public HasDestinationUrlCreative() {
    }

    public HasDestinationUrlCreative(
           java.lang.Long advertiserId,
           java.lang.Long id,
           java.lang.String name,
           com.google.api.ads.dfp.axis.v201602.Size size,
           java.lang.String previewUrl,
           com.google.api.ads.dfp.axis.v201602.CreativePolicyViolation[] policyViolations,
           com.google.api.ads.dfp.axis.v201602.AppliedLabel[] appliedLabels,
           com.google.api.ads.dfp.axis.v201602.DateTime lastModifiedDateTime,
           com.google.api.ads.dfp.axis.v201602.BaseCustomFieldValue[] customFieldValues,
           java.lang.String destinationUrl,
           com.google.api.ads.dfp.axis.v201602.DestinationUrlType destinationUrlType) {
        super(
            advertiserId,
            id,
            name,
            size,
            previewUrl,
            policyViolations,
            appliedLabels,
            lastModifiedDateTime,
            customFieldValues);
        this.destinationUrl = destinationUrl;
        this.destinationUrlType = destinationUrlType;
    }

    /**
     * Gets the destinationUrl value for this HasDestinationUrlCreative.
     *
     * @return destinationUrl   * The URL that the user is directed to if they click on the creative.
     * This
     *                     attribute is required and has a maximum length
     * of 1024 characters.
     */
    public java.lang.String getDestinationUrl() {
        return destinationUrl;
    }

    /**
     * Sets the destinationUrl value for this HasDestinationUrlCreative.
     *
     * @param destinationUrl   * The URL that the user is directed to if they click on the creative.
     * This
     *                     attribute is required and has a maximum length
     * of 1024 characters.
     */
    public void setDestinationUrl(java.lang.String destinationUrl) {
        this.destinationUrl = destinationUrl;
    }

    /**
     * Gets the destinationUrlType value for this HasDestinationUrlCreative.
     *
     * @return destinationUrlType   * The action that should be performed if the user clicks on the
     * creative.
     *                     This attribute is optional and defaults to {@link
     * DestinationUrlType#CLICK_TO_WEB}.
     */
    public com.google.api.ads.dfp.axis.v201602.DestinationUrlType getDestinationUrlType() {
        return destinationUrlType;
    }

    /**
     * Sets the destinationUrlType value for this HasDestinationUrlCreative.
     *
     * @param destinationUrlType   * The action that should be performed if the user clicks on the
     * creative.
     *                     This attribute is optional and defaults to {@link
     * DestinationUrlType#CLICK_TO_WEB}.
     */
    public void setDestinationUrlType(com.google.api.ads.dfp.axis.v201602.DestinationUrlType destinationUrlType) {
        this.destinationUrlType = destinationUrlType;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof HasDestinationUrlCreative)) return false;
        HasDestinationUrlCreative other = (HasDestinationUrlCreative) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = super.equals(obj) &&
            ((this.destinationUrl==null && other.getDestinationUrl()==null) ||
             (this.destinationUrl!=null &&
              this.destinationUrl.equals(other.getDestinationUrl()))) &&
            ((this.destinationUrlType==null && other.getDestinationUrlType()==null) ||
             (this.destinationUrlType!=null &&
              this.destinationUrlType.equals(other.getDestinationUrlType())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = super.hashCode();
        if (getDestinationUrl() != null) {
            _hashCode += getDestinationUrl().hashCode();
        }
        if (getDestinationUrlType() != null) {
            _hashCode += getDestinationUrlType().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(HasDestinationUrlCreative.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "HasDestinationUrlCreative"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("destinationUrl");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "destinationUrl"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("destinationUrlType");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "destinationUrlType"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "DestinationUrlType"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
# Deploy Kubernetes Worker Node(s)

This repo is not in alignment with current versions of Kubernetes, and will not be active in the future. The CoreOS Kubernetes documentation has been moved to the tectonic-docs repo, where it will be published and updated.

For tested, maintained, and production-ready Kubernetes instructions, see our Tectonic Installer documentation. The Tectonic Installer provides a Terraform-based Kubernetes installation. It is open source, uses upstream Kubernetes and can be easily customized.

Boot one or more CoreOS nodes which will be used as Kubernetes Workers. You must use a CoreOS version 962.0.0+ for the `/usr/lib/coreos/kubelet-wrapper` script to be present in the image. See [kubelet-wrapper](kubelet-wrapper.md) for more information.

See the [CoreOS Documentation](https://coreos.com/os/docs/latest/) for guides on launching nodes on supported platforms.

## Configure Service Components

### TLS Assets

Place the TLS keypairs generated previously in the following locations. Note that each keypair is unique and should be installed on the worker node it was generated for:

* File: `/etc/kubernetes/ssl/ca.pem`
* File: `/etc/kubernetes/ssl/${WORKER_FQDN}-worker.pem`
* File: `/etc/kubernetes/ssl/${WORKER_FQDN}-worker-key.pem`

And make sure you've set proper permission for private key:

```sh
$ sudo chmod 600 /etc/kubernetes/ssl/*-key.pem
$ sudo chown root:root /etc/kubernetes/ssl/*-key.pem
```

Create symlinks to the worker-specific certificate and key so that the remaining configurations on the workers do not have to be unique per worker.

```sh
$ cd /etc/kubernetes/ssl/
$ sudo ln -s ${WORKER_FQDN}-worker.pem worker.pem
$ sudo ln -s ${WORKER_FQDN}-worker-key.pem worker-key.pem
```

### Networking Configuration

*Note:* If the pod-network is being managed independently of flannel, then the flannel parts of this guide can be skipped. It's recommended that Calico is still used for providing network policy. See [kubernetes networking](kubernetes-networking.md) for more detail.

Just like earlier, create `/etc/flannel/options.env` and modify these values:

* Replace `${ADVERTISE_IP}` with this node's publicly routable IP.
* Replace `${ETCD_ENDPOINTS}`

**/etc/flannel/options.env**

```yaml
FLANNELD_IFACE=${ADVERTISE_IP}
FLANNELD_ETCD_ENDPOINTS=${ETCD_ENDPOINTS}
```

Next create a [systemd drop-in][dropins], which will use the above configuration when flannel starts

**/etc/systemd/system/flanneld.service.d/40-ExecStartPre-symlink.conf**

```yaml
[Service]
ExecStartPre=/usr/bin/ln -sf /etc/flannel/options.env /run/flannel/options.env
```

[dropins]: https://coreos.com/os/docs/latest/using-systemd-drop-in-units.html

### Docker Configuration

*Note:* If the pod-network is being managed independently, this step can be skipped. See [kubernetes networking](kubernetes-networking.md) for more detail.

Require that flanneld is running prior to Docker start.

Create `/etc/systemd/system/docker.service.d/40-flannel.conf`

**/etc/systemd/system/docker.service.d/40-flannel.conf**

```yaml
[Unit]
Requires=flanneld.service
After=flanneld.service
[Service]
EnvironmentFile=/etc/kubernetes/cni/docker_opts_cni.env
```

Create the Docker CNI Options file:

**/etc/kubernetes/cni/docker_opts_cni.env**

```yaml
DOCKER_OPT_BIP=""
DOCKER_OPT_IPMASQ=""
```

If using Flannel for networking, setup the Flannel CNI configuration with below. If you intend to use Calico for networking, setup using [Set Up the CNI config (optional)](#set-up-the-cni-config-optional) instead.

**/etc/kubernetes/cni/net.d/10-flannel.conf**

```yaml
{
    "name": "podnet",
    "type": "flannel",
    "delegate": {
        "isDefaultGateway": true
    }
}
```

### Create the kubelet Unit

Create `/etc/systemd/system/kubelet.service` and substitute the following variables:

* Replace `${MASTER_HOST}`
* Replace `${ADVERTISE_IP}` with this node's publicly routable IP.
* Replace `${DNS_SERVICE_IP}`
* Replace `${K8S_VER}` This will map to: `quay.io/coreos/hyperkube:${K8S_VER}` release, e.g. `v1.5.4_coreos.0`.
* If using Calico for network policy
  - Replace `${NETWORK_PLUGIN}` with `cni`
  - Add the following to `RKT_RUN_ARGS=`
    ```
    --volume cni-bin,kind=host,source=/opt/cni/bin \
    --mount volume=cni-bin,target=/opt/cni/bin
    ```
  - Add `ExecStartPre=/usr/bin/mkdir -p /opt/cni/bin`
* Decide if you will use [additional features][rkt-opts-examples] such as:
  - [mounting ephemeral disks][mount-disks]
  - [allow pods to mount RDB][rdb] or [iSCSI volumes][iscsi]
  - [allowing access to insecure container registries][insecure-registry]
  - [changing your CoreOS auto-update settings][update]

**Note**: Anyone with access to port 10250 on a node can execute arbitrary code in a pod on the node. Information, including logs and metadata, is also disclosed on port 10255. See [securing the Kubelet API][securing-kubelet-api] for more information.

**/etc/systemd/system/kubelet.service**

```yaml
[Service]
Environment=KUBELET_IMAGE_TAG=${K8S_VER}
Environment="RKT_RUN_ARGS=--uuid-file-save=/var/run/kubelet-pod.uuid \
  --volume dns,kind=host,source=/etc/resolv.conf \
  --mount volume=dns,target=/etc/resolv.conf \
  --volume var-log,kind=host,source=/var/log \
  --mount volume=var-log,target=/var/log"
ExecStartPre=/usr/bin/mkdir -p /etc/kubernetes/manifests
ExecStartPre=/usr/bin/mkdir -p /var/log/containers
ExecStartPre=-/usr/bin/rkt rm --uuid-file=/var/run/kubelet-pod.uuid
ExecStart=/usr/lib/coreos/kubelet-wrapper \
  --api-servers=https://${MASTER_HOST} \
  --cni-conf-dir=/etc/kubernetes/cni/net.d \
  --network-plugin=${NETWORK_PLUGIN} \
  --container-runtime=docker \
  --register-node=true \
  --allow-privileged=true \
  --pod-manifest-path=/etc/kubernetes/manifests \
  --hostname-override=${ADVERTISE_IP} \
  --cluster_dns=${DNS_SERVICE_IP} \
  --cluster_domain=cluster.local \
  --kubeconfig=/etc/kubernetes/worker-kubeconfig.yaml \
  --tls-cert-file=/etc/kubernetes/ssl/worker.pem \
  --tls-private-key-file=/etc/kubernetes/ssl/worker-key.pem
ExecStop=-/usr/bin/rkt stop --uuid-file=/var/run/kubelet-pod.uuid
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
```

### Set Up the kube-proxy Pod

Create `/etc/kubernetes/manifests/kube-proxy.yaml`:

* Replace `${MASTER_HOST}`

**/etc/kubernetes/manifests/kube-proxy.yaml**

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: kube-proxy
  namespace: kube-system
spec:
  hostNetwork: true
  containers:
  - name: kube-proxy
    image: quay.io/coreos/hyperkube:v1.5.4_coreos.0
    command:
    - /hyperkube
    - proxy
    - --master=${MASTER_HOST}
    - --kubeconfig=/etc/kubernetes/worker-kubeconfig.yaml
    securityContext:
      privileged: true
    volumeMounts:
    - mountPath: /etc/ssl/certs
      name: "ssl-certs"
    - mountPath: /etc/kubernetes/worker-kubeconfig.yaml
      name: "kubeconfig"
      readOnly: true
    - mountPath: /etc/kubernetes/ssl
      name: "etc-kube-ssl"
      readOnly: true
  volumes:
  - name: "ssl-certs"
    hostPath:
      path: "/usr/share/ca-certificates"
  - name: "kubeconfig"
    hostPath:
      path: "/etc/kubernetes/worker-kubeconfig.yaml"
  - name: "etc-kube-ssl"
    hostPath:
      path: "/etc/kubernetes/ssl"
```

### Set Up kubeconfig

In order to facilitate secure communication between Kubernetes components, kubeconfig can be used to define authentication settings. In this case, the kubelet and proxy are reading this configuration to communicate with the API.

Create `/etc/kubernetes/worker-kubeconfig.yaml`:

**/etc/kubernetes/worker-kubeconfig.yaml**

```yaml
apiVersion: v1
kind: Config
clusters:
- name: local
  cluster:
    certificate-authority: /etc/kubernetes/ssl/ca.pem
users:
- name: kubelet
  user:
    client-certificate: /etc/kubernetes/ssl/worker.pem
    client-key: /etc/kubernetes/ssl/worker-key.pem
contexts:
- context:
    cluster: local
    user: kubelet
  name: kubelet-context
current-context: kubelet-context
```

## Start Services

Now we can start the Worker services.

### Load Changed Units

Tell systemd to rescan the units on disk:

```sh
$ sudo systemctl daemon-reload
```

### Start kubelet, and flannel

Start the kubelet, which will start the proxy.

```sh
$ sudo systemctl start flanneld
$ sudo systemctl start kubelet
```

Ensure that the services start on each boot:

```sh
$ sudo systemctl enable flanneld
Created symlink from /etc/systemd/system/multi-user.target.wants/flanneld.service to /etc/systemd/system/flanneld.service.
$ sudo systemctl enable kubelet
Created symlink from /etc/systemd/system/multi-user.target.wants/kubelet.service to /etc/systemd/system/kubelet.service.
```

To check the health of the kubelet systemd unit that we created, run `systemctl status kubelet.service`.

Is the kubelet running?

  Yes, ready to configure `kubectl`

[rkt-opts-examples]: kubelet-wrapper.md#customizing-rkt-options
[rdb]: kubelet-wrapper.md#allow-pods-to-use-rbd-volumes
[iscsi]: kubelet-wrapper.md#allow-pods-to-use-iscsi-mounts
[host-dns]: kubelet-wrapper.md#use-the-hosts-dns-configuration
[mount-disks]: https://coreos.com/os/docs/latest/mounting-storage.html
[insecure-registry]: https://coreos.com/os/docs/latest/registry-authentication.html#using-a-registry-without-ssl-configured
[update]: https://coreos.com/os/docs/latest/switching-channels.html
[securing-kubelet-api]: kubelet-wrapper.md#Securing-the-Kubelet-API


text:
package org.enoir.rulest.model;

/**
 * Created by frank on 2015/4/1.
 */
public class RulESTBaseModel {
}


text:
package com.amazonaws.services.sagemaker.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateAppImageConfigResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The Amazon Resource Name (ARN) for the AppImageConfig.
     *

     */
    private String appImageConfigArn;

    /**
     *

     * The Amazon Resource Name (ARN) for the AppImageConfig.
     *

     *
     * @param appImageConfigArn
     *        The Amazon Resource Name (ARN) for the AppImageConfig.
     */

    public void setAppImageConfigArn(String appImageConfigArn) {
        this.appImageConfigArn = appImageConfigArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) for the AppImageConfig.
     *

     *
     * @return The Amazon Resource Name (ARN) for the AppImageConfig.
     */

    public String getAppImageConfigArn() {
        return this.appImageConfigArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) for the AppImageConfig.
     *

     *
     * @param appImageConfigArn
     *        The Amazon Resource Name (ARN) for the AppImageConfig.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateAppImageConfigResult withAppImageConfigArn(String appImageConfigArn) {
        setAppImageConfigArn(appImageConfigArn);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAppImageConfigArn() != null)
            sb.append("AppImageConfigArn: ").append(getAppImageConfigArn());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof UpdateAppImageConfigResult == false)
            return false;
        UpdateAppImageConfigResult other = (UpdateAppImageConfigResult) obj;
        if (other.getAppImageConfigArn() == null ^ this.getAppImageConfigArn() == null)
            return false;
        if (other.getAppImageConfigArn() != null && other.getAppImageConfigArn().equals(this.getAppImageConfigArn()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAppImageConfigArn() == null) ? 0 : getAppImageConfigArn().hashCode());
        return hashCode;
    }

    @Override
    public UpdateAppImageConfigResult clone() {
        try {
            return (UpdateAppImageConfigResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
XML Standard API: Interface  Parser
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.xml.sax

Interface  Parser

All Known Implementing Classes:
XMLReaderAdapter

Deprecated. This interface has been replaced by the SAX2
             XMLReader
             interface, which includes Namespace support.

public interface Parser

Basic interface for SAX (Simple API for XML) parsers.

 This module, both source code and documentation, is in the
 Public Domain, and comes with NO WARRANTY.
 See http://www.saxproject.org
 for further information.

This was the main event supplier interface for SAX1; it has
 been replaced in SAX2 by XMLReader,
 which includes Namespace support and sophisticated configurability
 and extensibility.

All SAX1 parsers must implement this basic interface: it allows
 applications to register handlers for different types of events
 and to initiate a parse from a URI, or a character stream.

All SAX1 parsers must also implement a zero-argument constructor
 (though other constructors are also allowed).

SAX1 parsers are reusable but not re-entrant: the application
 may reuse a parser object (possibly with a different input source)
 once the first parse has completed successfully, but it may not
 invoke the parse() methods recursively within a parse.

Since:
SAX 1.0

Version:
2.0.1 (sax2r2)

Author:
David Megginson

See Also:
EntityResolver,
DTDHandler,
DocumentHandler,
ErrorHandler,
HandlerBase,
InputSource

Method Summary

 void
parse(InputSource source)

          Deprecated. Parse an XML document.

 void
parse(java.lang.String systemId)

          Deprecated. Parse an XML document from a system identifier (URI).

 void
setDocumentHandler(DocumentHandler handler)

          Deprecated. Allow an application to register a document event handler.

 void
setDTDHandler(DTDHandler handler)

          Deprecated. Allow an application to register a DTD event handler.

 void
setEntityResolver(EntityResolver resolver)

          Deprecated. Allow an application to register a custom entity resolver.

 void
setErrorHandler(ErrorHandler handler)

          Deprecated. Allow an application to register an error event handler.

 void
setLocale(java.util.Locale locale)

          Deprecated. Allow an application to request a locale for errors and warnings.

Method Detail

setLocale

public void setLocale(java.util.Locale locale)
               throws SAXException

Deprecated.
Allow an application to request a locale for errors and warnings.

SAX parsers are not required to provide localisation for errors
 and warnings; if they cannot support the requested locale,
 however, they must throw a SAX exception.  Applications may
 not request a locale change in the middle of a parse.

Parameters:
locale - A Java Locale object.
Throws:
SAXException - Throws an exception
            (using the previous or default locale) if the
            requested locale is not supported.
See Also:
SAXException,
SAXParseException

setEntityResolver

public void setEntityResolver(EntityResolver resolver)

Deprecated.
Allow an application to register a custom entity resolver.

If the application does not register an entity resolver, the
 SAX parser will resolve system identifiers and open connections
 to entities itself (this is the default behaviour implemented in
 HandlerBase).

Applications may register a new or different entity resolver
 in the middle of a parse, and the SAX parser must begin using
 the new resolver immediately.

Parameters:
resolver - The object for resolving entities.
See Also:
EntityResolver,
HandlerBase

setDTDHandler

public void setDTDHandler(DTDHandler handler)

Deprecated.
Allow an application to register a DTD event handler.

If the application does not register a DTD handler, all DTD
 events reported by the SAX parser will be silently
 ignored (this is the default behaviour implemented by
 HandlerBase).

Applications may register a new or different
 handler in the middle of a parse, and the SAX parser must
 begin using the new handler immediately.

Parameters:
handler - The DTD handler.
See Also:
DTDHandler,
HandlerBase

setDocumentHandler

public void setDocumentHandler(DocumentHandler handler)

Deprecated.
Allow an application to register a document event handler.

If the application does not register a document handler, all
 document events reported by the SAX parser will be silently
 ignored (this is the default behaviour implemented by
 HandlerBase).

Applications may register a new or different handler in the
 middle of a parse, and the SAX parser must begin using the new
 handler immediately.

Parameters:
handler - The document handler.
See Also:
DocumentHandler,
HandlerBase

setErrorHandler

public void setErrorHandler(ErrorHandler handler)

Deprecated.
Allow an application to register an error event handler.

If the application does not register an error event handler,
 all error events reported by the SAX parser will be silently
 ignored, except for fatalError, which will throw a SAXException
 (this is the default behaviour implemented by HandlerBase).

Applications may register a new or different handler in the
 middle of a parse, and the SAX parser must begin using the new
 handler immediately.

Parameters:
handler - The error handler.
See Also:
ErrorHandler,
SAXException,
HandlerBase

parse

public void parse(InputSource source)
           throws SAXException,
                  java.io.IOException

Deprecated.
Parse an XML document.

The application can use this method to instruct the SAX parser
 to begin parsing an XML document from any valid input
 source (a character stream, a byte stream, or a URI).

Applications may not invoke this method while a parse is in
 progress (they should create a new Parser instead for each
 additional XML document).  Once a parse is complete, an
 application may reuse the same Parser object, possibly with a
 different input source.

Parameters:
source - The input source for the top-level of the
        XML document.
Throws:
SAXException - Any SAX exception, possibly
            wrapping another exception.
java.io.IOException - An IO exception from the parser,
            possibly from a byte stream or character stream
            supplied by the application.
See Also:
InputSource,
parse(java.lang.String),
setEntityResolver(org.xml.sax.EntityResolver),
setDTDHandler(org.xml.sax.DTDHandler),
setDocumentHandler(org.xml.sax.DocumentHandler),
setErrorHandler(org.xml.sax.ErrorHandler)

parse

public void parse(java.lang.String systemId)
           throws SAXException,
                  java.io.IOException

Deprecated.
Parse an XML document from a system identifier (URI).

This method is a shortcut for the common case of reading a
 document from a system identifier.  It is the exact
 equivalent of the following:

 parse(new InputSource(systemId));

If the system identifier is a URL, it must be fully resolved
 by the application before it is passed to the parser.

Parameters:
systemId - The system identifier (URI).
Throws:
SAXException - Any SAX exception, possibly
            wrapping another exception.
java.io.IOException - An IO exception from the parser,
            possibly from a byte stream or character stream
            supplied by the application.
See Also:
parse(org.xml.sax.InputSource)

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 1999-2010 The Apache Software Foundation. All Rights Reserved.


text:
package org.eclipse.bpel.common.wsdl.parsers;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMLResourceFactoryImpl;
import org.eclipse.xsd.XSDPackage;
import org.eclipse.xsd.XSDSchema;
import org.eclipse.xsd.util.XSDResourceFactoryImpl;
import org.eclipse.xsd.util.XSDUtil;

/**
 * A set of utilities to parse XML schemas and accounting for file imports.
 *

 * This class can be used with {@link XSDUtil}.
 *

 *
 * @author Vincent Zurczak - EBM WebSourcing
 */
public class XmlSchemaParser {

	/**
	 * Loads a XML schema.
	 * @param emfUri an EMF URI
	 * @param resourceSet a resource set
	 * @return an instance of {@link XSDSchema}
	 *

	 * This object already supports inclusions, which means there is no need to
	 * get the imports and parse them.
	 *

	 */
	public static XSDSchema loadXmlSchema( URI emfUri, ResourceSet resourceSet ) {
        Resource resource = resourceSet.getResource( emfUri, true );
        return (XSDSchema) resource.getContents().iterator().next();
	}

	/**
	 * @return a resource set to parse XML schemas
	 */
	public static ResourceSet createBasicResourceSetForXmlSchema() {

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put( "xml", new XMLResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put( "xsd", new XSDResourceFactoryImpl());
        resourceSet.getPackageRegistry().put( XSDPackage.eNS_URI, XSDPackage.eINSTANCE );

        return resourceSet;
	}
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>dynamic_vector_buffer</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="dynamic_string_buffer/size.html" title="dynamic_string_buffer::size">
<link rel="next" href="dynamic_vector_buffer/capacity.html" title="dynamic_vector_buffer::capacity">

Home
Libraries
People
FAQ
More

dynamic_vector_buffer

        Adapt a vector to the DynamicBuffer requirements.

template<
    typename Elem,
    typename Allocator>
class dynamic_vector_buffer

        Types

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  const_buffers_type

                  The type used to represent the input sequence as a list of buffers.

                  mutable_buffers_type

                  The type used to represent the output sequence as a list of buffers.

        Member
        Functions

<colgroup>
<col>
<col>
</colgroup>

                  Name

                  Description

                  capacity

                  Get the current capacity of the dynamic buffer.

                  commit

                  Move bytes from the output sequence to the input sequence.

                  consume

                  Remove characters from the input sequence.

                  data

                  Get a list of buffers that represents the input sequence.

                  dynamic_vector_buffer

                  Construct a dynamic buffer from a string.
  —
 Move construct
                  a dynamic buffer.

                  max_size

                  Get the maximum size of the dynamic buffer.

                  prepare

                  Get a list of buffers that represents the output sequence, with
                  the given size.

                  size

                  Get the size of the input sequence.

        Requires that sizeof(Elem) == 1.

        Requirements

        Header: boost/asio/buffer.hpp

        Convenience header: boost/asio.hpp

Copyright © 2003-2018 Christopher M. Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
ActiveRecord::Schema.define(version: 20161125224201) do

  create_table "addresses", force: :cascade do |t|
    t.integer  "house_number"
    t.string   "street"
    t.string   "state"
    t.integer  "zip"
    t.string   "unit"
    t.integer  "community_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.string   "city"
  end

  create_table "communities", force: :cascade do |t|
    t.integer  "total_loan_amount"
    t.integer  "interest_rate"
    t.string   "terms"
    t.string   "max_loan_amount"
    t.string   "name"
    t.string   "loan_period"
    t.string   "description"
    t.string   "number"
    t.string   "email"
    t.string   "website"
    t.datetime "created_at",        null: false
    t.datetime "updated_at",        null: false
    t.integer  "user_id"
  end

  create_table "identities", force: :cascade do |t|
    t.integer  "user_id"
    t.string   "provider"
    t.string   "uid"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "identities", ["user_id"], name: "index_identities_on_user_id"

  create_table "images", force: :cascade do |t|
    t.string   "location"
    t.integer  "user_id"
    t.integer  "community_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end

  create_table "loan_requests", force: :cascade do |t|
    t.string   "body"
    t.integer  "user_id"
    t.integer  "community_id"
    t.boolean  "accepted",     default: false
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "email"
    t.string   "encrypted_password",                          null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,          null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.string   "name"
    t.string   "address"
    t.string   "phone_number"
    t.string   "username"
    t.datetime "created_at",                                  null: false
    t.datetime "updated_at",                                  null: false
    t.string   "role",                   default: "Borrower"
  end

  add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end


text:
<?php

namespace DOMWrap\Tests\Manipulation;

class DetachTest extends \PHPUnit_Framework_TestCase
{
    use \DOMWrap\Tests\Harness\TestTrait;

    public function testDetachNode() {
        $expected = $this->document('

');
        $doc = $this->document('
this is a test
');
        $nodes = $doc->find('article > a')->first()->detach();

        $this->assertEqualXMLStructure($expected->children()->first(), $doc->children()->first(), true);
        $this->assertInstanceOf('\\DOMWrap\\NodeList', $nodes);
        $this->assertEquals(1, $nodes->count());

        $this->assertInstanceOf('\\DOMWrap\\Element', $nodes[0]);
        $this->assertEquals('a', $nodes[0]->tagName);
        $this->assertEquals('http://example.org/', $nodes[0]->attr('href'));
        $this->assertEquals('this is a test', $nodes[0]->text());
    }

    public function testDetachNodeSelect() {
        $expected = $this->document('');
        $doc = $this->document('
this is a test
');
        $nodes = $doc->find('article')->first()->detach('.a');

        $this->assertEqualXMLStructure($expected->children()->first(), $doc->children()->first(), true);
        $this->assertInstanceOf('\\DOMWrap\\NodeList', $nodes);
        $this->assertEquals(1, $nodes->count());

        $this->assertInstanceOf('\\DOMWrap\\Element', $nodes[0]);
        $this->assertEquals('article', $nodes[0]->tagName);
        $this->assertEquals('a', $nodes[0]->attr('class'));
    }

    public function testDetachNodeList() {
        $expected = $this->document('

');
        $doc = $this->document('
this is a test

test!

');
        $nodes = $doc->find('a, p')->detach();

        $this->assertEqualXMLStructure($expected->children()->first(), $doc->children()->first(), true);
        $this->assertInstanceOf('\\DOMWrap\\NodeList', $nodes);
        $this->assertEquals(2, $nodes->count());

        $this->assertInstanceOf('\\DOMWrap\\Element', $nodes[0]);
        $this->assertEquals('a', $nodes[0]->tagName);
        $this->assertEquals('http://example.org/', $nodes[0]->attr('href'));
        $this->assertEquals('this is a test', $nodes[0]->text());

        $this->assertInstanceOf('\\DOMWrap\\Element', $nodes[1]);
        $this->assertEquals('p', $nodes[1]->tagName);
        $this->assertEquals('test!', $nodes[1]->text());
    }

    public function testDetachNodeListNested() {
        $expected = $this->document('

');
        $doc = $this->document('
this is a testexample!

test!

');
        $nodes = $doc->find('article, section')->detach();

        $this->assertEqualXMLStructure($expected->children()->first(), $doc->children()->first(), true);
        $this->assertInstanceOf('\\DOMWrap\\NodeList', $nodes);
        $this->assertEquals(3, $nodes->count());

        $this->assertInstanceOf('\\DOMWrap\\Element', $nodes[0]);
        $this->assertEquals('section', $nodes[0]->tagName);
        $this->assertEquals(2, $nodes[0]->children()->count());

        $this->assertInstanceOf('\\DOMWrap\\Element', $nodes[1]);
        $this->assertEquals('article', $nodes[1]->tagName);
        $this->assertEquals(0, $nodes[1]->children()->count()); // Child
 already detached

        $this->assertInstanceOf('\\DOMWrap\\Element', $nodes[2]);
        $this->assertEquals('section', $nodes[2]->tagName);
        $this->assertEquals(1, $nodes[2]->children()->count());
    }

    public function testDetachNodeListDoesntExist() {
        $expected = $this->document('
this is a test

test!

');
        $doc = $this->document('
this is a test

test!

');
        $nodes = $doc->find('article')->detach();

        $this->assertEqualXMLStructure($expected->children()->first(), $doc->children()->first(), true);
        $this->assertInstanceOf('\\DOMWrap\\NodeList', $nodes);
        $this->assertEquals(0, $nodes->count());
    }

}


text:
<?php

namespace Augwa\QuickBooks\Enum;

/**
 * Product: ALL
 * Enumeration of possible Id Domains. NG- next gen (int); QB -
 * Provisional DB id (string); QBO; BM (Billing Manager); QBSDK - ListID,
 * TxnID, or TxnLineId.
 *
 * Class idDomainEnum
 * @package Augwa\QuickBooks\Enum
 */
class idDomainEnum
{

    const BM = 'BM';
    const NG = 'NG';
    const PMT = 'PMT';
    const QB = 'QB';
    const QBO = 'QBO';
    const QBSDK = 'QBSDK';

}


text:
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColorSpace.h"
#include "include/core/SkImage.h"
#include "include/core/SkImageGenerator.h"
#include "include/core/SkImageInfo.h"
#include "include/core/SkPaint.h"
#include "include/core/SkRect.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkSize.h"
#include "include/core/SkSurface.h"
#include "include/core/SkTypes.h"
#include "include/gpu/GrDirectContext.h"
#include "tools/ToolUtils.h"

namespace {

const SkISize   kSize = SkISize::Make(100, 100);
const SkIRect kSubset = SkIRect::MakeLTRB(25, 25, 75, 75);
const SkRect    kDest = SkRect::MakeXYWH(10, 10, 100, 100);

sk_sp<SkImage> make_mask(const sk_sp<SkSurface>& surface) {
    ToolUtils::draw_checkerboard(surface->getCanvas(), 0x80808080, 0x00000000, 5);
    return surface->makeImageSnapshot();
}

class MaskGenerator final : public SkImageGenerator {
public:
    MaskGenerator(const SkImageInfo& info) : INHERITED(info) {}

    bool onGetPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, const Options&)
    override {
        SkImageInfo surfaceInfo = info;
        if (kAlpha_8_SkColorType == info.colorType()) {
            surfaceInfo = surfaceInfo.makeColorSpace(nullptr);
        }

        make_mask(SkSurface::MakeRasterDirect(surfaceInfo, pixels, rowBytes));
        return true;
    }

private:
    using INHERITED = SkImageGenerator;
};

using MakerT = sk_sp<SkImage>(*)(SkCanvas*, const SkImageInfo&);
const MakerT makers[] = {
    // SkImage_Raster
    [](SkCanvas*, const SkImageInfo& info) -> sk_sp<SkImage> {
        return make_mask(SkSurface::MakeRaster(info));
    },

    // SkImage_Gpu
    [](SkCanvas* c, const SkImageInfo& info) -> sk_sp<SkImage> {
        sk_sp<SkSurface> surface;
        surface = SkSurface::MakeRenderTarget(c->recordingContext(), SkBudgeted::kNo, info);
        return make_mask(surface ? surface : SkSurface::MakeRaster(info));
    },

    // SkImage_Lazy
    [](SkCanvas*, const SkImageInfo& info) -> sk_sp<SkImage> {
        return SkImage::MakeFromGenerator(std::make_unique<MaskGenerator>(info));
    },
};

}  // namespace

// Checks whether subset SkImages preserve the original color type (A8 in this case).
DEF_SIMPLE_GM(imagemasksubset, canvas, 480, 480) {
    SkPaint paint;
    paint.setColor(0xff00ff00);

    const SkImageInfo info = SkImageInfo::MakeA8(kSize.width(), kSize.height());

    for (size_t i = 0; i < std::size(makers); ++i) {
        sk_sp<SkImage> image = ToolUtils::MakeTextureImage(canvas, makers[i](canvas, info));
        if (image) {
            canvas->drawImageRect(image, SkRect::Make(kSubset), kDest, SkSamplingOptions(),
                                  &paint, SkCanvas::kStrict_SrcRectConstraint);
            auto direct = GrAsDirectContext(canvas->recordingContext());
            sk_sp<SkImage> subset = image->makeSubset(kSubset, direct);
            canvas->drawImageRect(subset, kDest.makeOffset(kSize.width() * 1.5f, 0),
                                  SkSamplingOptions(), &paint);
        }
        canvas->translate(0, kSize.height() * 1.5f);
    }
}