text:
using System;
using System.Collections.Generic;
using System.Xml;

namespace Zw.XmlLanguageEditor.Parsing
{
    /// <summary>
    /// Parser for simple XML language files where the XML element name is the text id. No nesting supported.
    /// </summary>
    internal class XmlParser : IParser
    {
        private static readonly log4net.ILog log = global::log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public string Name => "XmlParser";

        public void CreateEmpty(IFormatOptions options, string fileName)
        {
            var xmlOptions = options as XmlFormatOptions;
            if (xmlOptions == null) throw new ArgumentException("XmlParser requires XmlFormatOptions!", nameof(options));
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateElement(xmlOptions.RootElementName));
            doc.Save(fileName);
        }

        public ParseResult ReadRecords(string filename)
        {
            var result = new ParseResult();
            var records = new List<Entry>();
            XmlDocument doc = new XmlDocument();
            doc.Load(filename);
            log.InfoFormat("Loaded '{0}' with {1} child nodes for reading", filename, doc.DocumentElement?.ChildNodes?.Count ?? -1);
            var xmlOptions = new XmlFormatOptions(doc.DocumentElement?.Name);
            result.FormatOptions = xmlOptions;
            foreach (XmlNode node in doc.DocumentElement.ChildNodes)
            {
                if (node.NodeType != XmlNodeType.Element) continue;
                var record = new Entry() { Id = node.Name, Value = node.InnerText };
                records.Add(record);
            }
            result.Records = records;
            return result;
        }

        public void InjectEntries(string fileName, IEnumerable<Entry> entries)
        {
            int countModified = 0;
            int countCreated = 0;
            XmlDocument doc = new XmlDocument();
            doc.Load(fileName);
            log.InfoFormat("Loaded '{0}' with {1} child nodes for merging", fileName, doc.DocumentElement?.ChildNodes?.Count ?? -1);
            foreach (var entry in entries)
            {
                var node = doc.DocumentElement.SelectSingleNode(GetXPath(entry)) as XmlElement;
                if (node == null)
                {
                    node = doc.CreateElement(entry.Id);
                    doc.DocumentElement.AppendChild(node);
                    countCreated++;
                }
                if (node.InnerText != entry.Value)
                {
                    node.InnerText = entry.Value;
                    countModified++;
                }
            }
            doc.Save(fileName);
            log.InfoFormat("Saved file with {0} changes applied ({1} nodes created)", countModified, countCreated);
        }

        public bool IsSupporting(DataFormat format)
        {
            return (format == DataFormat.Xml);
        }

        private string GetXPath(Entry entry)
        {
            return String.Format("{0}", entry.Id);
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
{% extends "base_template.html" %}

{% block content %}

    <form class="form-horizontal" style="width:50%;">
        <fieldset>

            <legend>Contact</legend>

                Email
                <input class="form-control" id="email" name="email" placeholder="email" required="" type="text">

                Message
                <textarea class="form-control" id="message" name="message">Your message</textarea>

                <button id="send" name="send" class="btn btn-success">Send</button>

        </fieldset>
    </form>

{% endblock %}


text:
package io.spring.initializr.generator.language;

/**
 * Base {@link Language} implementation.
 *
 * @author Stephane Nicoll
 */
public abstract class AbstractLanguage implements Language {

	private final String id;

	private final String jvmVersion;

	private final String sourceFileExtension;

	protected AbstractLanguage(String id, String jvmVersion, String sourceFileExtension) {
		this.id = id;
		this.jvmVersion = (jvmVersion != null) ? jvmVersion : DEFAULT_JVM_VERSION;
		this.sourceFileExtension = sourceFileExtension;
	}

	@Override
	public String id() {
		return this.id;
	}

	@Override
	public String jvmVersion() {
		return this.jvmVersion;
	}

	@Override
	public String sourceFileExtension() {
		return this.sourceFileExtension;
	}

	@Override
	public String toString() {
		return id();
	}

}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('cazador', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='cazador',
            name='raw_data_with_short_links',
            field=models.TextField(default=''),
            preserve_default=False,
        ),
    ]


text:
% Check if a graph is Eulerian, i.e. it has an Eulerian circuit
% "A connected undirected graph is Eulerian if and only if every graph vertex has an even degree."
% "A connected directed graph is Eulerian if and only if every graph vertex has equal in- and out- degree."
% Note: Assume that the graph is connected.
% INPUTS: adjacency matrix
% OUTPUTS: Boolean variable
% Other routines used: degrees.m, isdirected.m
% GB, Last Updated: October 2, 2009

function S=iseulerian(adj)

S=false;

[degs,indeg,outdeg]=degrees(adj);
odd=find(mod(degs,2)==1);

if not(isdirected(adj)) & isempty(odd) % if undirected and all degrees are even
  S=true;

elseif isdirected(adj) & indeg==outdeg % directed and in-degrees equal out-degrees
  S=true;

elseif numel(odd)==2
  fprintf('there is an Eulerian trail from node %2i to node %2i\n',odd(1),odd(2));

end


text:
export interface Product {
    id: number;
    name: string;
}


text:
'use strict';
/*jshint asi: true */

var test = require('tap').test
  , browserify =  require('browserify')
  , convert    =  require('convert-source-map')
  , mold       =  require('..')

function mapFileUrlComment(sourcemap, cb) {
  setTimeout(function () {
    cb('//@ sourceMappingURL=' + '/bundle.js.map');
  }, 5);
}

function mapFileUrlCommentSync(sourcemap) {
  return '//@ sourceMappingURL=' + '/bundle.js.map';
}

test('mold transform async', function (t) {
  t.plan(2)
  var bundle = '';
  browserify({ debug: true })
    .require(require.resolve('../examples/project/js/main.js'), { entry: true })
    .bundle()
    .pipe(mold.transform(mapFileUrlComment))
    .on('error', function (err) { console.error(err); })
    .on('data', function (data) {
      bundle += data;
    })
    .on('end', function () {
      t.notOk(~bundle.indexOf('application/json'), 'removes original comment')
      t.ok(~bundle.indexOf('//@ sourceMappingURL=/bundle.js.map'), 'adds returned comment')
    });
});

test('mold transform sync', function (t) {
  t.plan(2)
  var bundle = '';
  browserify({ debug: true })
    .require(require.resolve('../examples/project/js/main.js'), { entry: true })
    .bundle()
    .pipe(mold.transform(mapFileUrlCommentSync))
    .on('error', function (err) { console.error(err); })
    .on('data', function (data) {
      bundle += data;
    })
    .on('end', function () {
      t.notOk(~bundle.indexOf('application/json'), 'removes original comment')
      t.ok(~bundle.indexOf('//@ sourceMappingURL=/bundle.js.map'), 'adds returned comment')
    });
});


text:
"""
Part of the **PyCeption** package.

:Version: 1
:Authors: - Florian Indot
:Contact: florian.indot@gmail.com
:Date: 24.06.2017
:Revision: 2
:Copyright: MIT License
"""

import os
from enum import Enum
from time import gmtime, strftime
import lib
from lib.pattern import Singleton

RESET = "\033[0m"

class Level(Enum):
    EXCEPTION = 0
    ERROR = 1
    WARNING = 2
    INFORMATION = 3
    DEBUG = 4
    TRACE = 5
    FAILED = 20
    DONE = 21

class Color(Enum):
    PINK = "\033[95m"
    BLUE = "\033[94m"
    GREEN = "\033[92m"
    YELLOW = "\033[93m"
    ORANGE = "\033[33m"
    RED = "\033[91m"
    GREY = "\033[91m"
    WHITE = "\u001b[37;1m"

class Background(Enum):
    BLACK = "\u001b[40m"
    RED = "\u001b[41m"
    GREEN = "\u001b[42m"
    YELLOW = "\u001b[43m"
    BLUE = "\u001b[44m"
    MAGENTA = "\u001b[45m"
    CYAN = "\u001b[46m"
    WHITE = "\u001b[47m"

class Style(Enum):
    BOLD = "\u001b[1m"
    REVERSED = "\u001b[7m"
    UNDERLINE = "\u001b[4m"

def bold(text: str) -> str:
    return Style.BOLD.value + text + RESET

class Logger(object):
    """
    Simple logging system. Prepend timestamps and log levels to given messages.
    Pretty print the messages when possible (unix systems) using unicodes.

    This class metaclass is Singleton. Any subsequent call to the constructor
    posterior to to the first object creation will not have any effect.

    This class is tied to the Pyception library itself and should NOT be used
    nor imported. A "Pyception.log" facility method is available for use.
    Any behaviour considering log levels and logging files destinations is
    unsupported outside of the specified shorthand method.
    """

    __metaclass__ = Singleton

# ----------------------------------------------------------------------- MAGIC

    def __init__(self, output_level: Level = Level.INFORMATION):
        """
        Class constructor. Initializes the logging output level an detect
        whether the script is running on a windows or unix platform.

        :param output_level:    The stdout verbosity of the logging.
        :type output_level:     Level
        """
        self.output_level = output_level
        self._print = self._print_nt if os.name == 'nt' else self._print_unix

        fout_path = os.path.join(
            lib.SETTINGS["workdir"],
            strftime("%y-%m-%d.log", gmtime())
        )
        self._file_out = open(fout_path, "a+")
        self._last_output_level = None

# --------------------------------------------------------------------- METHODS

    def log(self, message: str, lvl: Level = Level.INFORMATION,
            linesep: str = os.linesep):
        """
        Main class method, logs the messages.

        :param message:     The text to be logged.
        :param lvl:         The level of the message.
        :type message:      str
        :type lvl:          Level
        """
        output = self._print(message, lvl)

        if lvl == Level.DONE or lvl == lvl.FAILED:
            lvl = self._last_output_level

        if lvl.value <= self.output_level.value:
            print(output, end=linesep)
        self._file_out.write(output + linesep)

        self._last_output_level = lvl

    def _print_nt(self, text: str, lvl: Level = Level.INFORMATION,
                  linesep: str = os.linesep):
        """
        Windows stdout logging. Without colors.
        """
        if lvl == Level.INFORMATION:
            return "Info: %s" % text
        elif lvl == Level.WARNING:
            return "Warning: %s" % text
        elif lvl == Level.ERROR:
            return "Error: %s" % text
        elif lvl == Level.EXCEPTION:
            return "EXCEPTION: %s" % text
        elif lvl == Level.DONE:
            return " %s ✔" % text
        elif lvl == Level.FAILED:
            return " %s ✘" % text

    def _print_unix(self, text: str = "", lvl: Level = Level.INFORMATION,
                    linesep: str = os.linesep):
        """
        UNIX stdout logging. With colors.
        """
        prefix = ""
        suffix = ""
        color = RESET

        if lvl == Level.INFORMATION:
            prefix = "Info :"
            color = Color.BLUE.value
        elif lvl == Level.WARNING:
            prefix = "Warning :"
            color = Color.ORANGE.value
        elif lvl == Level.ERROR:
            prefix = "Error :"
            color = Color.RED.value
        elif lvl == Level.EXCEPTION:
            prefix = "EXCEPTION :"
            color = Background.RED.value + Color.WHITE.value
        elif lvl == Level.DONE:
            suffix = " ✔"
            color = Color.GREEN.value
        elif lvl == Level.FAILED:
            suffix = " ✘"
            color = Color.ORANGE.value
        elif lvl == Level.DEBUG:
            prefix = "Debug :"
            color = Color.WHITE.value

        message = "{bold}{color}{prefix} {text} {suffix}{reset}".format(
            bold=Style.BOLD.value,
            color=color,
            prefix=prefix,
            text=text,
            suffix=suffix,
            reset=RESET
        )

        if lvl is not Level.DONE and lvl is not Level.FAILED:
            message = strftime("[%y-%m-%d %H:%M:%S] - ", gmtime()) + message
        return message.ljust(110)


text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace XlsToEf.Import
{
    [Obsolete("ImportColumnData Obsolete, please use DataForMatcherUi", true)]
    public class ImportColumnData : DataForMatcherUi
    {

    }

    public class DataForMatcherUi
    {
        public DataForMatcherUi()
        {
            RequiredTogether = new string[0][];
        }

        public string[] XlsxColumns { get; set; }
        public List<TableColumnConfiguration> TableColumns { get; set; }
        public string FileName { get; set; }
        public string[][] RequiredTogether { get; set; }
    }

    public class SingleColumnData
    {
        public SingleColumnData(string displayName, bool required = true)
        {
            DisplayName = displayName;
            Required = required;
        }

        public string DisplayName { get; private set; }
        public bool Required { get; private set; }
    }

    public class TableColumnConfiguration
    {
        public string Name { get; }

        public SingleColumnData ColumnData { get; }

        private TableColumnConfiguration(string columnName, SingleColumnData columnData)
        {
            Name = columnName;
            ColumnData = columnData;
        }

        public static TableColumnConfiguration Create<T>(Expression<Func<T>> propertyLambda,  SingleColumnData columnData)
        {
            var me = propertyLambda.Body as MemberExpression;

            if (me == null)
            {
                throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
            }

            var name =  me.Member.Name;

            var obj = new TableColumnConfiguration(name, columnData);
            return obj;

        }

        public static TableColumnConfiguration Create(string name, SingleColumnData columnData)
        {
            var obj = new TableColumnConfiguration(name, columnData);
            return obj;

        }
    }
}


text:
package com.formulasearchengine.mathosphere.mlp.pojos;

import java.util.List;
import java.util.Set;

public class Sentence {

  private List<Word> words;
  private Set<String> identifiers;
  private List<MathTag> formulas;

  public Sentence(List<Word> words, Set<String> identifiers, List<MathTag> formulas) {
    this.words = words;
    this.identifiers = identifiers;
    this.formulas = formulas;
  }

  public List<Word> getWords() {
    return words;
  }

  public boolean contains(String identifier) {
    return identifiers.contains(identifier);
  }

  public Set<String> getIdentifiers() {
    return identifiers;
  }

  public List<MathTag> getFormulas() {
    return formulas;
  }

  public void setFormulas(List<MathTag> formulas) {
    this.formulas = formulas;
  }

  @Override
  public String toString() {
    return "Sentence [words=" + words + ", identifiers=" + identifiers + "]";
  }

}


text:
using System;
using System.Reflection;

using log4net.Repository;

namespace log4net.Config
{
	/// <summary>
	/// Base class for all log4net configuration attributes.
	/// </summary>
	/// <remarks>
	/// This is an abstract class that must be extended by
	/// specific configurators. This attribute allows the
	/// configurator to be parameterised by an assembly level
	/// attribute.
	/// </remarks>
	[AttributeUsage(AttributeTargets.Assembly)]
	public abstract class ConfiguratorAttribute : Attribute
	{
		/// <summary>
		/// Configures the <see cref="ILoggerRepository"/> for the specified assembly.
		/// </summary>
		/// <param name="assembly">The assembly that this attribute was defined on.</param>
		/// <param name="repository">The repository to configure.</param>
		public abstract void Configure(Assembly assembly, ILoggerRepository repository);
	}
}


text:
USE WideWorldImporters
GO
ALTER DATABASE current SET AUTOMATIC_TUNING ( FORCE_LAST_GOOD_PLAN = ON);
DBCC FREEPROCCACHE;
ALTER DATABASE current SET QUERY_STORE CLEAR ALL;
GO


text:
use springair;
source drop.sql
source create.sql
source populate.sql
commit;


text:
<!doctype html>

<link rel="stylesheet" type="text/css" href="/static/new/cmaps_css.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="/static/new/images/favicon.ico">

    	Show Menu

	<input type="checkbox" id="show-menu" role="button">

Home

			Tracking

View Map

View Database

Assignments

Wiki

About

		Welcome to the Cadet Mapping and Positioning System

			   <object data="/static/new/images/fi-compass.svg" type="image/svg+xml" height="75%" width="75%" style="pointer-events: none;" ></object>

			   <object data="/static/new/images/fi-database.svg" type="image/svg+xml" height="75%" width="75%" style="pointer-events: none;" ></object>

			   <object data="/static/new/images/fi-clipboard-notes.svg" type="image/svg+xml" height="75%" width="75%" style="pointer-events: none;" ></object>


text:
<?php

class Storymarket_Content_Resource extends Storymarket_Base_Resource {
    public function __get($key) {
        $data = parent::__get($key);
        if (empty($data)) {
            return $data;
        }
        switch ($key) {
        case 'author':
        case 'uploaded_by':
        case 'uploadedBy':
            return new Storymarket_Content_User($data);
            break;

        case 'category':
            return new Storymarket_Categories_Category($this->manager->_api->categories, $data);
            break;

        case 'sub_type':
            return new Storymarket_SubTypes_SubType($this->manager->_api->sub_types, $data);
            break;

        case 'org':
            return new Storymarket_Orgs_Org($this->manager->_api->orgs, $data);
            break;

        case 'pricingScheme':
        case 'pricing_scheme':
            return new Storymarket_Schemes_PricingScheme($this->manager->_api->pricing, $data);
            break;

        case 'rightsScheme':
        case 'rights_scheme':
            return new Storymarket_Schemes_RightsScheme($this->manager->_api->rights, $data);
            break;

        }
        return $data;
    }

    public function __isset($key) {
        $acceptable = array('author', 'category', 'sub_type','org',
            'pricing_scheme', 'pricingScheme',
            'rights_scheme', 'rightsScheme',
            'uploaded_by', 'uploadedBy',
        );
        return in_array($key, $acceptable);
    }

    public function save() {
        $this->manager->update($this);
    }

    public function delete() {
        $this->manager->delete($this);
    }
}


text:
rightscale_marker

if node[:db][:init_slave_at_boot] == "true"

  if node[:db][:init_status].to_sym == :initialized
    log "  Already initialized perhaps from stop/start"
  else
    log "  Initializing slave at boot..."
    # See cookbooks/db/recipes/do_primary_init_slave.rb for the "db::do_primary_init_slave" recipe.
    include_recipe "db::do_primary_init_slave"
  end

else
  log "  Initialize slave at boot [skipped]"
end


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>And All The Roads That Lead You There Were Winding - Popagandhi</title>
<meta name="description" content="I came to the Middle East to do just one thing: see a part of the world that I felt I needed to learn more about. Its language was alien, but familiar – many...">
<link rel="stylesheet" href="Cormorant:400,400i,600,600i|Poppins:400,500,600,700&subset=latin-ext">
<link rel="stylesheet" href="/css/main.css">
<link rel="canonical" href="http://localhost:4000/2009/05/and-all-the-roads-that-lead-you-there-were-winding/">
<link rel="alternate" type="application/rss+xml" title="Popagandhi" href="http://localhost:4000/feed.xml" />

Home

About

            May 12, 2009

And All The Roads That Lead You There Were Winding

I came to the Middle East to do just one thing: see a part of the world that I felt I needed to learn more about. Its language was alien, but familiar – many Malay and Hindi words have roots in Arabic. Its customs and food strange, but not dissimilar – much of the Indian subcontinent that I love and call home was influenced, for the better and the worse, by centuries of Mughal rule. Dubai and Singapore had many things in common, and then not at all.

My months through the region are coming to an end. As I travelled through Dubai I fell hard for the United Arab Emirates, but not for its most famous, brashest city. I loved Abu Dhabi and I loved Al Ain. I loved the weekend drives into the desert, and camping trips to Oman. I discovered the lengths people will go to for bootleg alcohol, when liquor licenses and hotel drinking start to dry up (driving to Ajman to get bootleg supplies etc).

And as I embarked on my quest to see the real middle east, after giving up on Dubai – I was in for a treat. Yemen, bombs and all, shook me; it was like nothing I had seen before. Then my ambitious overland journey, beginning with Beirut. That's now drawing to an end.

The last month or so that i've been properly on the road, I've navigated my way around Lebanon through Syria through Turkey, without once knowing how to drive a car. I've met ridiculously awesome people. I've had countless cups of tea with strangers. I've seen some sights.

And the sights I've seen, I'm amazed by the opportunity – and good luck I've had in seeing some of these wonders. From a castle built by one man, still alive, in Beiteddine, to the phenomenal Kraks des Chevaliers in Syria (the embodiment of all childhood castle jousting fantasies, says Theroux, and he's right – again). The ancient cities of Damascus and Sana'a. The friends I've made all through Beirut, Damascus, Palmyra, Aleppo, Antalya, Cappadocia and Istanbul.

The long bus rides. I left Damascus last week and 36 hours later arrived in Antalya, but not before being stranded in Adana with too many Syrian pounds but no Turkish lira – and no money changer or warm clothes in the freezing cold of an eastern Turkish morning.

Done with my last bus ride (12 hours from Goreme to Istanbul), I now sleepwalk through Taksim Square at 7 in the morning, pleased to be back to one of my favourite cities in the world. One that makes me thankful for the beautiful people I call my friends, who last shared this city with me

– Alp, Z and gang. It was the city where Fortylove.tv was conceived, at the start of this tremendous journey.

But journeys never end, only their chapters do. It strikes me now that for all my complaints and grievances about the middle east, this region is truly special and needs to be seen to be understood. And I'm glad I had the chance to see it while I could.

If I could do it again, I would do a few weeks in Iran. But that will have to wait.

For now, long Turkish bus rides and what's left of my Istanbul days – one filled with lots of 'midye dolma', wet hamburgers, fish sandwiches, Bosphorous views and raki when the sun goes down, I'm sure.

Then London. Then moving into my new pad in Kuala Lumpur. Then a new chapter in life, love, and adulthood. I think I have airtickets booked or planned for every month from now through January, though, so the adventure doesn't end – it'll be the last of the middle east and Europe for some time, but more awaits.

Time to finish breakfast, put on my heavy backpack, and walk the last 1km to my hostel. It shall be the last hostel in awhile – I'm not giving up backpacking, I'm just… Upgrading. Life, travel, trading in my hobo life for the chance of getting to own things beyond my baggage allowance for the first time in a while.

I'm happy.

Share this post

                  Twitter

                  Facebook

                  Google+

                  LinkedIn

                Adrianna tan in Life & love

                    Life & love

                    Travel

                You may also like

                                    Tech

Road, Gravel, Mud

                                    Tech

So You Want To Be A Startup Founder

                                    Tech

Signals and Noise

                                    Life & love

Munduk

Made with love by folks at 69signals.

							About

							Contact

    	<form method="get" action="https://www.google.com/search">
			<input type="search" name="q" size="25" maxlength="255" placeholder="Search.." value="" />
		</form>

Begin typing your search above and press return to search. Press Esc to cancel.


text:
package org.apache.cassandra.service;

import java.net.InetAddress;
import java.util.*;
import java.util.concurrent.ExecutionException;

import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.RowUpdateBuilder;
import org.apache.cassandra.db.compaction.OperationType;
import org.apache.cassandra.db.lifecycle.SSTableSet;
import org.apache.cassandra.db.lifecycle.View;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.locator.AbstractReplicationStrategy;
import org.apache.cassandra.locator.TokenMetadata;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.concurrent.Refs;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class ActiveRepairServiceTest
{
    public static final String KEYSPACE5 = "Keyspace5";
    public static final String CF_STANDARD1 = "Standard1";
    public static final String CF_COUNTER = "Counter1";

    public String cfname;
    public ColumnFamilyStore store;
    public InetAddress LOCAL, REMOTE;

    private boolean initialized;

    @BeforeClass
    public static void defineSchema() throws ConfigurationException
    {
        SchemaLoader.prepareServer();
        SchemaLoader.createKeyspace(KEYSPACE5,
                                    KeyspaceParams.simple(2),
                                    SchemaLoader.standardCFMD(KEYSPACE5, CF_COUNTER),
                                    SchemaLoader.standardCFMD(KEYSPACE5, CF_STANDARD1));
    }

    @Before
    public void prepare() throws Exception
    {
        if (!initialized)
        {
            SchemaLoader.startGossiper();
            initialized = true;

            LOCAL = FBUtilities.getBroadcastAddress();
            // generate a fake endpoint for which we can spoof receiving/sending trees
            REMOTE = InetAddress.getByName("127.0.0.2");
        }

        TokenMetadata tmd = StorageService.instance.getTokenMetadata();
        tmd.clearUnsafe();
        StorageService.instance.setTokens(Collections.singleton(tmd.partitioner.getRandomToken()));
        tmd.updateNormalToken(tmd.partitioner.getMinimumToken(), REMOTE);
        assert tmd.isMember(REMOTE);
    }

    @Test
    public void testGetNeighborsPlusOne() throws Throwable
    {
        // generate rf+1 nodes, and ensure that all nodes are returned
        Set<InetAddress> expected = addTokens(1 + Keyspace.open(KEYSPACE5).getReplicationStrategy().getReplicationFactor());
        expected.remove(FBUtilities.getBroadcastAddress());
        Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(KEYSPACE5);
        Set<InetAddress> neighbors = new HashSet<>();
        for (Range<Token> range : ranges)
        {
            neighbors.addAll(ActiveRepairService.getNeighbors(KEYSPACE5, ranges, range, null, null));
        }
        assertEquals(expected, neighbors);
    }

    @Test
    public void testGetNeighborsTimesTwo() throws Throwable
    {
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();

        // generate rf*2 nodes, and ensure that only neighbors specified by the ARS are returned
        addTokens(2 * Keyspace.open(KEYSPACE5).getReplicationStrategy().getReplicationFactor());
        AbstractReplicationStrategy ars = Keyspace.open(KEYSPACE5).getReplicationStrategy();
        Set<InetAddress> expected = new HashSet<>();
        for (Range<Token> replicaRange : ars.getAddressRanges().get(FBUtilities.getBroadcastAddress()))
        {
            expected.addAll(ars.getRangeAddresses(tmd.cloneOnlyTokenMap()).get(replicaRange));
        }
        expected.remove(FBUtilities.getBroadcastAddress());
        Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(KEYSPACE5);
        Set<InetAddress> neighbors = new HashSet<>();
        for (Range<Token> range : ranges)
        {
            neighbors.addAll(ActiveRepairService.getNeighbors(KEYSPACE5, ranges, range, null, null));
        }
        assertEquals(expected, neighbors);
    }

    @Test
    public void testGetNeighborsPlusOneInLocalDC() throws Throwable
    {
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();

        // generate rf+1 nodes, and ensure that all nodes are returned
        Set<InetAddress> expected = addTokens(1 + Keyspace.open(KEYSPACE5).getReplicationStrategy().getReplicationFactor());
        expected.remove(FBUtilities.getBroadcastAddress());
        // remove remote endpoints
        TokenMetadata.Topology topology = tmd.cloneOnlyTokenMap().getTopology();
        HashSet<InetAddress> localEndpoints = Sets.newHashSet(topology.getDatacenterEndpoints().get(DatabaseDescriptor.getLocalDataCenter()));
        expected = Sets.intersection(expected, localEndpoints);

        Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(KEYSPACE5);
        Set<InetAddress> neighbors = new HashSet<>();
        for (Range<Token> range : ranges)
        {
            neighbors.addAll(ActiveRepairService.getNeighbors(KEYSPACE5, ranges, range, Arrays.asList(DatabaseDescriptor.getLocalDataCenter()), null));
        }
        assertEquals(expected, neighbors);
    }

    @Test
    public void testGetNeighborsTimesTwoInLocalDC() throws Throwable
    {
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();

        // generate rf*2 nodes, and ensure that only neighbors specified by the ARS are returned
        addTokens(2 * Keyspace.open(KEYSPACE5).getReplicationStrategy().getReplicationFactor());
        AbstractReplicationStrategy ars = Keyspace.open(KEYSPACE5).getReplicationStrategy();
        Set<InetAddress> expected = new HashSet<>();
        for (Range<Token> replicaRange : ars.getAddressRanges().get(FBUtilities.getBroadcastAddress()))
        {
            expected.addAll(ars.getRangeAddresses(tmd.cloneOnlyTokenMap()).get(replicaRange));
        }
        expected.remove(FBUtilities.getBroadcastAddress());
        // remove remote endpoints
        TokenMetadata.Topology topology = tmd.cloneOnlyTokenMap().getTopology();
        HashSet<InetAddress> localEndpoints = Sets.newHashSet(topology.getDatacenterEndpoints().get(DatabaseDescriptor.getLocalDataCenter()));
        expected = Sets.intersection(expected, localEndpoints);

        Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(KEYSPACE5);
        Set<InetAddress> neighbors = new HashSet<>();
        for (Range<Token> range : ranges)
        {
            neighbors.addAll(ActiveRepairService.getNeighbors(KEYSPACE5, ranges, range, Arrays.asList(DatabaseDescriptor.getLocalDataCenter()), null));
        }
        assertEquals(expected, neighbors);
    }

    @Test
    public void testGetNeighborsTimesTwoInSpecifiedHosts() throws Throwable
    {
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();

        // generate rf*2 nodes, and ensure that only neighbors specified by the hosts are returned
        addTokens(2 * Keyspace.open(KEYSPACE5).getReplicationStrategy().getReplicationFactor());
        AbstractReplicationStrategy ars = Keyspace.open(KEYSPACE5).getReplicationStrategy();
        List<InetAddress> expected = new ArrayList<>();
        for (Range<Token> replicaRange : ars.getAddressRanges().get(FBUtilities.getBroadcastAddress()))
        {
            expected.addAll(ars.getRangeAddresses(tmd.cloneOnlyTokenMap()).get(replicaRange));
        }

        expected.remove(FBUtilities.getBroadcastAddress());
        Collection<String> hosts = Arrays.asList(FBUtilities.getBroadcastAddress().getCanonicalHostName(),expected.get(0).getCanonicalHostName());
        Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(KEYSPACE5);

        assertEquals(expected.get(0), ActiveRepairService.getNeighbors(KEYSPACE5, ranges,
                                                                       ranges.iterator().next(),
                                                                       null, hosts).iterator().next());
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetNeighborsSpecifiedHostsWithNoLocalHost() throws Throwable
    {
        addTokens(2 * Keyspace.open(KEYSPACE5).getReplicationStrategy().getReplicationFactor());
        //Dont give local endpoint
        Collection<String> hosts = Arrays.asList("127.0.0.3");
        Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(KEYSPACE5);
        ActiveRepairService.getNeighbors(KEYSPACE5, ranges, ranges.iterator().next(), null, hosts);
    }

    Set<InetAddress> addTokens(int max) throws Throwable
    {
        TokenMetadata tmd = StorageService.instance.getTokenMetadata();
        Set<InetAddress> endpoints = new HashSet<>();
        for (int i = 1; i <= max; i++)
        {
            InetAddress endpoint = InetAddress.getByName("127.0.0." + i);
            tmd.updateNormalToken(tmd.partitioner.getRandomToken(), endpoint);
            endpoints.add(endpoint);
        }
        return endpoints;
    }

    @Test
    public void testGetActiveRepairedSSTableRefs()
    {
        ColumnFamilyStore store = prepareColumnFamilyStore();
        Set<SSTableReader> original = store.getLiveSSTables();

        UUID prsId = UUID.randomUUID();
        ActiveRepairService.instance.registerParentRepairSession(prsId, FBUtilities.getBroadcastAddress(), Collections.singletonList(store), null, true, 0, false);
        ActiveRepairService.ParentRepairSession prs = ActiveRepairService.instance.getParentRepairSession(prsId);
        prs.markSSTablesRepairing(store.metadata.cfId, prsId);

        //retrieve all sstable references from parent repair sessions
        Refs<SSTableReader> refs = prs.getActiveRepairedSSTableRefsForAntiCompaction(store.metadata.cfId, prsId);
        Set<SSTableReader> retrieved = Sets.newHashSet(refs.iterator());
        assertEquals(original, retrieved);
        refs.release();

        //remove 1 sstable from data data tracker
        Set<SSTableReader> newLiveSet = new HashSet<>(original);
        Iterator<SSTableReader> it = newLiveSet.iterator();
        final SSTableReader removed = it.next();
        it.remove();
        store.getTracker().dropSSTables(new com.google.common.base.Predicate<SSTableReader>()
        {
            public boolean apply(SSTableReader reader)
            {
                return removed.equals(reader);
            }
        }, OperationType.COMPACTION, null);

        //retrieve sstable references from parent repair session again - removed sstable must not be present
        refs = prs.getActiveRepairedSSTableRefsForAntiCompaction(store.metadata.cfId, prsId);
        retrieved = Sets.newHashSet(refs.iterator());
        assertEquals(newLiveSet, retrieved);
        assertFalse(retrieved.contains(removed));
        refs.release();
    }

    @Test
    public void testAddingMoreSSTables()
    {
        ColumnFamilyStore store = prepareColumnFamilyStore();
        Set<SSTableReader> original = Sets.newHashSet(store.select(View.select(SSTableSet.CANONICAL, (s) -> !s.isRepaired())).sstables);
        UUID prsId = UUID.randomUUID();
        ActiveRepairService.instance.registerParentRepairSession(prsId, FBUtilities.getBroadcastAddress(), Collections.singletonList(store), null, true, System.currentTimeMillis(), true);

        ActiveRepairService.ParentRepairSession prs = ActiveRepairService.instance.getParentRepairSession(prsId);
        prs.markSSTablesRepairing(store.metadata.cfId, prsId);
        try (Refs<SSTableReader> refs = prs.getActiveRepairedSSTableRefsForAntiCompaction(store.metadata.cfId, prsId))
        {
            Set<SSTableReader> retrieved = Sets.newHashSet(refs.iterator());
            assertEquals(original, retrieved);
        }
        createSSTables(store, 2);
        boolean exception = false;
        try
        {
            UUID newPrsId = UUID.randomUUID();
            ActiveRepairService.instance.registerParentRepairSession(newPrsId, FBUtilities.getBroadcastAddress(), Collections.singletonList(store), null, true, System.currentTimeMillis(), true);
            ActiveRepairService.instance.getParentRepairSession(newPrsId).markSSTablesRepairing(store.metadata.cfId, newPrsId);
        }
        catch (Throwable t)
        {
            exception = true;
        }
        assertTrue(exception);

        try (Refs<SSTableReader> refs = prs.getActiveRepairedSSTableRefsForAntiCompaction(store.metadata.cfId, prsId))
        {
            Set<SSTableReader> retrieved = Sets.newHashSet(refs.iterator());
            assertEquals(original, retrieved);
        }
    }

    @Test
    public void testSnapshotAddSSTables() throws ExecutionException, InterruptedException
    {
        ColumnFamilyStore store = prepareColumnFamilyStore();
        UUID prsId = UUID.randomUUID();
        Set<SSTableReader> original = Sets.newHashSet(store.select(View.select(SSTableSet.CANONICAL, (s) -> !s.isRepaired())).sstables);
        ActiveRepairService.instance.registerParentRepairSession(prsId, FBUtilities.getBroadcastAddress(), Collections.singletonList(store), Collections.singleton(new Range<>(store.getPartitioner().getMinimumToken(), store.getPartitioner().getMinimumToken())), true, System.currentTimeMillis(), true);
        ActiveRepairService.instance.getParentRepairSession(prsId).maybeSnapshot(store.metadata.cfId, prsId);

        UUID prsId2 = UUID.randomUUID();
        ActiveRepairService.instance.registerParentRepairSession(prsId2, FBUtilities.getBroadcastAddress(), Collections.singletonList(store), Collections.singleton(new Range<>(store.getPartitioner().getMinimumToken(), store.getPartitioner().getMinimumToken())), true, System.currentTimeMillis(), true);
        createSSTables(store, 2);
        ActiveRepairService.instance.getParentRepairSession(prsId).maybeSnapshot(store.metadata.cfId, prsId);
        try (Refs<SSTableReader> refs = ActiveRepairService.instance.getParentRepairSession(prsId).getActiveRepairedSSTableRefsForAntiCompaction(store.metadata.cfId, prsId))
        {
            assertEquals(original, Sets.newHashSet(refs.iterator()));
        }
        store.forceMajorCompaction();
        // after a major compaction the original sstables will be gone and we will have no sstables to anticompact:
        try (Refs<SSTableReader> refs = ActiveRepairService.instance.getParentRepairSession(prsId).getActiveRepairedSSTableRefsForAntiCompaction(store.metadata.cfId, prsId))
        {
            assertEquals(0, refs.size());
        }
    }

    @Test
    public void testSnapshotMultipleRepairs()
    {
        ColumnFamilyStore store = prepareColumnFamilyStore();
        Set<SSTableReader> original = Sets.newHashSet(store.select(View.select(SSTableSet.CANONICAL, (s) -> !s.isRepaired())).sstables);
        UUID prsId = UUID.randomUUID();
        ActiveRepairService.instance.registerParentRepairSession(prsId, FBUtilities.getBroadcastAddress(), Collections.singletonList(store), Collections.singleton(new Range<>(store.getPartitioner().getMinimumToken(), store.getPartitioner().getMinimumToken())), true, System.currentTimeMillis(), true);
        ActiveRepairService.instance.getParentRepairSession(prsId).maybeSnapshot(store.metadata.cfId, prsId);

        UUID prsId2 = UUID.randomUUID();
        ActiveRepairService.instance.registerParentRepairSession(prsId2, FBUtilities.getBroadcastAddress(), Collections.singletonList(store), Collections.singleton(new Range<>(store.getPartitioner().getMinimumToken(), store.getPartitioner().getMinimumToken())), true, System.currentTimeMillis(), true);
        boolean exception = false;
        try
        {
            ActiveRepairService.instance.getParentRepairSession(prsId2).maybeSnapshot(store.metadata.cfId, prsId2);
        }
        catch (Throwable t)
        {
            exception = true;
        }
        assertTrue(exception);
        try (Refs<SSTableReader> refs = ActiveRepairService.instance.getParentRepairSession(prsId).getActiveRepairedSSTableRefsForAntiCompaction(store.metadata.cfId, prsId))
        {
            assertEquals(original, Sets.newHashSet(refs.iterator()));
        }
    }

    private ColumnFamilyStore prepareColumnFamilyStore()
    {
        Keyspace keyspace = Keyspace.open(KEYSPACE5);
        ColumnFamilyStore store = keyspace.getColumnFamilyStore(CF_STANDARD1);
        store.truncateBlocking();
        store.disableAutoCompaction();
        createSSTables(store, 10);
        return store;
    }

    private void createSSTables(ColumnFamilyStore cfs, int count)
    {
        long timestamp = System.currentTimeMillis();
        for (int i = 0; i < count; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                new RowUpdateBuilder(cfs.metadata, timestamp, Integer.toString(j))
                .clustering("c")
                .add("val", "val")
                .build()
                .applyUnsafe();
            }
            cfs.forceBlockingFlush();
        }
    }
}


text:
<?php

namespace KyotoTyphoon\Client;

use \KyotoTyphoon\Interfaces\KyotoClientInterface;
use \KyotoTyphoon\Transport\KyotoRestTransport;

use \KyotoTyphoon\KyotoRequest as Request;
use \KyotoTyphoon\KyotoResponse as Response;

use \KyotoTyphoon\KyotoEvent;

class KyotoRestClient implements KyotoClientInterface
{
	public $transport;

	public function __construct(Array $options){
		$this->transport = new KyotoRestTransport($options);
	}

    public function GET(Array $params=[],Array $callbacks=[]){
        return $this->send(__FUNCTION__, [
			'params'=>$params,
			'callbacks'=>$callbacks
        ],$callbacks);
    }

    public function HEAD(Array $params=[],Array $callbacks=[]){
        return $this->send(__FUNCTION__, [
			'params'=>$params,
			'callbacks'=>$callbacks
        ],$callbacks);
    }

    public function PUT(Array $params=[],Array $callbacks=[]){
        return $this->send(__FUNCTION__, [
			'params'=>$params,
			'callbacks'=>$callbacks
        ],$callbacks);
    }

    public function DELETE(Array $params=[],Array $callbacks=[]){
        return $this->send(__FUNCTION__, [
			'params'=>$params,
			'callbacks'=>$callbacks
        ],$callbacks);
    }

    private function send($command,Array $params){

        $requestHash = spl_object_hash($request = new Request());
        $responseHash = spl_object_hash($response = new Response());

        $request->command = $command;

		foreach($params['params'] as $k=>$v){
			$request->params[$k]=$v;
		}

        foreach($params['callbacks'] as $event=>$callback){
            if(is_callable($callback)){
                KyotoEvent::once($event,$callback);
            }
        }

        return $this->transport->send($request, $response);
    }
}


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

import com.intellij.openapi.util.IconLoader;

import javax.swing.*;

public interface P4Icons {
    Icon CONNECTED = IconLoader.getIcon("/icons/p4connected.png");
    Icon DISCONNECTED = IconLoader.getIcon("/icons/p4disconnected.png");
}


text:
package com.geecat.steps.applet;

import java.applet.Applet;
import java.awt.Graphics;

public class SimpleApplet extends Applet {

	/**
	 <applet code=SimpleApplet" width=200 height=600>
	 </applet>
	 */
	private static final long serialVersionUID = 1L;

	public void paint(Graphics g) {
		g.drawString("A simple Applet", 20, 20);
	}

}


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../bower_components/paper-checkbox/paper-checkbox.html">
<link rel="import" href="../../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../../bower_components/iron-flex-layout/classes/iron-flex-layout.html">
<link rel="import" href="../../bower_components/paper-material/paper-material.html">

<dom-module id="test-item">
  <template>
    <div>
      <h1>  {{testQuestion}} </h1>
      <p> {{testDetail}} </p>
    </div>
    <add-answer></add-answer>
  </template>
  <script>
    Polymer({
      is: 'test-item',

      properties: {
        testQuestion: "Test Question",
        testDetail: "Test Details",
        notify: true
      }

    });
  </script>
</dom-module>


text:
package com.yumodev.rxjava1.retrofit;

import com.google.gson.Gson;
import com.yumo.demo.view.YmTestFragment;
import com.yumodev.rxjava1.retrofit.entry.RootGithubUrl;
import com.yumodev.rxjava1.retrofit.entry.User;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yumo on 2018/6/26.
 * [Retrofit结合RxJava使用指南](https://www.cnblogs.com/mengdd/p/6047948.html)
 */

public class TestRetrofit extends YmTestFragment {

    public void testRootGithubUrls(){
        GithubService githubService = ServiceGenerator.createService(GithubService.class);
        Call<RootGithubUrl> rootGithubUrlCalls = githubService.getRootGithubUrls("");
        rootGithubUrlCalls.enqueue(new Callback<RootGithubUrl>() {
            @Override
            public void onResponse(Call<RootGithubUrl> call, Response<RootGithubUrl> response) {
                RootGithubUrl rootGithubUrl = response.body();
                showToastMessage(rootGithubUrl.getRepository_url());
            }

            @Override
            public void onFailure(Call<RootGithubUrl> call, Throwable t) {

            }
        });
    }

    /**
     * 获取用户信息
     */
    public void testPrintUserInfo(){
        GithubService githubService = ServiceGenerator.createService(GithubService.class);
        Call<User> userCall = githubService.getUser("yumodev");
        userCall.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                User user = response.body();
                showToastMessage((new Gson()).toJson(user));
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });
    }

    /**
     * 获取用户信息
     */
    public void testPrintUserFollowing(){
        GithubService githubService = ServiceGenerator.createService(GithubService.class);
        Call<List<User>> userCall = githubService.getUserFollowing("yumodev");
        userCall.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                List<User> user = response.body();
                showToastMessage((new Gson()).toJson(user));
            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {

            }
        });
    }

    public void testPrintUserFollowingByRxjava(){
        GithubService githubService = ServiceGenerator.createService(GithubService.class);
        githubService.getUserFollowingObservable("yumodev")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<User>>(){

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<User> users) {
                        showToastMessage((new Gson()).toJson(users));
                    }
                });

    }
}


text:
RSpec.describe BreadcrumbTrail::Builder do
  let(:breadcrumbs) {
    [
      { path: "/", name: "home" },
      { path: "/foo", name: "foo" },
      { path: "/foo/bar", name: "foo/bar" }
    ].map { |data| BreadcrumbTrail::Breadcrumb.new(data) } }
  let(:context) { double("context") }

  subject { described_class.new(context, breadcrumbs) }

  it "raises on call" do
    expect { subject.call }.to raise_error(NotImplementedError)
  end
end


text:
package info.freelibrary.jiiify.handlers;

import static info.freelibrary.jiiify.Constants.HBS_DATA_KEY;
import static info.freelibrary.jiiify.Constants.HBS_PATH_SKIP_KEY;
import static info.freelibrary.jiiify.Constants.MESSAGES;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import info.freelibrary.jiiify.Configuration;
import info.freelibrary.jiiify.MessageCodes;
import info.freelibrary.jiiify.util.PathUtils;
import info.freelibrary.util.Logger;
import info.freelibrary.util.LoggerFactory;

import io.vertx.ext.web.RoutingContext;

/**
 * A handler that handles configuration refresh requests.
 *
 * @author Kevin S. Clarke
 */
public class RefreshHandler extends JiiifyHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(RefreshHandler.class, MESSAGES);

    /**
     * Creates a refresh handler
     *
     * @param aConfig The application's configuration
     */
    public RefreshHandler(final Configuration aConfig) {
        super(aConfig);
    }

    @Override
    public void handle(final RoutingContext aContext) {
        final String requestPath = aContext.request().uri();
        final String id = PathUtils.decode(requestPath.split("\\/")[4]);
        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode jsonNode = mapper.createObjectNode();

        LOGGER.debug(MessageCodes.DBG_062, aContext.request().uri());

        /* To drop the ID from the path for template processing */
        aContext.data().put(HBS_PATH_SKIP_KEY, 2 + slashCount(id));
        aContext.data().put(HBS_DATA_KEY, toHbsContext(jsonNode, aContext));
        aContext.next();
    }

    @Override
    protected Logger getLogger() {
        return LOGGER;
    }

}


text:
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;

namespace StephJob.Migrations
{
    public partial class AddTableEmploymentAveWeekEarnings : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "EmploymentAveWeekEarnings",
                columns: table => new
                {
                    EmploymentAveWeekEarningId = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    AverageWeeklyEarning2016 = table.Column<decimal>(type: "decimal(18, 2)", nullable: false),
                    Geo = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    Naics = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    NaicsCode2Digits = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    RefDate = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    Variable = table.Column<string>(type: "nvarchar(max)", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_EmploymentAveWeekEarnings", x => x.EmploymentAveWeekEarningId);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "EmploymentAveWeekEarnings");
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Posts | Leah Guthrie</title>
    <link>https://ltcguthrie.github.io/post/</link>
      <atom:link href="https://ltcguthrie.github.io/post/index.xml" rel="self" type="application/rss+xml" />
    <description>Posts</description>
    <generator>Wowchemy (https://wowchemy.com)</generator><language>en-us</language>
    <image>
      <url>https://ltcguthrie.github.io/media/icon_huded40674d5dd89b25aae90066bca22e4_122357_512x512_fill_lanczos_center_3.png</url>
      <title>Posts</title>
      <link>https://ltcguthrie.github.io/post/</link>
    </image>

  </channel>
</rss>


text:
import com.code_intelligence.jazzer.api.FuzzedDataProvider;

import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.AuthorizationGrantType;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.stream.Stream;
import java.util.Map;
import java.util.Set;

public class ClientRegistrationFuzzer {

     public static void fuzzerTestOneInput(FuzzedDataProvider data) {

        String registration = "registration-1";
        String scope = "email";
        String clientName = "Client 1";
        String clientId = "client-1";
        String clientSecret = "secret";
        String uri = "https://example.com";
        String config = "config-1";
        String value = "value-1";

        int switchInput = data.consumeInt(0,7);
        switch(switchInput) {
            case 0 :
                registration = data.consumeRemainingAsString();
                break;
            case 1 :
                scope = data.consumeRemainingAsString();
                break;
            case 2 :
                clientName = data.consumeRemainingAsString();
                break;
            case 3 :
                clientId = data.consumeRemainingAsString();
                break;
            case 4 :
                clientSecret = data.consumeRemainingAsString();
                break;
            case 5 :
                uri = data.consumeRemainingAsString();
                break;
            case 6 :
                config = data.consumeRemainingAsString();
                break;
            case 7 :
                value = data.consumeRemainingAsString();
                break;
        }

        Map<String, Object> configurationMetadata = new LinkedHashMap<>();
            configurationMetadata.put(config, value);
        Map<String, Object> PROVIDER_CONFIGURATION_METADATA = Collections
            .unmodifiableMap(configurationMetadata);

        ClientRegistration clientRegistration = null;
        try {
            clientRegistration = ClientRegistration.withRegistrationId(registration)
                .clientId(clientId)
                .clientSecret(clientSecret)
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .redirectUri(uri)
                .scope(scope)
                .authorizationUri(uri)
                .tokenUri(uri)
                .userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
                .issuerUri(uri)
                .providerConfigurationMetadata(null)
                .jwkSetUri(uri)
                .clientName(clientName)
                .build();

            ProviderDetails pd = clientRegistration.getProviderDetails();
        }
        catch (IllegalArgumentException iae){}

    }

}


text:
/**
 * This file includes some common utilities
 */

#if !defined HADOOP_SNAPPY_H
#define HADOOP_SNAPPY_H

#include <config.h>
#include <dlfcn.h>
#include <jni.h>

/* A helper macro to 'throw' a java exception. */
#define THROW(env, exception_name, message) \
  { \
	jclass ecls = env->FindClass(exception_name); \
	if (ecls) { \
	  env->ThrowNew(ecls, message); \
	  env->DeleteLocalRef(ecls); \
	} \
  }

/**
 * A helper function to dlsym a 'symbol' from a given library-handle.
 *
 * @param env jni handle to report contingencies.
 * @param handle handle to the dlopen'ed library.
 * @param symbol symbol to load.
 * @return returns the address where the symbol is loaded in memory,
 *         NULL on error.
 */

#define LOCK_CLASS(env, clazz, classname) \
  if (env->MonitorEnter(clazz) != 0) { \
    char exception_msg[128]; \
    snprintf(exception_msg, 128, "Failed to lock %s", classname); \
    THROW(env, "java/lang/InternalError", exception_msg); \
  }

#define UNLOCK_CLASS(env, clazz, classname) \
  if (env->MonitorExit(clazz) != 0) { \
    char exception_msg[128]; \
    snprintf(exception_msg, 128, "Failed to unlock %s", classname); \
    THROW(env, "java/lang/InternalError", exception_msg); \
  }

#endif


text: Hecho con amor por Elede Lab. 2015


text:
'use strict';
module.exports = function(sequelize, DataTypes) {
  var Interview = sequelize.define('Interview', {
    owner_id: DataTypes.INTEGER,
    start: DataTypes.DATE,
    end: DataTypes.DATE,
    interviewee_name: DataTypes.STRING,
    interviewee_email: DataTypes.STRING,
    title: DataTypes.STRING,
    roomid: DataTypes.STRING,
    status: DataTypes.STRING,
    drive_link: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        Interview.belongsTo(models.User, {foreignKey: 'owner_id'});
        Interview.belongsTo(models.Meeting, {foreignKey: 'roomid'});
      }
    }
  });
  return Interview;
};


text:
"""
ext_pylib.input.prompts
~~~~~~~~~~~~~~~~~~~~~~~

Functions for displaying and handling prompts on the terminal.
"""

from __future__ import print_function, unicode_literals

from ext_pylib.input import INPUT

def prompt(prompt_text, default=True):
    """Displays a yes/no prompt and returns the response as bool."""
    default_text = " [y] " if default else " [n] "
    while True:
        response = INPUT('[?] ' + prompt_text + default_text).lower()
        responses = {
            ''    : default,
            'y'   : True,
            'yes' : True,
            'n'   : False,
            'no'  : False,
        }
        if response in responses:
            return responses[response]
        else:
            print('Response not understood.')

def prompt_str(prompt_text, default_str=''):
    """Prompts for a string, returns the result."""
    add_text = ' '
    if default_str != '':
        add_text = ' [' + default_str + '] '

    response = INPUT('[?] ' + prompt_text + add_text)
    if response == '':
        response = default_str
    return response

def warn_prompt(prompt_text, required_response):
    """Warning prompt that prompts for a specific text (required_response).
    This is useful for potentially dangerous actions."""
    while True:
        response = INPUT("[!!] " + prompt_text + " [type n or '" + required_response + "'] ")
        if response == required_response:
            return True
        elif response.lower() in ['n', 'no']:
            return False
        else:
            print('Response not understood. Please type "n" or "required_response"')


text:
package com.melvin.share.model;

/**
 * Author: Melvin
 *

 * Data: 2016/7/23
 *

 * 描述:用于测试
 */
public class User extends BaseModel{

    public String username;
    public String password;
    public boolean isChecked=false;
    public boolean isShow=false;
}


text:
package com.computation.algo;

import com.computation.common.*;

import java.util.Collections;
import java.util.Comparator;
import java.util.Stack;

@SuppressWarnings("unused")
public class GrahamScan extends ConvexHull {
    public GrahamScan(Point2DCloud pointCloud, int threads,
                      boolean debug, int animationDelay) {
        super(pointCloud, threads, debug, animationDelay);
    }

    @Override
    protected void findHull() {

        Stack<Point2D> stack = new Stack<Point2D>();
        pointCloud.setField("ThreadPool", true);

        // preprocess so that points[0] has lowest y-coordinate; break ties by
        // x-coordinate
        // points[0] is an extreme point of the convex hull
        // (alternatively, could do easily in linear time)

        Collections.sort(points, new Comparator<Point2D>() {
            public int compare(Point2D p1, Point2D p2) {
                if (p2.y == p1.y) {
                    return p1.x - p2.x;
                }

                return p2.y - p1.y;
            }
        });

        final Point2D firstPoint = points.get(0);

        stack.push(firstPoint);

        points.remove(0);

        // sort by polar angle with respect to base point points[0],
        // breaking ties by distance to points[0]
        Collections.sort(points, new Comparator<Point2D>() {
            public int compare(Point2D q1, Point2D q2) {

                double dx1 = q1.x - firstPoint.x;
                double dy1 = q1.y - firstPoint.y;
                double dx2 = q2.x - firstPoint.x;
                double dy2 = q2.y - firstPoint.y;

                if (dy1 >= 0 && dy2 < 0) {
                    return -1; // q1 above; q2 below
                } else if (dy2 >= 0 && dy1 < 0) {
                    return +1; // q1 below; q2 above
                }
                // 3-collinear and horizontal
                else if (dy1 == 0 && dy2 == 0) {
                    if (dx1 >= 0 && dx2 < 0) {
                        return -1;
                    } else if (dx2 >= 0 && dx1 < 0) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
                // both above or below
                else {
                    // Note: ccwQuant() recomputes dx1, dy1, dx2, and dy2
                    return -Utils.ccwQuant(firstPoint, q1, q2);
                }
            }
        });

        stack.push(points.get(0)); // p[0] is first extreme point
        stack.push(points.get(1));

        int k1;
        for (k1 = 1; k1 < points.size(); k1++) {
            if (!points.get(0).equals(points.get(k1))) {
                break;
            }
        }

        // all points equal
        if (k1 == points.size()) {
            return;
        }

        // find index k2 of first point not collinear with points[0] and points[k1]
        int k2;
        for (k2 = k1 + 1; k2 < points.size(); k2++) {
            if (Utils.ccwQuant(points.get(0), points.get(k1), points.get(k2)) != 0) {
                break;
            }
        }

        stack.push(points.get(k2 - 1));    // points[k2-1] is second extreme point

        // Graham scan; note that points[N-1] is extreme point different from points[0]
        for (int i = k2; i < points.size(); i++) {
            Point2D top = stack.pop();

            while (Utils.ccwQuant(stack.peek(), top, points.get(i)) <= 0) {
                top = stack.pop();
            }

            stack.push(top);
            stack.push(points.get(i));
        }

        while (stack.size() != 1) {
            requestAnimationFrame();
            delay();

            Point2D a = stack.pop();
            Point2D b = stack.pop();

            a.setColor(Point2D.VISITED);
            b.setColor(Point2D.VISITED);

            pointCloud.addEdge(new Edge(a, b));
            stack.push(b);
            releaseAnimationFrame();
        }

        pointCloud.addEdge(new Edge(firstPoint, points.get(points.size() - 1)));
    }
}


text:
class IngameMenuState : public GameState {
  public:
    std::map<std::string, Urho3D::SharedPtr<Urho3D::UIElement>> b_p;
    IngameMenuState(Urho3D::Context *context);
    ~IngameMenuState();
    void HandleUpdate(Urho3D::StringHash eventType, Urho3D::VariantMap &event_data);
    void HandleKeyDown(Urho3D::StringHash eventType, Urho3D::VariantMap &event_data);
    void HandleControlClicked(Urho3D::StringHash eventType, Urho3D::VariantMap &eventData);
    void HandleOnHoverBegin(Urho3D::StringHash eventType, Urho3D::VariantMap &eventData);
    void HandleStartButtonReleased(Urho3D::StringHash eventType, Urho3D::VariantMap &event_data);
    void Start();
    void Stop();
    void create_ui();
    void subscribe_to_events();
    void unsubscribe_events();
    virtual const Urho3D::TypeInfo *GetTypeInfo() const;
    virtual const Urho3D::String &GetTypeName() const;

  private:
};

#endif


text:
package android.support.v17.leanback.widget;

import android.content.Context;
import android.support.v17.leanback.R;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.EditText;

/**
 * EditText widget that monitors keyboard changes.
 */
public class SearchEditText extends EditText {
    private static final String TAG = SearchEditText.class.getSimpleName();
    private static final boolean DEBUG = false;

    public interface OnKeyboardDismissListener {
        public void onKeyboardDismiss();
    }

    private OnKeyboardDismissListener mKeyboardDismissListener;

    public SearchEditText(Context context) {
        this(context, null);
    }

    public SearchEditText(Context context, AttributeSet attrs) {
        this(context, attrs, R.style.TextAppearance_Leanback_SearchTextEdit);
    }

    public SearchEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (DEBUG) Log.v(TAG, "Keyboard being dismissed");
            mKeyboardDismissListener.onKeyboardDismiss();
            return true;
        }
        return super.onKeyPreIme(keyCode, event);
    }

    /**
     * Set a keyboard dismissed listener.
     *
     * @param listener The listener.
     */
    public void setOnKeyboardDismissListener(OnKeyboardDismissListener listener) {
        mKeyboardDismissListener = listener;
    }
}


text:
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt

using System;
using System.IO;

namespace NUnit.Engine.Internal
{
    /// <summary>
    /// Provides internal logging to the NUnit framework
    /// </summary>
    public class Logger : ILogger
    {
        private const string TimeFmt = "HH:mm:ss.fff";
        private const string TraceFmt = "{0} {1,-5} [{2,2}] {3}: {4}";

        private readonly string _name;
        private readonly TextWriter _writer;

        public InternalTraceLevel TraceLevel { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="Logger"/> class.
        /// </summary>
        /// <param name="fullName">The name.</param>
        /// <param name="level">The log level.</param>
        /// <param name="writer">The writer where logs are sent.</param>
        public Logger(string fullName, InternalTraceLevel level, TextWriter writer)
        {
            TraceLevel = level;
            _writer = writer;

            var index = fullName.LastIndexOf('.');
            _name = index >= 0 ? fullName.Substring(index + 1) : fullName;
        }

        /// <summary>
        /// Logs the message at error level.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Error(string message)
        {
            Log(InternalTraceLevel.Error, message);
        }

        /// <summary>
        /// Logs the message at error level.
        /// </summary>
        /// <param name="format">The message.</param>
        /// <param name="args">The message arguments.</param>
        public void Error(string format, params object[] args)
        {
            Log(InternalTraceLevel.Error, format, args);
        }

        /// <summary>
        /// Logs the message at warm level.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Warning(string message)
        {
            Log(InternalTraceLevel.Warning, message);
        }

        /// <summary>
        /// Logs the message at warning level.
        /// </summary>
        /// <param name="format">The message.</param>
        /// <param name="args">The message arguments.</param>
        public void Warning(string format, params object[] args)
        {
            Log(InternalTraceLevel.Warning, format, args);
        }

        /// <summary>
        /// Logs the message at info level.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Info(string message)
        {
            Log(InternalTraceLevel.Info, message);
        }

        /// <summary>
        /// Logs the message at info level.
        /// </summary>
        /// <param name="format">The message.</param>
        /// <param name="args">The message arguments.</param>
        public void Info(string format, params object[] args)
        {
            Log(InternalTraceLevel.Info, format, args);
        }

        /// <summary>
        /// Logs the message at debug level.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Debug(string message)
        {
            Log(InternalTraceLevel.Verbose, message);
        }

        /// <summary>
        /// Logs the message at debug level.
        /// </summary>
        /// <param name="format">The message.</param>
        /// <param name="args">The message arguments.</param>
        public void Debug(string format, params object[] args)
        {
            Log(InternalTraceLevel.Verbose, format, args);
        }

        private void Log(InternalTraceLevel level, string message)
        {
            if (_writer != null && TraceLevel >= level)
                WriteLog(level, message);
        }

        private void Log(InternalTraceLevel level, string format, params object[] args)
        {
            if (TraceLevel >= level)
                WriteLog(level, string.Format(format, args));
        }

        private void WriteLog(InternalTraceLevel level, string message)
        {
            _writer.WriteLine(TraceFmt,
                DateTime.Now.ToString(TimeFmt),
                level,
#if NET20
                System.Threading.Thread.CurrentThread.ManagedThreadId,
#else
                Environment.CurrentManagedThreadId,
#endif
                _name, message);
        }
    }
}


text:
typedef struct _MACROCMD {
  char cmd[TEXTLEN];
} MACROCMD, *PMACROCMD;

typedef struct t_cmdque {
  int  n;
  char cmd[TEXTLEN];
  struct t_cmdque *next;
} COMMAND_QUE, *PCOMMAND_QUE;

int IsHex(const char* str);

int Express(char *answer,ulong parm);
int Addwtch(char *answer,ulong parm);
int Dasmcmd(char *answer,ulong parm);
int Dorigin(char *answer,ulong parm);
int Dumpcmd(char *answer,ulong parm);
int Stakcmd(char *answer,ulong parm);
int Assembl(char *answer,ulong parm);
int LineAsm(char *answer,ulong parm);
int LineDsm(char *answer,ulong parm);
int Commlab(char *answer,ulong parm);
int Breakpt(char *answer,ulong parm);
int Brkname(char *answer,ulong parm);
int Delbkpt(char *answer,ulong parm);
int Membkpt(char *answer,ulong parm);
int Hwbreak(char *answer,ulong parm);
int Runprog(char *answer,ulong parm);
int Stepper(char *answer,ulong parm);
int Tracing(char *answer,ulong parm);
int Keystrk(char *answer,ulong parm);
int Ctrlkey(char *answer,ulong parm);
int CtlDasm(char *answer,ulong parm);
int Altkeyd(char *answer,ulong parm);
int Openexe(char *answer,ulong parm);
int Heeeelp(char *answer,ulong parm);
int LoadMac(char *answer,ulong parm);

int Execute(char *s,char *answer);
int GetCmdlistSize(void);
void SetCmdInfo(HWND hw, char *cmd);

#endif //__CMDEXEC_H


text:
package gpio

import (
	"errors"
	"testing"

	"github.com/hybridgroup/gobot"
	"github.com/hybridgroup/gobot/gobottest"
)

var _ gobot.Driver = (*DirectPinDriver)(nil)

func initTestDirectPinDriver(conn gobot.Connection) *DirectPinDriver {
	testAdaptorDigitalRead = func() (val int, err error) {
		val = 1
		return
	}
	testAdaptorDigitalWrite = func() (err error) {
		return errors.New("write error")
	}
	testAdaptorAnalogRead = func() (val int, err error) {
		val = 80
		return
	}
	testAdaptorPwmWrite = func() (err error) {
		return errors.New("write error")
	}
	testAdaptorServoWrite = func() (err error) {
		return errors.New("write error")
	}
	return NewDirectPinDriver(conn, "bot", "1")
}

func TestDirectPinDriver(t *testing.T) {
	var ret map[string]interface{}
	var err interface{}

	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	gobottest.Assert(t, d.Name(), "bot")
	gobottest.Assert(t, d.Pin(), "1")
	gobottest.Assert(t, d.Connection().Name(), "adaptor")

	ret = d.Command("DigitalRead")(nil).(map[string]interface{})

	gobottest.Assert(t, ret["val"].(int), 1)
	gobottest.Assert(t, ret["err"], nil)

	err = d.Command("DigitalWrite")(map[string]interface{}{"level": "1"})
	gobottest.Assert(t, err.(error), errors.New("write error"))

	ret = d.Command("AnalogRead")(nil).(map[string]interface{})

	gobottest.Assert(t, ret["val"].(int), 80)
	gobottest.Assert(t, ret["err"], nil)

	err = d.Command("PwmWrite")(map[string]interface{}{"level": "1"})
	gobottest.Assert(t, err.(error), errors.New("write error"))

	err = d.Command("ServoWrite")(map[string]interface{}{"level": "1"})
	gobottest.Assert(t, err.(error), errors.New("write error"))
}

func TestDirectPinDriverStart(t *testing.T) {
	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	gobottest.Assert(t, len(d.Start()), 0)
}

func TestDirectPinDriverHalt(t *testing.T) {
	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	gobottest.Assert(t, len(d.Halt()), 0)
}

func TestDirectPinDriverOff(t *testing.T) {
	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	gobottest.Refute(t, d.DigitalWrite(0), nil)

	d = initTestDirectPinDriver(&gpioTestBareAdaptor{})
	gobottest.Assert(t, d.DigitalWrite(0), ErrDigitalWriteUnsupported)
}

func TestDirectPinDriverOn(t *testing.T) {
	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	gobottest.Refute(t, d.DigitalWrite(1), nil)

	d = initTestDirectPinDriver(&gpioTestBareAdaptor{})
	gobottest.Assert(t, d.DigitalWrite(1), ErrDigitalWriteUnsupported)
}

func TestDirectPinDriverDigitalWrite(t *testing.T) {
	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	gobottest.Refute(t, d.DigitalWrite(1), nil)

	d = initTestDirectPinDriver(&gpioTestBareAdaptor{})
	gobottest.Assert(t, d.DigitalWrite(1), ErrDigitalWriteUnsupported)
}

func TestDirectPinDriverDigitalRead(t *testing.T) {
	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	ret, err := d.DigitalRead()
	gobottest.Assert(t, ret, 1)

	d = initTestDirectPinDriver(&gpioTestBareAdaptor{})
	ret, err = d.DigitalRead()
	gobottest.Assert(t, err, ErrDigitalReadUnsupported)
}

func TestDirectPinDriverAnalogRead(t *testing.T) {
	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	ret, err := d.AnalogRead()
	gobottest.Assert(t, ret, 80)

	d = initTestDirectPinDriver(&gpioTestBareAdaptor{})
	ret, err = d.AnalogRead()
	gobottest.Assert(t, err, ErrAnalogReadUnsupported)
}

func TestDirectPinDriverPwmWrite(t *testing.T) {
	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	gobottest.Refute(t, d.PwmWrite(1), nil)

	d = initTestDirectPinDriver(&gpioTestBareAdaptor{})
	gobottest.Assert(t, d.PwmWrite(1), ErrPwmWriteUnsupported)
}
func TestDirectPinDriverDigitalWrie(t *testing.T) {
	d := initTestDirectPinDriver(newGpioTestAdaptor("adaptor"))
	gobottest.Refute(t, d.ServoWrite(1), nil)

	d = initTestDirectPinDriver(&gpioTestBareAdaptor{})
	gobottest.Assert(t, d.ServoWrite(1), ErrServoWriteUnsupported)
}


text:
package org.ihtsdo.otf.ts.rest.impl;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.ihtsdo.otf.ts.Project;
import org.ihtsdo.otf.ts.UserRole;
import org.ihtsdo.otf.ts.helpers.ConceptList;
import org.ihtsdo.otf.ts.helpers.ConceptListJpa;
import org.ihtsdo.otf.ts.helpers.PfsParameterJpa;
import org.ihtsdo.otf.ts.helpers.ProjectList;
import org.ihtsdo.otf.ts.jpa.ProjectJpa;
import org.ihtsdo.otf.ts.jpa.services.ProjectServiceJpa;
import org.ihtsdo.otf.ts.jpa.services.SecurityServiceJpa;
import org.ihtsdo.otf.ts.rest.ProjectServiceRest;
import org.ihtsdo.otf.ts.rf2.Concept;
import org.ihtsdo.otf.ts.rf2.jpa.ConceptJpa;
import org.ihtsdo.otf.ts.services.ProjectService;
import org.ihtsdo.otf.ts.services.SecurityService;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

/**
 * REST implementation for {@link ProjectServiceRest}..
 */
@Path("/project")
@Consumes({
    MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML
})
@Produces({
    MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML
})
@Api(value = "/project", description = "Operations to retrieve project info.")
public class ProjectServiceRestImpl extends RootServiceRestImpl implements
    ProjectServiceRest {

  /** The security service. */
  private SecurityService securityService;

  /**
   * Instantiates an empty {@link ProjectServiceRestImpl}.
   *
   * @throws Exception the exception
   */
  public ProjectServiceRestImpl() throws Exception {
    securityService = new SecurityServiceJpa();
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.ihtsdo.otf.ts.rest.ProjectServiceRest#addProject(org.ihtsdo.otf.ts.
   * jpa.ProjectJpa, java.lang.String)
   */
  @Override
  @PUT
  @Path("/add")
  @ApiOperation(value = "Add new project", notes = "Creates a new project.", response = Project.class)
  public Project addProject(
    @ApiParam(value = "Project, e.g. newProject", required = true) ProjectJpa project,
    @ApiParam(value = "Authorization token, e.g. 'guest'", required = true) @HeaderParam("Authorization") String authToken)
    throws Exception {
    Logger.getLogger(getClass()).info(
        "RESTful call PUT (Project): /add " + project);

    ProjectService projectService = new ProjectServiceJpa();
    try {
      authenticate(securityService, authToken, "add project",
          UserRole.ADMINISTRATOR);

      // check to see if project already exists
      for (Project p : projectService.getProjects().getObjects()) {
        if (p.getName().equals(project.getName())
            && p.getDescription().equals(project.getDescription())) {
          throw new Exception(
              "A project with this name and description already exists.");
        }
      }

      // Add project
      project.setLastModifiedBy(securityService.getUsernameForToken(authToken));
      Project newProject = projectService.addProject(project);
      return newProject;
    } catch (Exception e) {
      handleException(e, "trying to add a project");
      return null;
    } finally {
      projectService.close();
      securityService.close();
    }

  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.ihtsdo.otf.ts.rest.ProjectServiceRest#updateProject(org.ihtsdo.otf.
   * ts.jpa.ProjectJpa, java.lang.String)
   */
  @Override
  @POST
  @Path("/update")
  @ApiOperation(value = "Update project", notes = "Updates the specified project.")
  public void updateProject(
    @ApiParam(value = "Project, e.g. existingProject", required = true) ProjectJpa project,
    @ApiParam(value = "Authorization token, e.g. 'guest'", required = true) @HeaderParam("Authorization") String authToken)
    throws Exception {
    Logger.getLogger(getClass()).info(
        "RESTful call PUT (Project): /update " + project);

    // Create service and configure transaction scope
    ProjectService projectService = new ProjectServiceJpa();
    try {
      authenticate(securityService, authToken, "update project",
          UserRole.ADMINISTRATOR);

      // check to see if project already exists
      boolean found = false;
      for (Project p : projectService.getProjects().getObjects()) {
        if (p.getId().equals(project.getId())) {
          found = true;
          break;
        }
      }
      if (!found) {
        throw new Exception("Project " + project.getId() + " does not exist.");
      }

      // Update project
      project.setLastModifiedBy(securityService.getUsernameForToken(authToken));
      projectService.updateProject(project);

    } catch (Exception e) {
      handleException(e, "trying to update a project");
    } finally {
      projectService.close();
      securityService.close();
    }

  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.ihtsdo.otf.ts.rest.ProjectServiceRest#removeProject(java.lang.Long,
   * java.lang.String)
   */
  @Override
  @DELETE
  @Path("/remove/id/{id}")
  @ApiOperation(value = "Remove project", notes = "Removes the project with the specified id.")
  public void removeProject(
    @ApiParam(value = "Project id, e.g. 3", required = true) @PathParam("id") Long id,
    @ApiParam(value = "Authorization token, e.g. 'guest'", required = true) @HeaderParam("Authorization") String authToken)
    throws Exception {
    Logger.getLogger(getClass()).info(
        "RESTful call DELETE (Project): /remove/id/" + id);

    ProjectService projectService = new ProjectServiceJpa();
    try {
      authenticate(securityService, authToken, "remove project",
          UserRole.ADMINISTRATOR);

      // Create service and configure transaction scope
      projectService.removeProject(id);

    } catch (Exception e) {
      handleException(e, "trying to remove a project");
    } finally {
      projectService.close();
      securityService.close();
    }

  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.ihtsdo.otf.ts.rest.ProjectServiceRest#findConceptsInScope(java.lang
   * .Long, org.ihtsdo.otf.ts.helpers.PfsParameterJpa, java.lang.String)
   */
  @Override
  @POST
  @Path("/scope/id/{id}")
  @ApiOperation(value = "Find project scope for the project id", notes = "Gets all concpets in scope for this project.", response = ConceptList.class)
  public ConceptList findConceptsInScope(
    @ApiParam(value = "Project internal id, e.g. 2", required = true) @PathParam("id") Long id,
    @ApiParam(value = "PFS Parameter, e.g. '{ \"startIndex\":\"1\", \"maxResults\":\"5\" }'", required = false) PfsParameterJpa pfs,
    @ApiParam(value = "Authorization token, e.g. 'guest'", required = true) @HeaderParam("Authorization") String authToken)
    throws Exception {

    Logger.getLogger(getClass()).info("RESTful call (Project): scope/id/" + id);

    ProjectService projectService = new ProjectServiceJpa();
    try {
      authenticate(securityService, authToken, "get project scope",
          UserRole.VIEWER);

      ConceptList list =
          projectService
              .findConceptsInScope(projectService.getProject(id), pfs);
      // Need to detach the concepts.
      ConceptList list2 = new ConceptListJpa();
      for (Concept c : list.getObjects()) {
        list2.addObject(new ConceptJpa(c, false, false));
      }
      list2.setTotalCount(list.getTotalCount());
      return list2;
    } catch (Exception e) {
      handleException(e, "trying to retrieve scope concepts for project " + id);
      return null;
    } finally {
      projectService.close();
      securityService.close();
    }

  }

  /*
   * (non-Javadoc)
   *
   * @see org.ihtsdo.otf.ts.rest.ProjectServiceRest#getProject(java.lang.Long,
   * java.lang.String)
   */
  @Override
  @GET
  @Path("/id/{id}")
  @ApiOperation(value = "Get project for id", notes = "Gets the project for the specified id.", response = Project.class)
  public Project getProject(
    @ApiParam(value = "Project internal id, e.g. 2", required = true) @PathParam("id") Long id,
    @ApiParam(value = "Authorization token, e.g. 'guest'", required = true) @HeaderParam("Authorization") String authToken)
    throws Exception {
    Logger.getLogger(getClass()).info("RESTful call (Project): /id/" + id);

    ProjectService projectService = new ProjectServiceJpa();
    try {
      authenticate(securityService, authToken, "retrieve the project",
          UserRole.VIEWER);

      Project project = projectService.getProject(id);
      return project;
    } catch (Exception e) {
      handleException(e, "trying to retrieve a project");
      return null;
    } finally {
      projectService.close();
      securityService.close();
    }

  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.ihtsdo.otf.ts.rest.ProjectServiceRest#getProjects(java.lang.String)
   */
  @Override
  @GET
  @Path("/projects")
  @ApiOperation(value = "Get all projects", notes = "Gets all projects.", response = ProjectList.class)
  public ProjectList getProjects(
    @ApiParam(value = "Authorization token, e.g. 'guest'", required = true) @HeaderParam("Authorization") String authToken)
    throws Exception {
    Logger.getLogger(getClass()).info("RESTful call (Project): /projects");

    ProjectService projectService = new ProjectServiceJpa();
    try {
      authenticate(securityService, authToken, "retrieve projects",
          UserRole.VIEWER);

      ProjectList projects = projectService.getProjects();
      for (Project project : projects.getObjects()) {
        project.getScopeConcepts().size();
        project.getScopeExcludesConcepts().size();
        project.getActionWorkflowStatusValues().size();
      }
      return projects;
    } catch (Exception e) {
      handleException(e, "trying to retrieve the projects");
      return null;
    } finally {
      projectService.close();
      securityService.close();
    }

  }

}


text:
<?php

declare(strict_types=1);

namespace Docker\Context;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

/**
 * Docker\Context\Context.
 */
class Context implements ContextInterface
{
    public const FORMAT_STREAM = 'stream';

    public const FORMAT_TAR = 'tar';

    /**
     * @var bool Whether to remove the context directory
     */
    private $cleanup = false;

    /**
     * @var string
     */
    private $directory;

    /**
     * @var process Tar process
     */
    private $process;

    /**
     * @var Filesystem
     */
    private $fs;

    /**
     * @var resource Tar stream
     */
    private $stream;

    /**
     * @var string Format of the context (stream or tar)
     */
    private $format = self::FORMAT_STREAM;

    /**
     * @param string     $directory Directory of context
     * @param string     $format    Format to use when sending the call (stream or tar: string)
     * @param Filesystem $fs        filesystem object for cleaning the context directory on destruction
     */
    public function __construct($directory, $format = self::FORMAT_STREAM, Filesystem $fs = null)
    {
        $this->directory = $directory;
        $this->format = $format;
        $this->fs = $fs ?? new Filesystem();
    }

    /**
     * Get directory of Context.
     *
     * @return string
     */
    public function getDirectory()
    {
        return $this->directory;
    }

    /**
     * Set directory of Context.
     *
     * @param string $directory Targeted directory
     */
    public function setDirectory($directory): void
    {
        $this->directory = $directory;
    }

    /**
     * Return content of Dockerfile of this context.
     *
     * @return string Content of dockerfile
     */
    public function getDockerfileContent()
    {
        return \file_get_contents($this->directory.DIRECTORY_SEPARATOR.'Dockerfile');
    }

    /**
     * @return bool
     */
    public function isStreamed()
    {
        return self::FORMAT_STREAM === $this->format;
    }

    /**
     * @return resource|string
     */
    public function read()
    {
        return $this->isStreamed() ? $this->toStream() : $this->toTar();
    }

    /**
     * Return the context as a tar archive.
     *
     * @throws \Symfony\Component\Process\Exception\ProcessFailedException
     *
     * @return string Tar content
     */
    public function toTar()
    {
        $process = new Process('/usr/bin/env tar c .', $this->directory);
        $process->run();

        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        return $process->getOutput();
    }

    /**
     * Return a stream for this context.
     *
     * @return resource Stream resource in memory
     */
    public function toStream()
    {
        if (!\is_resource($this->process)) {
            $this->process = \proc_open('/usr/bin/env tar c .', [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes, $this->directory);
            $this->stream = $pipes[1];
        }

        return $this->stream;
    }

    public function __destruct()
    {
        if (\is_resource($this->stream)) {
            \fclose($this->stream);
        }

        if (\is_resource($this->process)) {
            \proc_close($this->process);
        }

        if ($this->cleanup) {
            $this->fs->remove($this->directory);
        }
    }

    /**
     * @param bool $value whether to remove the context directory
     */
    public function setCleanup(bool $value): void
    {
        $this->cleanup = $value;
    }
}


text:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "/home/jairfrancesco/OpenSurf/main.cpp" "/home/jairfrancesco/OpenSurf/CMakeFiles/surffeat.dir/main.cpp.o"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  "/home/jairfrancesco/OpenSurf/CMakeFiles/surf.dir/DependInfo.cmake"
  )

# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
  "/usr/local/include"
  "/usr/local/include/opencv"
  )
set(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})


text:
package org.openkilda.messaging.payload.flow;

import org.openkilda.messaging.Utils;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FlowCreatePayload extends FlowPayload {

    @JsonProperty("diverse-flowid")
    private String diverseFlowId;

    /**
     * Instance constructor.
     *
     * @param id                        flow id
     * @param source                    flow source
     * @param destination               flow destination
     * @param maximumBandwidth          flow maximum bandwidth
     * @param ignoreBandwidth           should ignore bandwidth in path computation
     * @param periodicPings             enable periodic flow pings
     * @param allocateProtectedPath     allocate flow protected path
     * @param description               flow description
     * @param created                   flow created timestamp
     * @param lastUpdated               flow last updated timestamp
     * @param diverseFlowId             make new flow diverse with FlowId
     * @param status                    flow status
     * @param maxLatency                max latency
     * @param priority                  flow priority
     * @param pinned                    pinned flag
     * @param encapsulationType         flow encapsulation type
     * @param pathComputationStrategy   path computation strategy
     */
    @JsonCreator
    public FlowCreatePayload(@JsonProperty(Utils.FLOW_ID) String id,
                             @JsonProperty("source") FlowEndpointPayload source,
                             @JsonProperty("destination") FlowEndpointPayload destination,
                             @JsonProperty("maximum-bandwidth") long maximumBandwidth,
                             @JsonProperty("ignore_bandwidth") Boolean ignoreBandwidth,
                             @JsonProperty("periodic-pings") Boolean periodicPings,
                             @JsonProperty("allocate_protected_path") Boolean allocateProtectedPath,
                             @JsonProperty("description") String description,
                             @JsonProperty("created") String created,
                             @JsonProperty("last-updated") String lastUpdated,
                             @JsonProperty("diverse-flowid") String diverseFlowId,
                             @JsonProperty("status") String status,
                             @JsonProperty("max-latency") Long maxLatency,
                             @JsonProperty("priority") Integer priority,
                             @JsonProperty("pinned") Boolean pinned,
                             @JsonProperty("encapsulation-type") String encapsulationType,
                             @JsonProperty("path-computation-strategy") String pathComputationStrategy) {
        super(id, source, destination, maximumBandwidth, ignoreBandwidth, periodicPings, allocateProtectedPath,
                description, created, lastUpdated, status, maxLatency, priority, pinned, encapsulationType,
                pathComputationStrategy);
        this.diverseFlowId = diverseFlowId;
    }
}