text:
const cssPrefix = require('postcss-prefix')
const nodeResolve = require('resolve')
const mapLimit = require('map-limit')
const postcss = require('postcss')
const assert = require('assert')
const crypto = require('crypto')
const stackTrace = require('stack-trace')
const cssResolve = require('style-resolve').sync
const fs = require('fs')
const path = require('path')

module.exports = sheetify
module.exports.getPrefix = getPrefix

// transform css
// (str, str, obj?, fn) -> str
function sheetify (src, filename, options, done) {
  // browserify transform
  if (typeof src === 'string' && !/\n/.test(src) && filename && filename._flags) {
    var args = Array.prototype.slice.apply(arguments)
    return require('./transform.js').apply(this, args)
  }

  // handle tagged template calls directly from Node
  const isTemplate = Array.isArray(src)
  if (isTemplate) src = src.join('')
  assert.equal(typeof src, 'string', 'src must be a string')
  src = src.trim()

  // Ensure prefix is always correct when run from inside node
  var css
  if (!isTemplate && (!filename || typeof filename === 'object')) {
    // module or file name via tagged template call w or w/out options
    const callerDirname = path.dirname(stackTrace.get()[1].getFileName())
    const resolved = cssResolve(src, { basedir: callerDirname })
    css = fs.readFileSync(resolved, 'utf8')
  } else {
    // it better be some css
    css = src
  }

  const prefix = getPrefix(css)

  // only parse if in a browserify transform
  if (typeof filename === 'string') parseCss(src, filename, prefix, options, done)

  return prefix
}

function getPrefix (css) {
  const prefix = '_' + crypto.createHash('md5')
    .update(css.trim())
    .digest('hex')
    .slice(0, 8)
  return prefix
}

// parse css
// (str, str, str, obj, fn) -> null
function parseCss (src, filename, prefix, options, done) {
  assert.equal(typeof filename, 'string', 'filename must be a string')
  assert.equal(typeof prefix, 'string', 'prefix must be a string')
  assert.equal(typeof options, 'object', 'options must be a object')
  assert.equal(typeof done, 'function', 'done must be a function')

  applyTransforms(filename, String(src), Object.assign({}, options), function (err, result) {
    if (err) return done(err)
    var p = postcss()
    p = p.use(cssPrefix('.' + prefix))

    try {
      result.css = p.process(result.css).toString()

      return done(null, result, prefix)
    } catch (e) {
      return done(e)
    }
  })

  // apply transforms to a string of css,
  // one at the time
  // (str, str, obj, fn) -> null
  function applyTransforms (filename, src, options, done) {
    var current = { css: src, files: [] }
    mapLimit(options.transform, 1, iterate, function (err) {
      if (err) return done(err)
      done(null, current)
    })

    // find and apply a transform to a string of css
    // (fn, fn) -> null
    function iterate (plugin, next) {
      if (typeof plugin === 'string' || typeof plugin === 'function') {
        plugin = [ plugin, {} ]
      } else if (!Array.isArray(plugin)) {
        return done(new Error('Plugin must be a string or array'))
      }

      const name = plugin[0]
      const opts = plugin[1] || {}
      if (typeof name === 'function') {
        return transformLoaded(name, opts)
      }

      const resolveOpts = {
        basedir: opts.basedir || options.basedir || process.cwd()
      }
      nodeResolve(name, resolveOpts, function (err, transformPath) {
        if (err) return done(err)

        const transform = require(transformPath)
        transformLoaded(transform, opts)
      })

      function transformLoaded (transform, opts) {
        transform(filename, current.css, opts, function (err, result) {
          if (err) return next(err)
          if (typeof result === 'string') {
            current.css = result
          } else {
            current.css = result.css
            current.files = current.files.concat(result.files)
          }
          next()
        })
      }
    }
  }
}


text:
	<title>Richard McCourt's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Richard McCourt's panel show appearances

Richard McCourt (born 1976-08-12[ref]) has appeared in 1 episodes between 2009-2009.  Richard McCourt on Wikipedia.

2009

2009-03-25 / Celebrity Juice

redpajama_set_name: RedPajamaGithub


text:
package it.unibz.inf.ontop.spec.mapping.parser.impl;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import it.unibz.inf.ontop.exception.*;
import it.unibz.inf.ontop.injection.TargetQueryParserFactory;
import it.unibz.inf.ontop.spec.mapping.TargetAtom;
import it.unibz.inf.ontop.injection.SQLPPMappingFactory;
import it.unibz.inf.ontop.injection.SpecificationFactory;
import it.unibz.inf.ontop.spec.mapping.PrefixManager;
import it.unibz.inf.ontop.spec.mapping.SQLPPSourceQueryFactory;
import it.unibz.inf.ontop.spec.mapping.parser.SQLMappingParser;
import it.unibz.inf.ontop.spec.mapping.parser.TargetQueryParser;
import it.unibz.inf.ontop.spec.mapping.pp.SQLPPMapping;
import it.unibz.inf.ontop.spec.mapping.pp.SQLPPTriplesMap;
import it.unibz.inf.ontop.spec.mapping.pp.impl.OntopNativeSQLPPTriplesMap;
import org.apache.commons.rdf.api.Graph;

import java.io.*;
import java.util.*;
import java.util.function.Supplier;

import static it.unibz.inf.ontop.exception.InvalidMappingExceptionWithIndicator.*;

/**
 * Mapping parser specific to the Ontop Native Mapping Language for SQL.
 *
 * Available through Guice.
 *
 */
public class OntopNativeMappingParser implements SQLMappingParser {

    public static final String MAPPING_ID_LABEL = "mappingId";
    public static final String TARGET_LABEL = "target";
    public static final String SOURCE_LABEL = "source";

    public static final String PREFIX_DECLARATION_TAG = "[PrefixDeclaration]";
    private static final ImmutableList<String> DEPRECATED_TAGS = ImmutableList.of(
            "[ClassDeclaration]", "[ObjectPropertyDeclaration]", "[DataPropertyDeclaration]");
    protected static final String SOURCE_DECLARATION_TAG = "[SourceDeclaration]";
    public static final String MAPPING_DECLARATION_TAG = "[MappingDeclaration]";

    public static final String START_COLLECTION_SYMBOL = "@collection [[";
    public static final String END_COLLECTION_SYMBOL = "]]";
    protected static final String COMMENT_SYMBOL = ";";

    private final TargetQueryParserFactory targetQueryParserFactory;
    private final SQLPPMappingFactory ppMappingFactory;
    private final SpecificationFactory specificationFactory;
    private final SQLPPSourceQueryFactory sourceQueryFactory;

    /**
     * Create an SQL Mapping Parser for generating an OBDA model.
     */
    @Inject
    private OntopNativeMappingParser(SpecificationFactory specificationFactory,
                                     TargetQueryParserFactory targetQueryParserFactory,
                                     SQLPPMappingFactory ppMappingFactory,
                                     SQLPPSourceQueryFactory sourceQueryFactory) {
        this.targetQueryParserFactory = targetQueryParserFactory;
        this.ppMappingFactory = ppMappingFactory;
        this.specificationFactory = specificationFactory;
        this.sourceQueryFactory = sourceQueryFactory;
    }

    /**
     * Parsing is not done at construction time because our dependency
     * injection framework (Guice) does not manage exceptions nicely.
     *
     */
    @Override
    public SQLPPMapping parse(File file) throws InvalidMappingException, MappingIOException {
        if (!file.exists()) {
            throw new MappingIOException("WARNING: Cannot locate OBDA file at: " + file.getPath());
        }
        if (!file.canRead()) {
            throw new MappingIOException(String.format("Error while reading the file located at %s.\n" +
                    "Make sure you have the read permission at the location specified.", file.getAbsolutePath()));
        }
        try (Reader reader = new FileReader(file)) {
            return load(reader, specificationFactory, ppMappingFactory, file.getName());
        }
        catch (IOException e) {
            throw new MappingIOException(e);
        }
    }

    @Override
    public SQLPPMapping parse(Reader reader) throws InvalidMappingException, MappingIOException {
        return load(reader, specificationFactory, ppMappingFactory, ".obda file");
    }

    @Override
    public SQLPPMapping parse(Graph mappingGraph)  {
        throw new IllegalArgumentException("The Ontop native mapping language has no RDF serialization. Passing a RDF graph" +
                "to the OntopNativeMappingParser is thus invalid.");
    }

	private SQLPPMapping load(Reader reader, SpecificationFactory specificationFactory,
                                     SQLPPMappingFactory ppMappingFactory, String fileName)
            throws MappingIOException, InvalidMappingExceptionWithIndicator {

        ImmutableMap.Builder<String, String> prefixes = ImmutableMap.builder();
        ImmutableList.Builder<SQLPPTriplesMap> mappings = ImmutableList.builder();
        List<Indicator> invalidMappingIndicators = new ArrayList<>();

        try (LineNumberReader lineNumberReader = new LineNumberReader(reader)) {
            try {
                String line;
                while ((line = lineNumberReader.readLine()) != null) {
                    //noinspection StatementWithEmptyBody
                    if (line.isEmpty() || line.trim().indexOf(COMMENT_SYMBOL) == 0) {
                        // skip blank lines and comment lines (starting with ;)
                    }
                    else if (line.contains(PREFIX_DECLARATION_TAG)) {
                        prefixes.putAll(readPrefixDeclaration(lineNumberReader));
                    }
                    else if (line.contains(MAPPING_DECLARATION_TAG)) {
                        TargetQueryParser parser = targetQueryParserFactory.createParser(specificationFactory.createPrefixManager(prefixes.build()));
                        mappings.addAll(readMappingDeclaration(lineNumberReader, parser, invalidMappingIndicators));
                    }
                    // These exceptions will be rethrown as IOException and then as MappingIOException
                    else {
                        DEPRECATED_TAGS.stream()
                                .filter(line::contains)
                                .forEach(tag -> { throw new RuntimeException("The tag " + tag
                                        + " is no longer supported. You may safely remove the content from the file."); });

                        if (line.contains(SOURCE_DECLARATION_TAG)) {
                            throw new RuntimeException("Source declaration is not supported anymore (since 3.0). " +
                                    "Please give this information with the Ontop configuration.");
                        }
                        throw new RuntimeException("Unknown syntax: " + line);
                    }
                }
            }
            catch (Exception e) {
                throw new IOException(String.format("ERROR reading %s at line: %d\nMESSAGE: %s", fileName,
                        lineNumberReader.getLineNumber(), e.getMessage()), e);
            }
        }
        catch (IOException e) {
            throw new MappingIOException(e);
        }

        // Throw some validation exceptions
        if (!invalidMappingIndicators.isEmpty()) {
            throw new InvalidMappingExceptionWithIndicator(invalidMappingIndicators);
        }

        PrefixManager prefixManager = specificationFactory.createPrefixManager(prefixes.build());
        return ppMappingFactory.createSQLPreProcessedMapping(mappings.build(), prefixManager);
	}

    /*
     * Helper methods related to load file.
     */

    private static ImmutableMap<String, String> readPrefixDeclaration(BufferedReader reader) throws IOException {
        ImmutableMap.Builder<String, String> prefixes = ImmutableMap.builder();
        String line;
        while (!(line = reader.readLine()).isEmpty()) {
            String[] tokens = line.split("[\t| ]+");
            prefixes.put(tokens[0], tokens[1]);
        }
        return prefixes.build();
    }

    private final class MappingBuilder {
        private final List<Indicator> invalidMappingIndicators;

        private String mappingId = "";
        private final ImmutableList.Builder<String> sourceQuery = ImmutableList.builder();
        private String targetString = null;
        private ImmutableList<TargetAtom> targetQuery = null;
        boolean isMappingValid = true;

        MappingBuilder(List<Indicator> invalidMappingIndicators) {
            this.invalidMappingIndicators = invalidMappingIndicators;
        }

        private void fail(Supplier<Integer> line, Object hint, int reason) {
            invalidMappingIndicators.add(new Indicator(line.get(), hint, reason));
            isMappingValid = false;
        }

        boolean isValid() { return isMappingValid; }

        Optional<OntopNativeSQLPPTriplesMap> build() {
            return (!mappingId.isEmpty() && isMappingValid)
                ? Optional.of(new OntopNativeSQLPPTriplesMap(
                        mappingId,
                        sourceQueryFactory.createSourceQuery(
                                String.join("\n", sourceQuery.build())),
                        targetString,
                        targetQuery))
                : Optional.empty();
        }

        void setMappingId(String value, Supplier<Integer> line) {
            mappingId = value;
            if (mappingId.isEmpty())
                fail(line, MAPPING_ID_LABEL, MAPPING_ID_IS_BLANK);
        }

        void setTarget(String value, TargetQueryParser parser, Supplier<Integer> line) {
            targetString = value;
            if (!targetString.isEmpty()) {
                try {
                    targetQuery = parser.parse(targetString);
                }
                catch (TargetQueryParserException e) {
                    fail(line, new String[]{mappingId, targetString, e.getMessage()}, ERROR_PARSING_TARGET_QUERY);
                }
            }
            else
                fail(line, mappingId, TARGET_QUERY_IS_BLANK);
        }

        void setSource(String value, Supplier<Integer> line) {
            if (!value.isEmpty())
                sourceQuery.add(value);
            else
                fail(line, mappingId, SOURCE_QUERY_IS_BLANK);
        }
    }

    /**
     * @param reader LineNumberReader
     * @param parser TargetQueryParser
     * @param invalidMappingIndicators Read-write list of error indicators.
     * @return SQLPPTriplesMaps of the current source
     * @throws IOException
     */
    private ImmutableList<SQLPPTriplesMap> readMappingDeclaration(LineNumberReader reader,
                                                                TargetQueryParser parser,
                                                                List<Indicator> invalidMappingIndicators)
            throws IOException {

        ImmutableList.Builder<SQLPPTriplesMap> mappings = ImmutableList.builder();
        MappingBuilder current = new MappingBuilder(invalidMappingIndicators);

        String currentLabel = ""; // the reader is working on which label
        String line;
        while ((line = reader.readLine())!= null) {
            if (line.trim().equals(END_COLLECTION_SYMBOL)) {
                current.build().ifPresent(mappings::add);
                return mappings.build();
            }
            else if (line.isEmpty()) {
                current.build().ifPresent(mappings::add);
                current = new MappingBuilder(invalidMappingIndicators);
            }
            // skip the comment lines (which have ; as their first non-space symbol)
            //      and invalid mappings
            else if (line.trim().indexOf(COMMENT_SYMBOL) != 0 && current.isValid()) {
                String[] tokens = line.split("[\t| ]+", 2);
                String value = tokens[tokens.length - 1].trim();
                if (tokens.length > 1) {
                    String label = tokens[0].trim();
                    if (!label.isEmpty())
                        currentLabel = label;
                }

                switch (currentLabel) {
                    case MAPPING_ID_LABEL:
                        current.setMappingId(value, reader::getLineNumber);
                        break;
                    case TARGET_LABEL:
                        current.setTarget(value, parser, reader::getLineNumber);
                        break;
                    case SOURCE_LABEL:
                        current.setSource(value, reader::getLineNumber);
                        break;
                    default:
                        throw new IOException(String.format("Unknown parameter name \"%s\" at line: %d.", tokens[0], reader.getLineNumber()));
                }
            }
        }

        throw new IOException(String.format("End collection symbol %s is missing.", END_COLLECTION_SYMBOL));
    }
}


text:
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved.

/**
* \file playback_device.h
* @brief Describes the \c rs::playback::device class, \c rs::playback::capture_mode
* and \c rs::playback::file_format enums, and \c rs::playback::file_info struct.
*/

#pragma once
#include <librealsense/rs.hpp>

#ifdef WIN32
#ifdef realsense_playback_EXPORTS
#define  DLL_EXPORT __declspec(dllexport)
#else
#define  DLL_EXPORT __declspec(dllimport)
#endif /* realsense_playback_EXPORTS */
#else /* defined (WIN32) */
#define DLL_EXPORT
#endif

namespace rs
{
    namespace playback
    {
        /**
        * @brief Capture modes
        */
		enum capture_mode
        {
            synced  = 1,  /**<  Blocking read until an image from each enabled stream is available */
            asynced = 2   /**<  Images are indicated to the application through camera notifications */
        };

        /**
        * @brief File formats.
        */
		enum file_format
        {
            rs_rssdk_format = 0,  /**<  Windows/Android RSSDK format */
            rs_linux_format = 1   /**<  Linux SDK format */
        };

        /**
        * @brief Describes the record software stack versions and file configuration.
        */
        struct file_info
        {
            int32_t                         version;                     /**<  Linux SDK file version: defines the file format and available data */
            char                            sdk_version[32];             /**<  Linux SDK version that was used to capture the file */
            char                            librealsense_version[32];    /**<  librealsense version that was used to capture the file */
            playback::capture_mode          capture_mode;                /**<  Indicates how the frames were captured by the recording application */
            playback::file_format           type;                        /**<  Indicates the file format, which is derived from the software stack that recorded it: Windows/Android RSSDK or Linux SDK */
        };

        /**
        * @brief Extends librealsense \c rs::device to provide playback capabilities. Commonly used for debug, testing and validation with known input.
        *
        * The playback device reads the device static information, the captured device configuration, streams configuration, and streams data from the file.
        * The playback device can be configured to run as in real time mode, as a live camera, or non-real time mode, as a file camera.
        * Some of the captured data, such as frame metadata fields, reflects the actual behavior at the time of recording, and not the actual playback behavior.
        * Creating the \c rs::playback::device and defining the source file location is done using \c rs::playback::context.
        */
        class DLL_EXPORT device : public rs::device
        {
        public:
            /**
            * @brief Pause streaming and keep the current file read location.
            *
            * While the streaming is paused, the application can access all device queries. Image reading is blocked, and no new sample indication is triggered.
            * File streaming can be resumed after pause by calling device start.
            */
            void pause();

            /**
            * @brief Sets the current file read location by the requested stream type and index.
            *
            * The file read pointer is set according to the time-correlated set of all enabled streams in the playback session.
            * It selects the stream frame with the requested index, while the other streams frames are selected by the nearest capture time.
            * The file read pointer is set to the frame with latest capture time.
            * While the method executes, the streaming state is set to paused. After the method returns, the device returns to the original streaming state.
            * While the method executes, other device operations are unsupported, and have unexpected behavior.
            * @param[in] index Zero-based frame index to set the file read pointer
            * @param[in] stream  Stream type for which the frame is selected
            * @return bool
            * - true     Set succeeded and frame data is available
            * - false    Failed to set the file read pointer to the requested index
            */
            bool set_frame_by_index(int index, rs::stream stream);

            /**
            * @brief Sets the current file read location to the frame according to the requested timestamp.
            *
            * The file read pointer location is set according to the time correlated set of all enabled streams in the playback session.
            * It locates the first frame of any enabled stream, with capture time larger than the requested timestamp.
            * The other streams frames are selected by the nearest capture time.
            * The file read pointer will be set to the frame with latest capture time.
            * While the method executes, the streaming state is set to paused. After the method returns, the device returns to the original streaming state.
            * While the method executes, other device operations are unsupported, and have unexpected behavior.
            * @param[in] timestamp  Time, in milliseconds
            * @return
            * - true     Set succeeded and frame data is available
            * - false    Failed to set the file read pointer to the requested index
            */
            bool set_frame_by_timestamp(uint64_t timestamp);

            /**
            * @brief Gets the index of current frame.
            *
            * This method can be called only if capture and playback mode is sync, or after \c set_frame_by_index() or \c set_frame_by_timestamp() was called.
            * This method is not supported for async playback mode.
            * When the method is supported, it can be called in any streaming state.
            * @param[in] stream  Stream type for which the frame is queried
            * @return int Frame index
            */
            int get_frame_index(rs::stream stream);

            /**
            * @brief Sets the playback mode to real time or non real time
            *
            * The real time mode selection defines the rate of samples delivery to the application.
            * Real time mode imitates the real time behavior of the file record session, in which the frames are provided to the application according to the actual time it was captured.
            * In this mode frame drops might occur according to the playback runtime behavior - application or system latency can cause the device to skip recorded frames.
            * Non-real time mode ignores the actual capture time and delivers all frames without drops. The playback time and frame rate depends only on the application
			* and system behavior.
            * The default mode is real time.
            * This mode is designed for a single consumer, as the next sample delivery is blocked by current sample processing, faster or slower than the original camera FPS.
            * @param[in] real time Requested state
            */
            void set_real_time(bool realtime);

            /**
            * @brief Indicates the playback real time mode
            *
            * For more details, see the \c rs::playback::device::set_real_time() method.
            * @return bool Real time state
            */
            bool is_real_time();

            /**
            * @brief Gets the total frame count of the requested stream captured in the file.
            *
            * @param[in] stream  Stream type for which the frame count is queried
            * @return int        Frame count
            */
            int get_frame_count(rs::stream stream);

            /**
            * @brief Gets the total frame count of the stream with the lowest frame count captured in the file.
            *
            * @return int Frame count
            */
            int get_frame_count();

            /**
            * @brief Provides information of the software stack, with which the file was captured, and the way it was captured.
            *
            * Those parameters may influence the way the file can be played.
            * @return core::file_info File info.
            */
            file_info get_file_info();
        };
    }
}


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

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseCommonTestingUtility;
import org.apache.hadoop.hbase.procedure2.ProcedureTestingUtility.NoopProcedure;
import org.apache.hadoop.hbase.procedure2.store.ProcedureStore;
import org.apache.hadoop.hbase.testclassification.MasterTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hbase.thirdparty.com.google.protobuf.Int32Value;

import org.apache.hadoop.hbase.shaded.protobuf.generated.ProcedureProtos.ProcedureState;

@Category({MasterTests.class, MediumTests.class})
public class TestProcedureEvents {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestProcedureEvents.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestProcedureEvents.class);

  private TestProcEnv procEnv;
  private ProcedureStore procStore;
  private ProcedureExecutor<TestProcEnv> procExecutor;

  private HBaseCommonTestingUtility htu;
  private FileSystem fs;
  private Path logDir;

  @Before
  public void setUp() throws IOException {
    htu = new HBaseCommonTestingUtility();
    Path testDir = htu.getDataTestDir();
    fs = testDir.getFileSystem(htu.getConfiguration());
    logDir = new Path(testDir, "proc-logs");

    procEnv = new TestProcEnv();
    procStore = ProcedureTestingUtility.createWalStore(htu.getConfiguration(), logDir);
    procExecutor = new ProcedureExecutor<>(htu.getConfiguration(), procEnv, procStore);
    procStore.start(1);
    ProcedureTestingUtility.initAndStartWorkers(procExecutor, 1, true);
  }

  @After
  public void tearDown() throws IOException {
    procExecutor.stop();
    procStore.stop(false);
    procExecutor.join();
    fs.delete(logDir, true);
  }

  /**
   * Tests being able to suspend a Procedure for N timeouts and then failing.s
   * Resets the timeout after each elapses. See {@link TestTimeoutEventProcedure} for example
   * of how to do this sort of trickery with the ProcedureExecutor; i.e. suspend for a while,
   * check for a condition and if not set, suspend again, etc., ultimately failing or succeeding
   * eventually.
   */
  @Test
  public void testTimeoutEventProcedure() throws Exception {
    final int NTIMEOUTS = 5;

    TestTimeoutEventProcedure proc = new TestTimeoutEventProcedure(500, NTIMEOUTS);
    procExecutor.submitProcedure(proc);

    ProcedureTestingUtility.waitProcedure(procExecutor, proc.getProcId());
    ProcedureTestingUtility.assertIsAbortException(procExecutor.getResult(proc.getProcId()));
    assertEquals(NTIMEOUTS + 1, proc.getTimeoutsCount());
  }

  @Test
  public void testTimeoutEventProcedureDoubleExecution() throws Exception {
    testTimeoutEventProcedureDoubleExecution(false);
  }

  @Test
  public void testTimeoutEventProcedureDoubleExecutionKillIfSuspended() throws Exception {
    testTimeoutEventProcedureDoubleExecution(true);
  }

  private void testTimeoutEventProcedureDoubleExecution(final boolean killIfSuspended)
      throws Exception {
    TestTimeoutEventProcedure proc = new TestTimeoutEventProcedure(1000, 3);
    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExecutor, true);
    ProcedureTestingUtility.setKillIfSuspended(procExecutor, killIfSuspended);
    long procId = procExecutor.submitProcedure(proc);
    ProcedureTestingUtility.testRecoveryAndDoubleExecution(procExecutor, procId, true);
    ProcedureTestingUtility.assertIsAbortException(procExecutor.getResult(proc.getProcId()));
  }

  /**
   * This Event+Procedure exhibits following behavior:
   *

   *
On procedure execute()
   *

   *
If had enough timeouts, abort the procedure. Else....

   *
Suspend the event and add self to its suspend queue

   *
Go into waiting state

   *

   *

   *

   *     On waiting timeout
   *

   *
Wake the event (which adds this procedure back into scheduler queue), and set own's
   *       state to RUNNABLE (so can be executed again).

   *

   *

   *

   */
  public static class TestTimeoutEventProcedure extends NoopProcedure<TestProcEnv> {
    private final ProcedureEvent event = new ProcedureEvent("timeout-event");

    private final AtomicInteger ntimeouts = new AtomicInteger(0);
    private int maxTimeouts = 1;

    public TestTimeoutEventProcedure() {}

    public TestTimeoutEventProcedure(final int timeoutMsec, final int maxTimeouts) {
      this.maxTimeouts = maxTimeouts;
      setTimeout(timeoutMsec);
    }

    public int getTimeoutsCount() {
      return ntimeouts.get();
    }

    @Override
    protected Procedure[] execute(final TestProcEnv env) throws ProcedureSuspendedException {
      LOG.info("EXECUTE " + this + " ntimeouts=" + ntimeouts);
      if (ntimeouts.get() > maxTimeouts) {
        setAbortFailure("test", "give up after " + ntimeouts.get());
        return null;
      }

      event.suspend();
      if (event.suspendIfNotReady(this)) {
        setState(ProcedureState.WAITING_TIMEOUT);
        throw new ProcedureSuspendedException();
      }

      return null;
    }

    @Override
    protected synchronized boolean setTimeoutFailure(final TestProcEnv env) {
      int n = ntimeouts.incrementAndGet();
      LOG.info("HANDLE TIMEOUT " + this + " ntimeouts=" + n);
      setState(ProcedureState.RUNNABLE);
      event.wake((AbstractProcedureScheduler) env.getProcedureScheduler());
      return false;
    }

    @Override
    protected void afterReplay(final TestProcEnv env) {
      if (getState() == ProcedureState.WAITING_TIMEOUT) {
        event.suspend();
        event.suspendIfNotReady(this);
      }
    }

    @Override
    protected void serializeStateData(ProcedureStateSerializer serializer)
        throws IOException {
      Int32Value.Builder ntimeoutsBuilder = Int32Value.newBuilder().setValue(ntimeouts.get());
      serializer.serialize(ntimeoutsBuilder.build());

      Int32Value.Builder maxTimeoutsBuilder = Int32Value.newBuilder().setValue(maxTimeouts);
      serializer.serialize(maxTimeoutsBuilder.build());
    }

    @Override
    protected void deserializeStateData(ProcedureStateSerializer serializer)
        throws IOException {
      Int32Value ntimeoutsValue = serializer.deserialize(Int32Value.class);
      ntimeouts.set(ntimeoutsValue.getValue());

      Int32Value maxTimeoutsValue = serializer.deserialize(Int32Value.class);
      maxTimeouts = maxTimeoutsValue.getValue();
    }
  }

  private class TestProcEnv {
    public ProcedureScheduler getProcedureScheduler() {
      return procExecutor.getScheduler();
    }
  }
}


text:
const addon = require('./build/Release/async');
console.log(addon.byeASync());
console.log(addon.byeSync());


text:
package br.com.tupinikimtecnologia.constants;

/**
 * Created by felipe on 14/08/15.
 */
public class GeralConstants {

    public static final String HOWTO_URL = "https://github.com/feliperce/httpflooder/wiki";

    public static final class Db{
        public static final String DB_NAME = "httpflooder.db";
        public static final String DB_DIR = System.getProperty("user.home")+"/HttpFlooder/";
    }

    public static final class RandomData{
        public static final String USER_ANGET[] = {
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
                "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0",
                "Mozilla/5.0 (X11; Linux) KHTML/4.9.1 (like Gecko) Konqueror/4.9",
                "Mozilla/5.0 (X11; U; Linux i686; fr-fr) AppleWebKit/525.1+ (KHTML, like Gecko, Safari/525.1+) midori/1.19",
                "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16",
                "Galaxy/1.0 [en] (Mac OS X 10.5.6; U; en)",
                "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
                "Googlebot/2.1 (+http://www.googlebot.com/bot.html)",
                "Googlebot-Image/1.0",
                "iaskspider/2.0(+http://iask.com/help/help_index.html)",
                "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
                "Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)"
        };

        public static final String RAND_NAME_FULL = "{%full_name}";
        public static final String RAND_NAME_FIRST = "{%first_name}";
        public static final String RAND_NAME_LAST = "{%last_name}";
        public static final String RAND_AGE = "{%age}";
        public static final String RAND_EMAIL = "{%email}";
        public static final String RAND_ADDRESS = "{%address}";
        public static final String RAND_CITY = "{%city}";
        public static final String RAND_COUNTRY = "{%country}";
        public static final String RAND_PASSWORD = "{%password}";
        public static final String RAND_LATITUDE = "{%latitude}";
        public static final String RAND_LONGITUDE = "{%longitude}";
        public static final String RAND_SENTENCE = "{%sentence}";

    }

    public static final class Debug{
        public static final boolean SQL_SHOW = false;
        public static final boolean HTTP_REQUEST_SHOW = false;
    }
}


text:
import itertools, operator
from .data import *

import shapely, shapely.ops
from shapely.geometry import asShape as geoj2shapely
from shapely.geometry import mapping as shapely2geoj
from shapely.prepared import prep as supershapely

# Distinction between cut and glue operations
# cut: ...
# glue: ...

# Or how about this:
# spatial link: join attribs, option to use match geometry (ala geoproc)
# spatial glue: dissolve
# spatial cut: difference

# Clipping to region of interest (no transfer of values)
# should belongs in management.py
# maybe rename to crop?
# and allow any nr of datainput, only keeping common to all

def vector_clip_overlap(data, clip):
    pass

def vector_clip_difference(*datalist):
    pass

def vector_clip_symmetrical_difference(*datalist):
    pass

# Clip (with transfer of values)???
# ala Arcgis intersect/union/diff
# essentially same as clipping all layers, then spajoin together results
# so maybe unnecessary?

##def vector_intersect(*datalist):
##    # detect lowest dimension geotype
##    lowestgeotype = "Polygon"
##    for data in datalist:
##        if "LineString" in data.type:
##            lowestgeotype = "LineString"
##        elif "Point" in data.type:
##            lowestgeotype = "Point"
##            break # lowest possible
##    # create spatial index for all data
##    for data in datalist:
##        data.create_spatial_index()
##    # get first data
##    data = datalist[0]
##    # create new
##    new = GeoTable()
##    new.fields = list(data.fields)
##    # intersect each feat in first with all others
##    def process_intersection(intersection):
##        if lowestgeotype in intersection.type:
##            geoj = shapely2geoj(intersection)
##            new.add_feature(feat.row, geoj)
##    for feat in data:
##        print feat.id
##        geom = geoj2shapely(feat.geometry)
##        for otherfeat in datalist[1].quick_overlap(feat.bbox):
##            othergeom = geoj2shapely(otherfeat.geometry)
##            intersection = geom.intersection(othergeom)
##            if not intersection.is_empty:
##                if intersection.type == "GeometryCollection":
##                    for subintsec in intersection:
##                        process_intersection(subintsec)
##                else:
##                    process_intersection(intersection)
##    return new

# Overlay Analysis (transfer of values, but no clip)

def vector_spatialjoin(data1, data2, joincondition, radius=None):
    """Possible joinconditions:
        intersects, within, contains, crosses, touches, equals
       Also:
        distance
    """
    # create spatial index
    if not hasattr(data1, "spindex"): data1.create_spatial_index()
    if not hasattr(data2, "spindex"): data2.create_spatial_index()
    # create new
    new = GeoTable()
    new.fields = list(data1.fields)
    new.fields.extend(data2.fields)
    # intersect each feat in first with all others
    if joincondition in ("distance",):
        new.fields.append("DISTANCE")
        if joincondition == "distance" and radius is None: raise Exception("radius arg must be set when using distance mode")
        maxnum = 9223372036854775807
        for feat in data1.quick_nearest(data2.bbox, n=maxnum):
            geom = geoj2shapely(feat.geometry)
            matchtest = getattr(geom, "distance")
            for otherfeat in data2.quick_nearest(feat.bbox, n=maxnum):
                othergeom = geoj2shapely(otherfeat.geometry)
                match = matchtest(othergeom)
                if match <= radius:
                    joined = list(feat.row)
                    joined.extend(otherfeat.row)
                    joined.append(match)
                    print "match", match
                    new.add_feature(joined, feat.geometry)
    else:
        for feat in data1.quick_overlap(data2.bbox):
            geom = geoj2shapely(feat.geometry)
            matchtest = getattr(geom, joincondition)
            for otherfeat in data2.quick_overlap(feat.bbox):
                othergeom = geoj2shapely(otherfeat.geometry)
                match = matchtest(othergeom)
                if match:
                    joined = list(feat.row)
                    joined.extend(otherfeat.row)
                    print "match", len(joined)
                    new.add_feature(joined, feat.geometry)

    return new

def overlap_summary(groupbydata, valuedata, fieldmapping=[]):
    # prep
    data1,data2 = groupbydata,valuedata
    if fieldmapping: aggfields,aggtypes = zip(*fieldmapping)
    aggfunctions = dict([("count",len),
                         ("sum",sum),
                         ("max",max),
                         ("min",min),
                         ("average",lambda seq: sum(seq)/float(len(seq)) ) ])

    # create spatial index
    if not hasattr(data1, "spindex"): data1.create_spatial_index()
    if not hasattr(data2, "spindex"): data2.create_spatial_index()

    # create new
    new = GeoTable()
    new.fields = list(data1.fields)
    if fieldmapping:
        for aggfield,aggtype in fieldmapping:
            new.fields.append(aggfield)

    # for each groupby feature
    for i,feat in enumerate(data1.quick_overlap(data2.bbox)):
        geom = geoj2shapely(feat.geometry)
        geom = supershapely(geom)
        matches = []

        # get all value features that intersect
        for otherfeat in data2.quick_overlap(feat.bbox):
            othergeom = geoj2shapely(otherfeat.geometry)
            if geom.intersects(othergeom):
                matches.append(otherfeat)

        # make newrow from original row
        newrow = list(feat.row)

        # if any matches
        if matches:
            def make_number(value):
                try: return float(value)
                except: return None

            # add summary values to newrow based on fieldmapping
            for aggfield,aggtype in fieldmapping:
                values = [otherfeat[aggfield] for otherfeat in matches]
                if aggtype in ("sum","max","min","average"):
                    # only consider number values if numeric stats
                    values = [make_number(value) for value in values if make_number(value) != None]
                aggregatefunc = aggfunctions[aggtype]
                summaryvalue = aggregatefunc(values)
                newrow.append(summaryvalue)

        # otherwise, add empty values
        else:
            newrow.extend(("" for _ in fieldmapping))

        # write feature to output
        new.add_feature(newrow, feat.geometry)

    return new

# Distance Analysis

def vector_nearest(data, otherdata, search_radius=None, n=1):
    pass

def vector_buffer(data, dist_expression):
    # buffer and change each geojson dict in-place
    new = GeoTable()
    new.fields = list(data.fields)
    for feat in data:
        geom = geoj2shapely(feat.geometry)
        dist = eval(dist_expression)
        buffered = geom.buffer(dist)
        if not buffered.is_empty:
            geoj = shapely2geoj(buffered)
            geoj["type"] = buffered.type
            new.add_feature(feat.row, geoj)
    # change data type to polygon
    new.type = "Polygon"
    return new


text:
package com.guardtime.ksi.unisignature.inmemory;

import com.guardtime.ksi.hashing.DataHash;
import com.guardtime.ksi.unisignature.ChainResult;

/**
 * Aggregation hash chain hash calculation result
 */
final class InMemoryChainResult implements ChainResult {

    private final DataHash lastHash;
    private final long level;

    /**
     * Create hash chain result.
     *
     * @param lastHash
     *         last chain
     * @param level
     *         chain result level
     */
    public InMemoryChainResult(DataHash lastHash, long level) {
        this.lastHash = lastHash;
        this.level = level;
    }

    /**
     * @return level
     */
    public final long getLevel() {
        return level;
    }

    /**
     * @return output hash
     */
    public final DataHash getOutputHash() {
        return lastHash;
    }

    @Override
    public String toString() {
        return lastHash + ", level=" + level;
    }
}


text:
"""The Logistic distribution class."""

# Dependency imports
import numpy as np
import tensorflow.compat.v2 as tf

from tensorflow_probability.python.bijectors import identity as identity_bijector
from tensorflow_probability.python.bijectors import softplus as softplus_bijector
from tensorflow_probability.python.distributions import distribution
from tensorflow_probability.python.internal import assert_util
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import parameter_properties
from tensorflow_probability.python.internal import prefer_static as ps
from tensorflow_probability.python.internal import reparameterization
from tensorflow_probability.python.internal import samplers
from tensorflow_probability.python.internal import tensor_util

class Logistic(distribution.AutoCompositeTensorDistribution):
  """The Logistic distribution with location `loc` and `scale` parameters.

  #### Mathematical details

  The cumulative density function of this distribution is:

  ```none
  cdf(x; mu, sigma) = 1 / (1 + exp(-(x - mu) / sigma))
  ```

  where `loc = mu` and `scale = sigma`.

  The Logistic distribution is a member of the [location-scale family](
  https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be
  constructed as,

  ```none
  X ~ Logistic(loc=0, scale=1)
  Y = loc + scale * X
  ```

  #### Examples

  Examples of initialization of one or a batch of distributions.

  ```python
  tfd = tfp.distributions

  # Define a single scalar Logistic distribution.
  dist = tfd.Logistic(loc=0., scale=3.)

  # Evaluate the cdf at 1, returning a scalar.
  dist.cdf(1.)

  # Define a batch of two scalar valued Logistics.
  # The first has mean 1 and scale 11, the second 2 and 22.
  dist = tfd.Logistic(loc=[1, 2.], scale=[11, 22.])

  # Evaluate the pdf of the first distribution on 0, and the second on 1.5,
  # returning a length two tensor.
  dist.prob([0, 1.5])

  # Get 3 samples, returning a 3 x 2 tensor.
  dist.sample([3])

  # Arguments are broadcast when possible.
  # Define a batch of two scalar valued Logistics.
  # Both have mean 1, but different scales.
  dist = tfd.Logistic(loc=1., scale=[11, 22.])

  # Evaluate the pdf of both distributions on the same point, 3.0,
  # returning a length 2 tensor.
  dist.prob(3.0)
  ```

  """

  def __init__(self,
               loc,
               scale,
               validate_args=False,
               allow_nan_stats=True,
               name='Logistic'):
    """Construct Logistic distributions with mean and scale `loc` and `scale`.

    The parameters `loc` and `scale` must be shaped in a way that supports
    broadcasting (e.g. `loc + scale` is a valid operation).

    Args:
      loc: Floating point tensor, the means of the distribution(s).
      scale: Floating point tensor, the scales of the distribution(s). Must
        contain only positive values.
      validate_args: Python `bool`, default `False`. When `True` distribution
        parameters are checked for validity despite possibly degrading runtime
        performance. When `False` invalid inputs may silently render incorrect
        outputs.
      allow_nan_stats: Python `bool`, default `True`. When `True`, statistics
        (e.g., mean, mode, variance) use the value '`NaN`' to indicate the
        result is undefined. When `False`, an exception is raised if one or
        more of the statistic's batch members are undefined.
      name: The name to give Ops created by the initializer.

    Raises:
      TypeError: if loc and scale are different dtypes.
    """
    parameters = dict(locals())
    with tf.name_scope(name) as name:
      dtype = dtype_util.common_dtype([loc, scale], dtype_hint=tf.float32)
      self._loc = tensor_util.convert_nonref_to_tensor(
          loc, name='loc', dtype=dtype)
      self._scale = tensor_util.convert_nonref_to_tensor(
          scale, name='scale', dtype=dtype)
      super(Logistic, self).__init__(
          dtype=self._scale.dtype,
          reparameterization_type=reparameterization.FULLY_REPARAMETERIZED,
          validate_args=validate_args,
          allow_nan_stats=allow_nan_stats,
          parameters=parameters,
          name=name)

  @classmethod
  def _parameter_properties(cls, dtype, num_classes=None):
    # pylint: disable=g-long-lambda
    return dict(
        loc=parameter_properties.ParameterProperties(),
        scale=parameter_properties.ParameterProperties(
            default_constraining_bijector_fn=(
                lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype)))))
    # pylint: enable=g-long-lambda

  @property
  def loc(self):
    """Distribution parameter for the location."""
    return self._loc

  @property
  def scale(self):
    """Distribution parameter for scale."""
    return self._scale

  def _event_shape_tensor(self):
    return tf.constant([], dtype=tf.int32)

  def _event_shape(self):
    return tf.TensorShape([])

  def _sample_n(self, n, seed=None):
    loc = tf.convert_to_tensor(self.loc)
    scale = tf.convert_to_tensor(self.scale)
    shape = ps.concat([[n], self._batch_shape_tensor(loc=loc, scale=scale)], 0)
    # Uniform variates must be sampled from the open-interval `(0, 1)` rather
    # than `[0, 1)`. To do so, we use
    # `np.finfo(dtype_util.as_numpy_dtype(self.dtype)).tiny` because it is the
    # smallest, positive, 'normal' number. A 'normal' number is such that the
    # mantissa has an implicit leading 1. Normal, positive numbers x, y have the
    # reasonable property that, `x + y >= max(x, y)`. In this case, a subnormal
    # number (i.e., np.nextafter) can cause us to sample 0.
    uniform = samplers.uniform(
        shape=shape,
        minval=np.finfo(dtype_util.as_numpy_dtype(self.dtype)).tiny,
        maxval=1.,
        dtype=self.dtype,
        seed=seed)
    sampled = tf.math.log(uniform) - tf.math.log1p(-uniform)
    return sampled * scale + loc

  def _log_prob(self, x):
    loc = tf.convert_to_tensor(self.loc)
    scale = tf.convert_to_tensor(self.scale)
    z = (x - loc) / scale
    return -z - 2. * tf.math.softplus(-z) - tf.math.log(scale)

  def _log_cdf(self, x):
    return -tf.math.softplus(-self._z(x))

  def _cdf(self, x):
    return tf.sigmoid(self._z(x))

  def _log_survival_function(self, x):
    return -tf.math.softplus(self._z(x))

  def _survival_function(self, x):
    return tf.sigmoid(-self._z(x))

  def _entropy(self):
    scale = tf.convert_to_tensor(self.scale)
    return tf.broadcast_to(2. + tf.math.log(scale),
                           self._batch_shape_tensor(scale=scale))

  def _mean(self):
    loc = tf.convert_to_tensor(self.loc)
    return tf.broadcast_to(loc, self._batch_shape_tensor(loc=loc))

  def _stddev(self):
    scale = tf.convert_to_tensor(self.scale)
    return tf.broadcast_to(
        scale * tf.constant(np.pi / np.sqrt(3), dtype=scale.dtype),
        self._batch_shape_tensor(scale=scale))

  def _mode(self):
    return self._mean()

  def _z(self, x):
    """Standardize input `x` to a unit logistic."""
    with tf.name_scope('standardize'):
      return (x - self.loc) / self.scale

  def _quantile(self, x):
    return self.loc + self.scale * (tf.math.log(x) - tf.math.log1p(-x))

  def _default_event_space_bijector(self):
    return identity_bijector.Identity(validate_args=self.validate_args)

  def _parameter_control_dependencies(self, is_init):
    if is_init:
      dtype_util.assert_same_float_dtype([self.loc, self.scale])
    if not self.validate_args:
      return []
    assertions = []
    if is_init != tensor_util.is_ref(self._scale):
      assertions.append(assert_util.assert_positive(
          self._scale, message='Argument `scale` must be positive.'))
    return assertions


text:
.. -*- coding: utf-8 -*-
.. URL: https://docs.docker.com/compose/reference/kill/
.. SOURCE: https://github.com/docker/compose/blob/master/docs/reference/kill.md
   doc version: 1.13
      https://github.com/docker/compose/commits/master/docs/reference/kill.md
   doc version: 20.10
      https://github.com/docker/docker.github.io/blob/master/compose/reference/kill.md
.. check date: 2022/04/08
.. Commits on Jan 28, 2022 b6b19516d0feacd798b485615ebfee410d9b6f86
.. -------------------------------------------------------------------

.. docker-compose kill
.. _docker-compose-kill:

=======================================
docker-compose kill
=======================================

.. code-block:: bash

   使い方: docker-compose kill [オプション] [サービス...]

   オプション:
   -s SIGNAL         コンテナに送信するシグナル。デフォルトのシグナルは SIGKILL

.. Forces running containers to stop by sending a SIGKILL signal. Optionally the signal can be passed, for example:

``SIGKILL`` シグナルを送信し、実行中のコンテナを強制停止します。次のように、オプションでシグナルを渡すこともできます。

.. code-block:: bash

   $ docker-compose kill -s SIGINT

.. seealso::

   docker-compose kill
      https://docs.docker.com/compose/reference/kill/


text:
package logbook.bean;

import java.io.Serializable;
import java.util.List;

import javax.json.JsonObject;

import logbook.internal.JsonHelper;
import logbook.internal.SlotItemType;
import lombok.Data;

/**
 * 装備定義
 *
 */
@Data
public class SlotitemMst implements Serializable {

    private static final long serialVersionUID = 383813721548687786L;

    /** api_id */
    private Integer id;

    /** api_sortno */
    private Integer sortno;

    /** api_name */
    private String name;

    /** api_type */
    private List<Integer> type;

    /** api_taik(耐久) */
    private Integer taik;

    /** api_souk(装甲) */
    private Integer souk;

    /** api_houg(火力) */
    private Integer houg;

    /** api_raig(雷装) */
    private Integer raig;

    /** api_soku(速力) */
    private Integer soku;

    /** api_baku(爆装) */
    private Integer baku;

    /** api_tyku(対空) */
    private Integer tyku;

    /** api_tais(対潜) */
    private Integer tais;

    /** api_atap(?) */
    private Integer atap;

    /** api_houm(命中/対爆) */
    private Integer houm;

    /** api_raim(雷撃命中) */
    private Integer raim;

    /** api_houk(回避/迎撃) */
    private Integer houk;

    /** api_raik(雷撃回避) */
    private Integer raik;

    /** api_bakk(爆撃回避) */
    private Integer bakk;

    /** api_saku(索敵) */
    private Integer saku;

    /** api_sakb(索敵妨害) */
    private Integer sakb;

    /** api_luck(運) */
    private Integer luck;

    /** api_leng(射程) */
    private Integer leng;

    /** api_rare(レアリティ) */
    private Integer rare;

    /** api_cost(配置コスト) */
    private Integer cost;

    /** api_distance(航続距離) */
    private Integer distance;

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

    /**
     * この装備定義が指定された装備種定数であるかを返します。
     * @param itemType 装備種定数
     * @return この装備定義が指定された装備種定数である場合true
     */
    public boolean is(SlotItemType itemType) {
        if (this.getType() == null)
            return false;
        return itemType.getType() == this.getType().get(2);
    }

    /**
     * この装備定義が指定されたいずれかの装備種定数であるかを返します。
     * @param itemType1 装備種定数
     * @param itemType2 装備種定数
     * @return この装備定義が指定されたいずれかの装備種定数である場合true
     */
    public boolean is(SlotItemType itemType1, SlotItemType itemType2) {
        if (this.getType() == null)
            return false;
        int type2 = this.getType().get(2);
        return itemType1.getType() == type2 || itemType2.getType() == type2;
    }

    /**
     * この装備定義が指定されたいずれかの装備種定数であるかを返します。
     * @param itemTypes 装備種定数
     * @return この装備定義が指定されたいずれかの装備種定数である場合true
     */
    public boolean is(SlotItemType... itemTypes) {
        if (this.getType() == null)
            return false;
        int type2 = this.getType().get(2);
        for (SlotItemType itemType : itemTypes) {
            if (itemType.getType() == type2) {
                return true;
            }
        }
        return false;
    }

    /**
     * この装備定義から{@link SlotItemType}を返します。
     *
     * @return {@link SlotItemType}
     */
    public SlotItemType asSlotItemType() {
        return SlotItemType.toSlotItemType(this);
    }

    /**
     * JsonObjectから{@link SlotitemMst}を構築します
     *
     * @param json JsonObject
     * @return {@link SlotitemMst}
     */
    public static SlotitemMst toSlotitem(JsonObject json) {
        SlotitemMst bean = new SlotitemMst();
        JsonHelper.bind(json)
                .setInteger("api_id", bean::setId)
                .setInteger("api_sortno", bean::setSortno)
                .setString("api_name", bean::setName)
                .setIntegerList("api_type", bean::setType)
                .setInteger("api_taik", bean::setTaik)
                .setInteger("api_souk", bean::setSouk)
                .setInteger("api_houg", bean::setHoug)
                .setInteger("api_raig", bean::setRaig)
                .setInteger("api_soku", bean::setSoku)
                .setInteger("api_baku", bean::setBaku)
                .setInteger("api_tyku", bean::setTyku)
                .setInteger("api_tais", bean::setTais)
                .setInteger("api_atap", bean::setAtap)
                .setInteger("api_houm", bean::setHoum)
                .setInteger("api_raim", bean::setRaim)
                .setInteger("api_houk", bean::setHouk)
                .setInteger("api_raik", bean::setRaik)
                .setInteger("api_bakk", bean::setBakk)
                .setInteger("api_saku", bean::setSaku)
                .setInteger("api_sakb", bean::setSakb)
                .setInteger("api_luck", bean::setLuck)
                .setInteger("api_leng", bean::setLeng)
                .setInteger("api_rare", bean::setRare)
                .setInteger("api_cost", bean::setCost)
                .setInteger("api_distance", bean::setDistance);
        return bean;
    }
}


text:
#ifndef PARSER_H
#define	PARSER_H

#include <sys/types.h>

#define ERROR_UNEXPECTED_EOD 1
#define ERROR_UNEXPECTED_TOKEN 2
#define ERROR_STRING_KEY_EXPECTED 3
#define ERROR_COLON_EXPECTED 4

struct ParserHandlers {
	int (*onBool)(void *arg, char bool);
	void *onBoolArg;

	int (*onNull)(void *arg);
	void *onNullArg;

	int (*onNumber)(void *arg, const unsigned char *number, size_t len);
	void *onNumberArg;

	int (*onString)(void *arg, const unsigned char *string, size_t len);
	void *onStringArg;

	int (*onListStart)(void *arg);
	void *onListStartArg;

	int (*onListEnd)(void *arg);
	void *onListEndArg;

	int (*onMapStart)(void *arg);
	void *onMapStartArg;

	int (*onMapKey)(void *arg, const unsigned char *key, size_t len);
	void *onMapKeyArg;

	int (*onMapEnd)(void *arg);
	void *onMapEndArg;
};

struct Parser {
	const unsigned char *start;
	const unsigned char *end;

	const unsigned char *cur;

	struct ParserHandlers handlers;
};

void parser_init(struct Parser *parser);
int parser_parse(struct Parser *parser, unsigned char *buf, size_t len);

#endif	/* PARSER_H */


text:
title: OCR
layout: post
---

How has OCR improved since the first version?

- Accuracy
- Cost
- Speed
- Training

# Tesseract

# Sparse Convolutional Neural Networks (CNNs)

# Web Services

# GPU

## Cloud

## Local

# References

1. [Tesseract OCR](https://github.com/tesseract-ocr/tesseract)
1. [Optical Character Recognition with CUDA C](http://www.cs.uky.edu/~raphael/grad/keepingCurrent/reed-ocr.pdf)


text:
<?php

declare(strict_types = 1);
namespace UaComparator\Module\Mapper;

use BrowserDetector\Loader\NotFoundException;
use Psr\Cache\CacheItemPoolInterface;
use UaDataMapper\InputMapper;
use UaResult\Browser\Browser;
use UaResult\Company\CompanyLoader;
use UaResult\Device\Device;
use UaResult\Engine\Engine;
use UaResult\Os\Os;
use UaResult\Result\Result;
use Wurfl\Request\GenericRequestFactory;

/**
 * Browscap.ini parsing class with caching and update capabilities
 *
 * @category  UaComparator
 *
 * @author    Thomas Mueller <mimmi20@live.de>
 * @copyright 2015 Thomas Mueller
 * @license   http://www.opensource.org/licenses/MIT MIT License
 */
class Browscap implements MapperInterface
{
    /**
     * @var \UaDataMapper\InputMapper|null
     */
    private $mapper = null;

    /**
     * @var \Psr\Cache\CacheItemPoolInterface|null
     */
    private $cache = null;

    /**
     * @param \UaDataMapper\InputMapper         $mapper
     * @param \Psr\Cache\CacheItemPoolInterface $cache
     */
    public function __construct(InputMapper $mapper, CacheItemPoolInterface $cache)
    {
        $this->mapper = $mapper;
        $this->cache  = $cache;
    }

    /**
     * Gets the information about the browser by User Agent
     *
     * @param \stdClass $parserResult
     * @param string    $agent
     *
     * @return \UaResult\Result\Result the object containing the browsers details
     */
    public function map($parserResult, $agent)
    {
        if (!isset($parserResult->browser)) {
            $browser = new Browser(null, null, null);
        } else {
            $browserName    = $this->mapper->mapBrowserName($parserResult->browser);
            $browserVersion = $this->mapper->mapBrowserVersion(
                $parserResult->version,
                $browserName
            );

            if (!empty($parserResult->browser_type)) {
                $browserType = $parserResult->browser_type;
            } else {
                $browserType = null;
            }

            //if (!empty($parserResult->browser_modus) && 'unknown' !== $parserResult->browser_modus) {
            //    $browserModus = $parserResult->browser_modus;
            //} else {
            //    $browserModus = null;
            //}

            $browserManufacturer = null;
            $browserMakerKey     = $this->mapper->mapBrowserMaker($parserResult->browser_maker, $browserName);
            try {
                $browserManufacturer = (new CompanyLoader($this->cache))->load($browserMakerKey);
            } catch (NotFoundException $e) {
                //$this->logger->info($e);
            }

            $browser = new Browser(
                $browserName,
                $browserManufacturer,
                $browserVersion,
                $this->mapper->mapBrowserType($this->cache, $browserType),
                $parserResult->browser_bits
            );
        }

        if (!isset($parserResult->device_code_name)) {
            $device = new Device(null, null, null, null);
        } else {
            $deviceName = $this->mapper->mapDeviceName($parserResult->device_code_name);

            $deviceManufacturer = null;
            $deviceMakerKey     = $this->mapper->mapDeviceMaker($parserResult->device_maker, $deviceName);
            try {
                $deviceManufacturer = (new CompanyLoader($this->cache))->load($deviceMakerKey);
            } catch (NotFoundException $e) {
                //$this->logger->info($e);
            }

            $deviceBrand    = null;
            $deviceBrandKey = $this->mapper->mapDeviceBrandName($parserResult->device_brand_name, $deviceName);
            try {
                $deviceBrand = (new CompanyLoader($this->cache))->load($deviceBrandKey);
            } catch (NotFoundException $e) {
                //$this->logger->info($e);
            }

            $device = new Device(
                $deviceName,
                $this->mapper->mapDeviceMarketingName($parserResult->device_name, $deviceName),
                $deviceManufacturer,
                $deviceBrand,
                $this->mapper->mapDeviceType($this->cache, $parserResult->device_type),
                $parserResult->device_pointing_method
            );
        }

        if (!isset($parserResult->platform)) {
            $os = new Os(null, null);
        } else {
            $platform        = $this->mapper->mapOsName($parserResult->platform);
            $platformVersion = $this->mapper->mapOsVersion($parserResult->platform_version, $parserResult->platform);

            $osManufacturer = null;
            $osMakerKey     = $this->mapper->mapOsMaker($parserResult->platform_maker, $parserResult->platform);
            try {
                $osManufacturer = (new CompanyLoader($this->cache))->load($osMakerKey);
            } catch (NotFoundException $e) {
                //$this->logger->info($e);
            }

            $os = new Os(
                $platform,
                null,
                $osManufacturer,
                $platformVersion,
                $parserResult->platform_bits
            );
        }

        if (!isset($parserResult->renderingengine_name)) {
            $engine = new Engine(null);
        } else {
            $engineName = $this->mapper->mapEngineName($parserResult->renderingengine_name);

            $engineManufacturer = null;
            try {
                $engineManufacturer = (new CompanyLoader($this->cache))->load($parserResult->renderingengine_maker);
            } catch (NotFoundException $e) {
                //$this->logger->info($e);
            }

            $engine = new Engine(
                $engineName,
                $engineManufacturer,
                $this->mapper->mapEngineVersion($parserResult->renderingengine_version)
            );
        }

        $requestFactory = new GenericRequestFactory();

        return new Result($requestFactory->createRequestForUserAgent($agent), $device, $os, $browser, $engine);
    }

    /**
     * @return null|\UaDataMapper\InputMapper
     */
    public function getMapper()
    {
        return $this->mapper;
    }
}


text:
import { useEffect } from "react";
import { Message } from "../../lib/ipc";

export type ExtensionMessageCallback = (
  message: Message,
  sender: chrome.runtime.MessageSender,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  sendResponse: (response?: any) => void
) => void;

export const useExtensionMessage = (callback: ExtensionMessageCallback) => {
  useEffect(() => {
    chrome.runtime.onMessage.addListener(callback);
    return () => chrome.runtime.onMessage.removeListener(callback);
  }, [callback]);
};


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

<title>IUnit (CDO Model Repository Documentation)</title>
<meta name="date" content="">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.eclipse.emf.cdo.server

Interface IUnit

public interface IUnit

Since:

4.5

No Implement

This interface is not intended to be implemented by clients.

No Extend

This interface is not intended to be extended by clients.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
close(IView view)

IUnitManager
getManager()

CDOID
getRootID()

boolean
isOpen()

void
open(IView view,
    CDORevisionHandler revisionHandler,
    OMMonitor monitor)

Method Detail

getManager

IUnitManager getManager()

getRootID

CDOID getRootID()

isOpen

boolean isOpen()

open

void open(IView view,
          CDORevisionHandler revisionHandler,
          OMMonitor monitor)

close

void close(IView view)

Skip navigation links

Overview

Package

Class

Use

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright (c) 2011-2015 Eike Stepper (Berlin, Germany) and others.


text:
package org.jpacman.test.framework.model;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import org.jpacman.framework.model.Board;
import org.jpacman.framework.model.Direction;
import org.jpacman.framework.model.Tile;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 * Test the Board.tileAt method by means of a series of test cases with
 * Parameterized data.
 *
 * @author Arie van Deursen, TU Delft, Feb 10, 2012
 */
@RunWith(Parameterized.class)
public class BoardTileAtTest {

	private final int startx, starty;
	private final Direction dir;
	private final int nextx, nexty;
	private final Board board;

	private static final int WIDTH = 10;
	private static final int HEIGHT = 20;

	/**
	 * Create a new test case obtaining the tile
	 * from starting point (x, y) into the given direction.
	 * The result should be the new point (nx, ny).
	 * @param x Start x
	 * @param y Start y
	 * @param d way to go
	 * @param nx Next x
	 * @param ny Next y
	 */
	public BoardTileAtTest(int x, int y, Direction d, int nx, int ny) {
		startx = x;
		starty = y;
		dir = d;
		nextx = nx;
		nexty = ny;
		board = new Board(WIDTH, HEIGHT);
	}

	/**
	 * The actual test case.
	 */
	@Test
	public void testTileAtDirection() {
		Tile source = board.tileAt(startx, starty);
		Tile actual = board.tileAtDirection(source, dir);
		Tile desired = board.tileAt(nextx, nexty);
		assertEquals(desired, actual);
	}

	/**
	 * List of (x,y)/Direction/(newx,newy) data points.
	 * @return Test data to be fed to constructor.
	 */
	@Parameters
	public static Collection<Object[]> data() {
		Object[][] values = new Object[][] {
				// Pick all directions from one point.
				{ 2, 2, Direction.UP, 2, 1 },
				{ 2, 2, Direction.DOWN, 2, 3 },
				{ 2, 2, Direction.LEFT, 1, 2 },
				{ 2, 2, Direction.RIGHT, 3, 2 },
				// Verify the worm holes in all directions.
				{ 0, 2, Direction.LEFT, WIDTH - 1, 2 },
				{ WIDTH - 1, 2, Direction.RIGHT, 0, 2 },
				{ 2, 0, Direction.UP, 2, HEIGHT - 1 },
				{ 2, HEIGHT - 1, Direction.DOWN, 2, 0 } };
		return Arrays.asList(values);
	}

}


text:
@interface EpisodeViewModel : NSObject

@property (nonatomic, strong) NSNumber *seasonNumber;
@property (nonatomic, strong) NSNumber *episodeNumber;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *fullName;
@property (nonatomic, strong) NSString *videoPath;
@property (nonatomic, strong) NSString *subtitlePath;

@end


text:
package io.vertx.db2client.impl.codec;

import java.sql.JDBCType;
import java.util.ArrayList;
import java.util.List;

import io.vertx.db2client.impl.drda.ColumnMetaData;
import io.vertx.sqlclient.desc.ColumnDescriptor;
import io.vertx.sqlclient.impl.RowDesc;

class DB2RowDesc extends RowDesc {

  private final ColumnMetaData columnDefinitions;

  DB2RowDesc(ColumnMetaData columnDefinitions) {
    super(columnDefinitions.getColumnNames(), columns(columnDefinitions));
    this.columnDefinitions = columnDefinitions;
  }

  ColumnMetaData columnDefinitions() {
    return columnDefinitions;
  }

  private static List<ColumnDescriptor> columns(ColumnMetaData md) {
    List<String> names = md.getColumnNames();
    List<JDBCType> types = md.getJdbcTypes();
    List<ColumnDescriptor> columns = new ArrayList<>(names.size());
    for (int i = 0; i < names.size(); i++) {
      columns.add(new DB2ColumnDesc(names.get(i), types.get(i)));
    }
    return columns;
  }

  static class DB2ColumnDesc implements ColumnDescriptor {

    private final String name;
    private final JDBCType type;

    public DB2ColumnDesc(String name, JDBCType type) {
      this.name = name;
      this.type = type;
    }

    @Override
    public String name() {
      return name;
    }

    @Override
    public JDBCType jdbcType() {
      return type;
    }

    @Override
    public boolean isArray() {
      // Array don't seem supported for the moment
      return false;
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <SurfaceView
        android:id="@+id/play_ac_sv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.v7.widget.Toolbar
        android:id="@+id/play_ac_tb"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_alignParentTop="true"
        android:background="@color/light_bule">

    </android.support.v7.widget.Toolbar>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/light_bule"
        android:orientation="vertical">

        <SeekBar
            android:id="@+id/play_ac_seek_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/play_ac_previous"
                android:layout_width="@dimen/image_size_small"
                android:layout_height="@dimen/image_size_small"
                android:background="@mipmap/previous" />

            <Button
                android:id="@+id/play_ac_stop"
                android:layout_width="@dimen/image_size_small"
                android:layout_height="@dimen/image_size_small"
                android:background="@mipmap/stop" />

            <Button
                android:id="@+id/play_ac_play_or_pause"
                android:layout_width="@dimen/image_size_small"
                android:layout_height="@dimen/image_size_small"
                android:background="@mipmap/play" />

            <Button
                android:id="@+id/play_ac_next"
                android:layout_width="@dimen/image_size_small"
                android:layout_height="@dimen/image_size_small"
                android:background="@mipmap/next" />

            <Button
                android:id="@+id/play_ac_full_screen"
                android:layout_width="@dimen/image_size_small"
                android:layout_height="@dimen/image_size_small"
                android:background="@mipmap/full_screen" />

            <TextView
                android:id="@+id/play_ac_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/text_size_small" />

            <TextView
                android:id="@+id/play_ac_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:textSize="@dimen/text_size_small" />
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


text:
 'use static';

 module.exports = require('../../../locales/v2/ko.json');


text:
from __future__ import absolute_import
from __future__ import unicode_literals

from setuptools import setup, find_packages

def _requires_from_file(filename):
    return open(filename).read().splitlines()

try:
    with open('README.rst') as f:
        readme = f.read()
except IOError:
    readme = ''

setup(
    name="trie-search",
    version='0.3.0',
    url='https://github.com/nkmrtty/trie-search',
    author='Tatsuya Nakamura',
    author_email='nkmrtty.com@gmail.com',
    maintainer='Tatsuya Nakamura',
    maintainer_email='nkmrtty.com@gmail.com',
    description='Trie-search is a package for text pattern search using marisa-trie',
    long_description=readme,
    packages=find_packages(),
    install_requires=_requires_from_file('requirements.txt'),
    license="MIT",
    classifiers=[
        'Intended Audience :: Science/Research',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'License :: OSI Approved :: MIT License',
        'Topic :: Text Processing',
    ], )


text:
typedef enum {BNE, BEQ, B, BL32, BRANCH, LDR, STR, STMIA, LDMIA, POP, PUSH, MOV, MVN, NEG, CMP, TST, ADD, SUB, MUL, EOR, AND, ROR, BIC, ASR, LSL, LSR, _32BIT, WF_, SEV, NOP, EXTENSION, UNKNOWN} instruction_type_t; // 30 different types

int load(const char* filename, unsigned int* table, int size);

int parse_line(const char* line, unsigned int* address, char* instruction_name, char* instruction_args);

unsigned int calculate_cycles(instruction_type_t instruction_type, const char* args);

instruction_type_t enumerate_instruction(const char* instruction_name);

unsigned short meta_data(instruction_type_t instruction_type, const char* args);

unsigned int get_instruction(unsigned int address, unsigned int* table);

unsigned int is_conditional_branch(instruction_type_t instruction_type);

unsigned int encode_instruction_data(char* instruction_name, char* instruction_args);

int normalize_assembly_format(const char* original_line, char* normalized_line);

int parse_ovp_disassembled_line(const char* line, char* instruction_name, char* instruction_args);

#endif //_INSTRUCTIONS_ANALYSER_H


text:
require 'spec_helper'

describe 'StringToSlug' do
  context 'String tests with fallback' do
    it 'should be true' do
      str = "Hello world its me Привет Мир 際"

      I18n.locale = :en
      str.to_smart_slug_param(tolerance: 90).should eq "hello-world-its-me-priviet-mir-ji"
      str.to_smart_slug_param(tolerance: 50).should eq "hello-world-its-me"
      I18n.locale = :ru
    end
  end

  context "readme" do
    it "testcase 1" do
      "Документ.doc".to_slug_param(locale: :ru).should eq "dokument-doc"
      "Документ.doc".to_slug_param(locale: :en).should eq "doc"

      :"Документ.doc".to_slug_param(locale: :ru).should eq "dokument-doc"
      :"Документ.doc".to_slug_param(locale: :en).should eq "doc"

      "Документ.doc".to_slug_param(sep: '_', locale: :ru).should eq "dokument_doc"
      "Документ.doc".to_slug_param(sep: '_', locale: :en).should eq "doc"

      :"Документ.doc".to_slug_param(sep: '_', locale: :ru).should eq "dokument_doc"
      :"Документ.doc".to_slug_param(sep: '_', locale: :en).should eq "doc"
    end
  end

  context 'String tests' do
    it 'should be true' do
      "Привет Мир! Hello world!".to_slug_param.should eq "privet-mir-hello-world"
      "Документ.doc".to_slug_param.should eq "dokument-doc"
    end

    it 'When wrong translation' do
      "Привет Мир! Hello world!".to_slug_param(locale: :en).should eq "hello-world"
      "Документ.doc".to_slug_param(locale: :en).should eq "doc"
    end
  end

  context 'Filename test' do
    it 'should be true' do
      "/doc/dir/test/document.doc".to_slug_param.should     eq "doc-dir-test-document-doc"

      "/doc/dir/test/document.doc".slugged_filename.should  eq "document.doc"
      "/доки/dir/тест/документ.doc".slugged_filename.should eq "dokument.doc"
      "/доки/dir/тест/документ".slugged_filename.should     eq "dokument"
      "/доки/dir/тест/доку мент".slugged_filename.should    eq "doku-ment"

      String.slugged_filename("/доки/dir/тест/доку мент").should eq "doku-ment"
    end

    it 'When wrong translation' do
      "/doc/dir/test/document.doc".to_slug_param(locale: :ru).should     eq "doc-dir-test-document-doc"
      "/doc/dir/test/document.doc".slugged_filename(locale: :ru).should  eq "document.doc"

      "/доки/dir/тест/документ.doc".slugged_filename(locale: :en).should eq ".doc"
      "/доки/dir/тест/документ".slugged_filename(locale: :en).should     eq ""
      "/доки/dir/тест/доку мент".slugged_filename(locale: :en).should    eq ""

      String.slugged_filename("/доки/dir/тест/доку мент", locale: :en).should eq ""
    end
  end

  context 'Full path to file' do
    it 'should be true' do
      "/doc/dir/test/document.doc".slugged_filepath.should  eq "/doc/dir/test/document.doc"
      "/доки/dir/тест/документ.doc".slugged_filepath.should eq "/доки/dir/тест/dokument.doc"
      "/доки/dir/тест/документ".slugged_filepath.should     eq "/доки/dir/тест/dokument"
      "/доки/dir/тест/доку мент".slugged_filepath.should    eq "/доки/dir/тест/doku-ment"

      String.slugged_filepath("/доки/dir/тест/доку мент").should eq "/доки/dir/тест/doku-ment"
    end

    it 'When wrong translation' do
      "/doc/dir/test/document.doc".slugged_filepath(locale: :en).should  eq "/doc/dir/test/document.doc"
      "/доки/dir/тест/документ.doc".slugged_filepath(locale: :en).should eq "/доки/dir/тест/.doc"

      "/доки/dir/тест/документ".slugged_filepath(locale: :en).should     eq "/доки/dir/тест/"
      "/доки/dir/тест/доку мент".slugged_filepath(locale: :en).should    eq "/доки/dir/тест/"

      String.slugged_filepath("/доки/dir/тест/доку мент", locale: :en).should eq "/доки/dir/тест/"
    end
  end

  context 'sep' do
    it 'should be true' do
      "Привет Мир! Hello world!".to_slug_param(sep: '_').should eq "privet_mir_hello_world"
      "Документ.doc".to_slug_param(sep: '_').should eq "dokument_doc"

      "/доки/dir/тест/документ".slugged_filepath(sep: '_').should      eq "/доки/dir/тест/dokument"
      "/доки/dir/тест/доку мент".slugged_filepath(sep: '_').should     eq "/доки/dir/тест/doku_ment"
      "/доки/dir/тест/доку мент".slugged_filename(sep: '_').should eq "doku_ment"
    end
  end

  context "spec chars" do
    it "should works" do
      "[$&+,:;=?@Hello world!#|'<>.^*()%!-]".to_slug_param.should eq 'hello-world'
    end

    it "should works" do
      "教師 — the-teacher".to_slug_param.should eq 'the-teacher'
      "Hello ^, I'm here!".to_slug_param.should eq 'hello-i-m-here'
    end

    it "should works" do
      "HELLO---WorlD".to_slug_param(sep: '_').should eq 'hello_world'
    end

    it "should works" do
      str = "__...HELLO-___--+++--WorlD----__&&***...__.---"

      str.to_slug_param.should eq 'hello-world'
      str.to_slug_param(sep: '_').should eq 'hello_world'
      str.to_slug_param(sep: '+').should eq 'hello+world'
    end

    it "should works" do
      str = "Ilya zykin aka   Killich, $$$ aka the-teacher"
      str.to_slug_param(sep: '+').should eq "ilya+zykin+aka+killich+aka+the+teacher"
    end

    it "should works" do
      str = "Илья Николаевич, прекратите кодить по выходным!".to_sym
      str.to_slug_param.should eq "ilya-nikolaevich-prekratite-kodit-po-vyhodnym"
    end
  end

  context 'Scopes' do
    it "should work with Nested Controller Name" do
      class PagesController < ApplicationController; end
      ctrl = PagesController.new
      ctrl.controller_path.to_slug_param.should eq 'pages'
    end

    it "should work with Nested Controller Name" do
      module Admin; end
      class Admin::PagesController < ApplicationController; end
      ctrl = Admin::PagesController.new
      ctrl.controller_path.to_slug_param.should eq 'admin-pages'
    end

    it "should work with Nested Controller Name" do
      module Admin; end
      class Admin::PagesController < ApplicationController; end
      ctrl = Admin::PagesController.new
      params = { sep: '_' }
      ctrl.controller_path.to_slug_param(params).should eq 'admin_pages'
    end
  end
end


text:
module FreeDSL.VWalk.InterpreterFold where

import Control.Monad.State.Strict
import PolyGraph.Common.DslSupport (interpretInM)
import PolyGraph.ReadOnly.Graph (AdjacencyIndex(..))
import FreeDSL.VWalk

--  interpretStepM :: c -> f (m a) -> m a

--interpretInM :: forall f a m c. MInterpreterWithCtx c m f => c -> Free f a -> m a
--interpretInM c prog = foldDslProg return (interpretStepM c) prog
{-
-- not useds
interpretWalk :: forall g v e t m r. (Eq v, AdjacencyIndex g v e t, MonadState ([v]) m) =>
                               VWalkDSL v r -> g -> v -> m r
interpretWalk prog g v = interpretInM (g,v) prog

interpretWalk' :: forall g v e t m r. (Eq v, AdjacencyIndex g v e t, Monad m) =>
                               VWalkDSL v r -> g -> v -> StateT [v] m r
interpretWalk' prog g v = interpretInM (g,v) prog
-}

--
-- note this scope narrowing works, MonadState just narrows to StateT when runStateT is used
--
runWalkFull :: forall  g v e t r m . (Eq v, Monad m, AdjacencyIndex g v e t) =>
                               VWalkDSL v r -> g -> v -> m (r, [v])
runWalkFull program g v = runStateT (interpretInM g program) [v] -- ([] is empty initial state)

runWalkState :: forall  g v e t r m . (Eq v, Monad m, AdjacencyIndex g v e t) =>
                               VWalkDSL v r -> g -> v -> m [v]
runWalkState program g  =  liftM snd . runWalkFull program g

runWalk :: forall g v e t r m. (Eq v, Monad m, AdjacencyIndex g v e t) =>
                               VWalkDSL v r -> g -> v -> m r
runWalk program g  =  liftM fst . runWalkFull program g


text:
#pragma once
#include "polycode/core/PolyGlobals.h"
#include "polycode/core/PolyEntity.h"
#include "polycode/core/PolyShader.h"
#include "polycode/core/PolyRenderDataArray.h"
#include "polycode/core/PolyRenderer.h"

namespace Polycode {

	class Material;
	class Mesh;
	class Texture;
	class Skeleton;
    class Bone;
	class Image;
	class ResourcePool;

	/**
	* 3D polygonal mesh instance. The SceneMesh is the base for all polygonal 3d geometry. It can have simple textures or complex materials applied to it.
	*/
	class _PolyExport SceneMesh : public Entity {
		public:

            SceneMesh();

			/**
			* Construct a scene mesh from a mesh file.
			* @param fileName Path to mesh file to load.
			*/
			explicit SceneMesh(ResourcePool *pool, const String& fileName);

			/**
			* Construct scene mesh from an existing Mesh instance.
			*/
			explicit SceneMesh(std::shared_ptr<Mesh> mesh);

			/**
			* Construct scene mesh from an existing Mesh instance.
			*/
			static SceneMesh *SceneMeshFromMesh(std::shared_ptr<Mesh> mesh);

			virtual ~SceneMesh();

			void Render(GPUDrawBuffer *buffer);

			ShaderPass getShaderPass(unsigned int index);
			unsigned int getNumShaderPasses();
			void addShaderPass(ShaderPass pass);
			void removeShaderPass(int shaderIndex);

			/**
			* Returns the Mesh instance of the actual mesh.
			*/
			std::shared_ptr<Mesh> getMesh();

			/**
			* Returns the material applied.
			*/
			std::shared_ptr<Material> getMaterial();

			/**
			* Loads a skeleton from a file and applies it to the scene mesh.
			* @param fileName Filename to load the skeleton from.
			*/
			std::shared_ptr<Skeleton> loadSkeleton(Core *core, const String& fileName);

			/**
			* Clears the currently applied material
			*/
			void clearMaterial();

			/**
			* Set material from existing Material instance.
			* @param material Material to apply.
			*/
			void setMaterial(std::shared_ptr<Material> material);

			/**
			* Set the mesh this scene mesh renders.
			* @param mesh Set a new mesh to render.
			*/
			void setMesh(std::shared_ptr<Mesh> mesh);

			/**
			* Sets a skeleton from an existing skeleton instance.
			* @param skeleton Skeleton to set to this mesh.
			*/
			void setSkeleton(std::shared_ptr<Skeleton> skeleton);

			/**
			* Returns the skeleton applied to this scene mesh.
			*/
			std::shared_ptr<Skeleton> getSkeleton();

			/**
			 * Sets the line width for line-based meshes.
			 */
			void setLineWidth(Number newWidth);

			/**
			 * If this mesh was loaded form file, returns the filename of the loaded mesh.
			 */
			String getFilename();

			/**
			 * Sets the filename path of the mesh.
			 */
			void setFilename(const String &fileName);

			/**
			 * Loads mesh from file. Deletes current mesh if ownsMesh is set to true.
			 */
			void loadFromFile(ResourcePool *pool, const String &fileName);

			/**
			 * Line width for line-based meshes.
			 */
			Number lineWidth;

			/**
			 * If set to true, will antialias the lines in a line-based mesh. Defaults to false.
			 */
			bool lineSmooth;

			/**
			 * If setto true, will antialias points in a point-based mesh. Defaults to false.
			 */
			bool pointSmooth;

			/**
			 * If set to true, will check against actual geometry polygons on ray hit detection. Defaults to false.
			 */
			bool useGeometryHitDetection;

			bool customHitDetection(const Ray &ray);

			/**
			 * The Renderer has an ability to set an override material that is set for all rendered entities. If forceMaterial is set to true, this entity will always use its assigned material, even if an override material is set.
			 */
			void setForceMaterial(bool forceMaterial);
			bool getForceMaterial();

			virtual Entity *Clone(bool deepClone, bool ignoreEditorOnly) const;
			virtual void applyClone(Entity *clone, bool deepClone, bool ignoreEditorOnly) const;

			/**
			 * If this flag is set to false, backface culling is disabled when rendering this entity, rendering both sides of each face. Set to true by default.
			 */
			bool backfaceCulled;
			bool sendBoneMatricesToMaterial;

		protected:

            void createMaterialBoneParams(ShaderBinding *shaderBinding);
			bool useVertexBuffer;
			std::shared_ptr<Mesh> mesh;
			std::shared_ptr<Material> material;
			std::shared_ptr<Skeleton> skeleton;
			std::vector<std::shared_ptr<LocalShaderParam> > colorParams;
            std::vector<std::shared_ptr<LocalShaderParam> > boneMatrixParams;
			std::vector<ShaderPass> shaderPasses;
			String fileName;

	};
}


text:
var net = require('net');

if(process.argv.length < 4) {
  return console.log('Usage:\n\t ./02-my-telnet.js host port.');
}

var host = process.argv[2];
var port = process.argv[3];

var socket = net.connect({ host: host, port: port}, function() {
  console.log('connected to', host, 'on port', port);

  process.stdin.on('data', function(data) {
    var line = data.toString('utf8');
    line = line.slice(0, line.length-1) + '\r\n';
    socket.write(line);
  });

  socket.pipe(process.stdout);
});

socket.on('end', function() {
  console.log('disconnected from server');
  process.exit();
});


text:
package gnu.javax.crypto.mode;

import gnu.java.security.Registry;
import gnu.java.security.util.Sequence;
import gnu.javax.crypto.cipher.IBlockCipher;

import java.util.Arrays;
import java.util.Iterator;

/**
 * The implementation of the Counter Mode.
 *

 * The algorithm steps are formally described as follows:
 *
 *

 *     CTR Encryption: O[j] = E(K)(T[j]); for j = 1, 2...n;
 *                     C[j] = P[j] ˆ O[j]; for j = 1, 2...n.
 *     CTR Decryption: O[j] = E(K)(T[j]); for j = 1, 2...n;
 *                     P[j] = C[j] ˆ O[j]; for j = 1, 2...n.
 *

 *
 *

 * where P is the plaintext, C is the ciphertext,
 * E(K) is the underlying block cipher encryption function
 * parametrised with the session key K, and T is
 * the Counter.
 *

 * This implementation, uses a standard incrementing function with a step of 1,
 * and an initial value similar to that described in the NIST document.
 *

 * References:
 *

 *

 * Recommendation for Block Cipher Modes of Operation Methods and Techniques,
 * Morris Dworkin.

 *

 */
public class CTR
    extends BaseMode
    implements Cloneable
{
  private int off;
  private byte[] counter, enc;

  /**
   * Trivial package-private constructor for use by the Factory class.
   *
   * @param underlyingCipher the underlying cipher implementation.
   * @param cipherBlockSize the underlying cipher block size to use.
   */
  CTR(IBlockCipher underlyingCipher, int cipherBlockSize)
  {
    super(Registry.CTR_MODE, underlyingCipher, cipherBlockSize);
  }

  /**
   * Private constructor for cloning purposes.
   *
   * @param that the instance to clone.
   */
  private CTR(CTR that)
  {
    this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize);
  }

  public Object clone()
  {
    return new CTR(this);
  }

  public void setup()
  {
    if (modeBlockSize > cipherBlockSize)
      throw new IllegalArgumentException("mode size exceeds cipher block size");
    off = 0;
    counter = new byte[cipherBlockSize];
    int i = cipherBlockSize - 1;
    int j = iv.length - 1;
    while (i >= 0 && j >= 0)
      counter[i--] = iv[j--];
    enc = new byte[cipherBlockSize];
    cipher.encryptBlock(counter, 0, enc, 0);
  }

  public void teardown()
  {
    if (counter != null)
      Arrays.fill(counter, (byte) 0);
    if (enc != null)
      Arrays.fill(enc, (byte) 0);
  }

  public void encryptBlock(byte[] in, int i, byte[] out, int o)
  {
    ctr(in, i, out, o);
  }

  public void decryptBlock(byte[] in, int i, byte[] out, int o)
  {
    ctr(in, i, out, o);
  }

  public Iterator blockSizes()
  {
    return new Sequence(1, cipherBlockSize).iterator();
  }

  private void ctr(byte[] in, int inOffset, byte[] out, int outOffset)
  {
    for (int i = 0; i < modeBlockSize; i++)
      {
        out[outOffset++] = (byte)(in[inOffset++] ^ enc[off++]);
        if (off == cipherBlockSize)
          {
            int j;
            for (j = cipherBlockSize - 1; j >= 0; j--)
              {
                counter[j]++;
                if ((counter[j] & 0xFF) != 0)
                  break;
              }
            if (j == 0)
              counter[cipherBlockSize - 1]++;
            off = 0;
            cipher.encryptBlock(counter, 0, enc, 0);
          }
      }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>Arch Game Engine: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Arch Game Engine
    0.1

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Tileset

layer

Tileset::layer Member List

This is the complete list of members for Tileset::layer, including all inherited members.

height	Tileset::layer

th	Tileset::layer

tiles	Tileset::layer

tw	Tileset::layer

width	Tileset::layer

x	Tileset::layer

y	Tileset::layer

<address class="footer">
Generated by

 1.8.11
</address>


text:
package net.liftmodules.salatauth

import net.liftweb.util.Helpers._
import org.mindrot.jbcrypt.BCrypt
import com.mongodb.casbah.query.Imports._
import org.bson.types.ObjectId
import salat._
import salat.global._

/**
 * User entity prototype.
 *
 * You should define your entity extending this class. For example:
 * {{{
 * case class User(
 *   val _id: ObjectId,
 *   override val username: String,
 *   override val password: String,
 *   val realName: String,
 *   val email: String,
 *   override val roles: Set[String],
 *   val phone: String
 * ) extends ProtoUser(username, password, roles)
 * }}}
 *
 * To allow your roles be serialized you have to set SalatAuth.rolesCollections
 * in your Boot.scala.
 */
abstract class ProtoUser(
    val username: String,
    val password: String,
    val roles: Set[String]
) {

  private lazy val rolesCollection = SalatAuth.rolesCollection.vend

  /**
   * Checks if the password match with this user password
   * @param pass Password to be checked
   */
  def passwordMatch(pass: String): Boolean = {
    if (pass.length > 0 && password.length > 0) {
      tryo(BCrypt.checkpw(pass, password)).openOr(false)
    } else false
  }

  /**
   * Searches for roles in MongoDB
   */
  def findRoles(query: DBObject): List[Role] = {
    rolesCollection.toList.flatMap(_.find(query).map(dbo => grater[Role].asObject(dbo)).toList)
  }

  private lazy val perms = findRoles("_id" $in roles).flatMap(_.permissions).toSet

  /**
   * Returns a set of permissions for this user.
   */
  def permissions = perms
}

object ProtoUser {

  /**
   * Helper function to hash password
   *
   * @param password to be hashed
   */
  def hashPassword(password: String): String =
    tryo(BCrypt.hashpw(password, BCrypt.gensalt(10))).openOr("")
}


text:
import StringIO

FILENAME = 'cloud-config.yml'

UNITS= [
    ('sshd.socket', 'host-files/sshd.socket', 'restart', 'runtime: true'),
    ('pam-sshd.service', 'host-files/pam-sshd.service', 'start', ''),
]

FILES = [
    ('host-files/pam-sshd-prep', '/opt/pam-sshd-prep', "0755"),
    ('host-files/default.pam-sshd', '/etc/default/pam-sshd', "0644"),
    ('host-files/sshd_config', '/etc/ssh/sshd_config', "0644"),
]

HEADER = '''#cloud-config
coreos:
  units:'''

UNIT_HEADER = '''
- name: "%s"
  command: "%s"
  %s
  content: |
'''

WRITE_FILES_HEADER = '''
write_files:'''

FILES_HEADER = '''
- path: "%s"
  permissions: "%s"
  owner: "root"
  content: |
'''

def write(content, dst, indent):
    for line in content.readlines():
        level = (indent+len(line)) if (len(line) > 1) else 0
        dst.write("%*s" % (level, line))

with open(FILENAME, 'w') as config:
    write(StringIO.StringIO(HEADER), config, 0)
    for name, src_path, command, extras in UNITS:
        with open(src_path, 'r') as unit:
            write(StringIO.StringIO(UNIT_HEADER % (name, command, extras)), config, 4)
            write(unit, config, 8)

    write(StringIO.StringIO(WRITE_FILES_HEADER), config, 0)
    for src_path, dst_path, mode in FILES:
        with open(src_path, 'r') as src_file:
            write(StringIO.StringIO(FILES_HEADER % (dst_path, mode)), config, 2)
            write(src_file, config, 6)


text:
package com.fsck.k9.account;

import com.fsck.k9.Account.DeletePolicy;
import com.fsck.k9.mail.ConnectionSecurity;
import com.fsck.k9.mail.ServerSettings.Type;

/**
 * Deals with logic surrounding account creation.
 * <p/>
 * TODO Move much of the code from com.fsck.k9.activity.setup.* into here
 */
public class AccountCreator {

    public static DeletePolicy getDefaultDeletePolicy(Type type) {
        switch (type) {
            case IMAP: {
                return DeletePolicy.ON_DELETE;
            }
            case POP3: {
                return DeletePolicy.NEVER;
            }
            case WebDAV: {
                return DeletePolicy.ON_DELETE;
            }
            case EWS: {
                return DeletePolicy.ON_DELETE;
            }
            case SMTP: {
                throw new IllegalStateException("Delete policy doesn't apply to SMTP");
            }
        }

        throw new AssertionError("Unhandled case: " + type);
    }

    public static int getDefaultPort(ConnectionSecurity securityType, Type storeType) {
        switch (securityType) {
            case NONE:
            case STARTTLS_REQUIRED: {
                return storeType.defaultPort;
            }
            case SSL_TLS_REQUIRED: {
                return storeType.defaultTlsPort;
            }
        }

        throw new AssertionError("Unhandled ConnectionSecurity type encountered: " + securityType);
    }
}