text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/modules/webaudio/audio_worklet_thread.h"

#include <memory>
#include "base/feature_list.h"
#include "base/synchronization/waitable_event.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/module_record.h"
#include "third_party/blink/renderer/bindings/core/v8/script_source_code.h"
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_gc_controller.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/testing/page_test_base.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
#include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h"
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/core/workers/worklet_module_responses_map.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
#include "third_party/blink/renderer/platform/wtf/threading.h"

namespace blink {

class AudioWorkletThreadTest : public PageTestBase {
 public:
  void SetUp() override {
    PageTestBase::SetUp(IntSize());
    NavigateTo(KURL("https://example.com/"));
    reporting_proxy_ = std::make_unique<WorkerReportingProxy>();
  }

  void TearDown() override {
    AudioWorkletThread::ClearSharedBackingThread();
  }

  std::unique_ptr<AudioWorkletThread> CreateAudioWorkletThread() {
    std::unique_ptr<AudioWorkletThread> thread =
        AudioWorkletThread::Create(*reporting_proxy_);
    LocalDOMWindow* window = GetFrame().DomWindow();
    thread->Start(
        std::make_unique<GlobalScopeCreationParams>(
            window->Url(), mojom::blink::ScriptType::kModule, "AudioWorklet",
            window->UserAgent(),
            window->GetFrame()->Loader().UserAgentMetadata(),
            nullptr /* web_worker_fetch_context */, Vector<CSPHeaderAndType>(),
            window->GetReferrerPolicy(), window->GetSecurityOrigin(),
            window->IsSecureContext(), window->GetHttpsState(),
            nullptr /* worker_clients */, nullptr /* content_settings_client */,
            window->GetSecurityContext().AddressSpace(),
            OriginTrialContext::GetTokens(window).get(),
            base::UnguessableToken::Create(), nullptr /* worker_settings */,
            kV8CacheOptionsDefault,
            MakeGarbageCollected<WorkletModuleResponsesMap>(),
            mojo::NullRemote() /* browser_interface_broker */,
            BeginFrameProviderParams(), nullptr /* parent_feature_policy */,
            window->GetAgentClusterID()),
        base::nullopt, std::make_unique<WorkerDevToolsParams>());
    return thread;
  }

  // Attempts to run some simple script for |thread|.
  void CheckWorkletCanExecuteScript(WorkerThread* thread) {
    base::WaitableEvent wait_event;
    PostCrossThreadTask(
        *thread->GetWorkerBackingThread().BackingThread().GetTaskRunner(),
        FROM_HERE,
        CrossThreadBindOnce(&AudioWorkletThreadTest::ExecuteScriptInWorklet,
                            CrossThreadUnretained(this),
                            CrossThreadUnretained(thread),
                            CrossThreadUnretained(&wait_event)));
    wait_event.Wait();
  }

  void CheckWorkletThreadPriority(WorkerThread* thread,
                                  base::ThreadPriority expected_priority) {
    base::WaitableEvent wait_event;
    PostCrossThreadTask(
        *thread->GetWorkerBackingThread().BackingThread().GetTaskRunner(),
        FROM_HERE,
        CrossThreadBindOnce(&AudioWorkletThreadTest::CheckThreadPriority,
                            CrossThreadUnretained(this),
                            CrossThreadUnretained(thread),
                            expected_priority,
                            CrossThreadUnretained(&wait_event)));
    wait_event.Wait();
  }

 private:
  void ExecuteScriptInWorklet(WorkerThread* thread,
                              base::WaitableEvent* wait_event) {
    ScriptState* script_state =
        thread->GlobalScope()->ScriptController()->GetScriptState();
    EXPECT_TRUE(script_state);
    ScriptState::Scope scope(script_state);
    KURL js_url("https://example.com/worklet.js");
    v8::Local<v8::Module> module = ModuleRecord::Compile(
        script_state->GetIsolate(), "var counter = 0; ++counter;", js_url,
        js_url, ScriptFetchOptions(), TextPosition::MinimumPosition(),
        ASSERT_NO_EXCEPTION);
    EXPECT_FALSE(module.IsEmpty());
    ScriptValue exception =
        ModuleRecord::Instantiate(script_state, module, js_url);
    EXPECT_TRUE(exception.IsEmpty());
    ModuleEvaluationResult result =
        ModuleRecord::Evaluate(script_state, module, js_url);
    EXPECT_TRUE(result.IsSuccess());
    wait_event->Signal();
  }

  void CheckThreadPriority(WorkerThread* thread,
                           base::ThreadPriority expected_priority,
                           base::WaitableEvent* wait_event) {
    ASSERT_TRUE(thread->IsCurrentThread());
// TODO(crbug.com/1022888): The worklet thread priority is always NORMAL on
// linux.
#if defined(OS_LINUX)
    EXPECT_EQ(base::PlatformThread::GetCurrentThreadPriority(),
              base::ThreadPriority::NORMAL);
#else
    EXPECT_EQ(base::PlatformThread::GetCurrentThreadPriority(),
              expected_priority);
#endif
    wait_event->Signal();
  }

  std::unique_ptr<WorkerReportingProxy> reporting_proxy_;
};

TEST_F(AudioWorkletThreadTest, Basic) {
  std::unique_ptr<AudioWorkletThread> worklet = CreateAudioWorkletThread();
  CheckWorkletCanExecuteScript(worklet.get());
  worklet->Terminate();
  worklet->WaitForShutdownForTesting();
}

// Tests that the same WebThread is used for new worklets if the WebThread is
// still alive.
TEST_F(AudioWorkletThreadTest, CreateSecondAndTerminateFirst) {
  // Create the first worklet and wait until it is initialized.
  std::unique_ptr<AudioWorkletThread> first_worklet =
      CreateAudioWorkletThread();
  Thread* first_thread =
      &first_worklet->GetWorkerBackingThread().BackingThread();
  CheckWorkletCanExecuteScript(first_worklet.get());
  v8::Isolate* first_isolate = first_worklet->GetIsolate();
  ASSERT_TRUE(first_isolate);

  // Create the second worklet and immediately destroy the first worklet.
  std::unique_ptr<AudioWorkletThread> second_worklet =
      CreateAudioWorkletThread();
  // We don't use terminateAndWait here to avoid forcible termination.
  first_worklet->Terminate();
  first_worklet->WaitForShutdownForTesting();

  // Wait until the second worklet is initialized. Verify that the second
  // worklet is using the same thread and Isolate as the first worklet.
  Thread* second_thread =
      &second_worklet->GetWorkerBackingThread().BackingThread();
  ASSERT_EQ(first_thread, second_thread);

  v8::Isolate* second_isolate = second_worklet->GetIsolate();
  ASSERT_TRUE(second_isolate);
  EXPECT_EQ(first_isolate, second_isolate);

  // Verify that the worklet can still successfully execute script.
  CheckWorkletCanExecuteScript(second_worklet.get());

  second_worklet->Terminate();
  second_worklet->WaitForShutdownForTesting();
}

// Tests that a new WebThread is created if all existing worklets are
// terminated before a new worklet is created.
TEST_F(AudioWorkletThreadTest, TerminateFirstAndCreateSecond) {
  // Create the first worklet, wait until it is initialized, and terminate it.
  std::unique_ptr<AudioWorkletThread> worklet = CreateAudioWorkletThread();
  Thread* first_thread = &worklet->GetWorkerBackingThread().BackingThread();
  CheckWorkletCanExecuteScript(worklet.get());

  // We don't use terminateAndWait here to avoid forcible termination.
  worklet->Terminate();
  worklet->WaitForShutdownForTesting();

  // Create the second worklet. The backing thread is same.
  worklet = CreateAudioWorkletThread();
  Thread* second_thread = &worklet->GetWorkerBackingThread().BackingThread();
  EXPECT_EQ(first_thread, second_thread);
  CheckWorkletCanExecuteScript(worklet.get());

  worklet->Terminate();
  worklet->WaitForShutdownForTesting();
}

// Tests that v8::Isolate and WebThread are correctly set-up if a worklet is
// created while another is terminating.
TEST_F(AudioWorkletThreadTest, CreatingSecondDuringTerminationOfFirst) {
  std::unique_ptr<AudioWorkletThread> first_worklet =
      CreateAudioWorkletThread();
  CheckWorkletCanExecuteScript(first_worklet.get());
  v8::Isolate* first_isolate = first_worklet->GetIsolate();
  ASSERT_TRUE(first_isolate);

  // Request termination of the first worklet and create the second worklet
  // as soon as possible. We don't wait for its termination.
  // Note: We rely on the assumption that the termination steps don't run
  // on the worklet thread so quickly. This could be a source of flakiness.
  first_worklet->Terminate();
  std::unique_ptr<AudioWorkletThread> second_worklet =
      CreateAudioWorkletThread();

  v8::Isolate* second_isolate = second_worklet->GetIsolate();
  ASSERT_TRUE(second_isolate);
  EXPECT_EQ(first_isolate, second_isolate);

  // Verify that the isolate can run some scripts correctly in the second
  // worklet.
  CheckWorkletCanExecuteScript(second_worklet.get());
  second_worklet->Terminate();
  second_worklet->WaitForShutdownForTesting();
}

class AudioWorkletThreadDisplayPriorityTest : public AudioWorkletThreadTest {
 public:
  AudioWorkletThreadDisplayPriorityTest() {
    feature_list_.InitAndDisableFeature(features::kAudioWorkletRealtimeThread);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_F(AudioWorkletThreadDisplayPriorityTest, DisplayPriority) {
  std::unique_ptr<AudioWorkletThread> worklet = CreateAudioWorkletThread();
  CheckWorkletThreadPriority(worklet.get(), base::ThreadPriority::DISPLAY);
  worklet->Terminate();
  worklet->WaitForShutdownForTesting();
}

class AudioWorkletThreadRealtimePriorityTest : public AudioWorkletThreadTest {
 public:
  AudioWorkletThreadRealtimePriorityTest() {
    feature_list_.InitAndEnableFeature(features::kAudioWorkletRealtimeThread);
  }

 private:
  base::test::ScopedFeatureList feature_list_;
};

TEST_F(AudioWorkletThreadRealtimePriorityTest, RealtimePriority) {
  std::unique_ptr<AudioWorkletThread> worklet = CreateAudioWorkletThread();
  CheckWorkletThreadPriority(worklet.get(),
                             base::ThreadPriority::REALTIME_AUDIO);
  worklet->Terminate();
  worklet->WaitForShutdownForTesting();
}

}  // namespace blink


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

namespace SharpEntropy.IO
{
	///
	/// Abstract parent class for readers of GIS models.
	///
	/// <author>
	/// Jason Baldridge
	/// </author>
	/// <author>
	/// Richard J. Northedge
	/// </author>
	/// <version>
	/// based on GISModelReader.java, $Revision: 1.5 $, $Date: 2004/06/11 20:51:36 $
	/// </version>
	public abstract class GisModelReader : IGisModelReader
	{
		private char[] _spaces;
		private int _correctionConstant;
		private double _correctionParameter;
		private string[] _outcomeLabels;
		private int[][] _outcomePatterns;
		private int _predicateCount;
		private Dictionary<string, PatternedPredicate> _predicates;

		///
		/// The number of predicates contained in the model.
		///
		protected int PredicateCount
		{
			get
			{
				return _predicateCount;
			}
		}

        ///
		/// Retrieve a model from disk.
		///
		///
This method delegates to worker methods for each part of this
		/// sequence.  If you are creating a reader that conforms largely to this
		/// sequence but varies at one or more points, override the relevant worker
		/// method(s) to achieve the required format.

		///
		///
If you are creating a reader for a format which does not follow this
		/// sequence at all, override this method and ignore the
		/// other ReadX methods provided in this abstract class.

		///
		/// <remarks>
		/// Thie method assumes that models are saved in the
		/// following sequence:
		///
		///
GIS (model type identifier)

		///
1. the correction constant (int)

		///
2. the correction constant parameter (double)

		///
3. outcomes

		///
3a. number of outcomes (int)

		///
3b. outcome names (string array - length specified in 3a)

		///
4. predicates

		///
4a. outcome patterns

		///
4ai. number of outcome patterns (int)

		///
4aii. outcome pattern values (each stored in a space delimited string)

		///
4b. predicate labels

		///
4bi. number of predicates (int)

		///
4bii. predicate names (string array - length specified in 4bi)

		///
4c. predicate parameters (double values)

		/// </remarks>
		protected virtual void ReadModel()
		{
			_spaces = new char[] {' '}; //cached constant to improve performance
			CheckModelType();
			_correctionConstant = ReadCorrectionConstant();
			_correctionParameter = ReadCorrectionParameter();
			_outcomeLabels = ReadOutcomes();
			ReadPredicates(out _outcomePatterns, out _predicates);
		}

		///
		/// Checks the model file being read from begins with the sequence of characters
		/// "GIS".
		///
		protected virtual void CheckModelType()
		{
			string modelType = ReadString();
			if (modelType != "GIS")
			{
				throw new ApplicationException("Error: attempting to load a " + modelType + " model as a GIS model." + " You should expect problems.");
			}
		}

		///
		/// Reads the correction constant from the model file.
		///
		protected virtual int ReadCorrectionConstant()
		{
			return ReadInt32();
		}

		///
		/// Reads the correction constant parameter from the model file.
		///
		protected virtual double ReadCorrectionParameter()
		{
			return ReadDouble();
		}

		///
		/// Reads the outcome names from the model file.
		///
		protected virtual string[] ReadOutcomes()
		{
			int outcomeCount = ReadInt32();
			var outcomeLabels = new string[outcomeCount];
			for (int currentLabel = 0; currentLabel < outcomeCount; currentLabel++)
			{
				outcomeLabels[currentLabel] = ReadString();
			}
			return outcomeLabels;
		}

		///
		/// Reads the predicate information from the model file, placing the data in two
		/// structures - an array of outcome patterns, and a Dictionary of predicates
		/// keyed by predicate name.
		///
        protected virtual void ReadPredicates(out int[][] outcomePatterns, out Dictionary<string, PatternedPredicate> predicates)
		{
			outcomePatterns = ReadOutcomePatterns();
			string[] asPredicateLabels = ReadPredicateLabels();
			predicates = ReadParameters(outcomePatterns, asPredicateLabels);
		}

		///
		/// Reads the outcome pattern information from the model file.
		///
		protected virtual int[][] ReadOutcomePatterns()
		{
			//get the number of outcome patterns (that is, the number of unique combinations of outcomes in the model)
			int outcomePatternCount = ReadInt32();
			//initialize an array of outcome patterns.  Each outcome pattern is itself an array of integers
			var outcomePatterns = new int[outcomePatternCount][];
			//for each outcome pattern
			for (int currentOutcomePattern = 0; currentOutcomePattern < outcomePatternCount; currentOutcomePattern++)
			{
				//read a space delimited string from the model file containing the information for the integer array.
				//The first value in the integer array is the number of predicates related to this outcome pattern; the
				//other values make up the outcome IDs for this pattern.
				string[] tokens = ReadString().Split(_spaces);
				//convert this string to the array of integers required for the pattern
				var patternData = new int[tokens.Length];
				for (int currentPatternValue = 0; currentPatternValue < tokens.Length; currentPatternValue++)
				{
					patternData[currentPatternValue] = int.Parse(tokens[currentPatternValue], System.Globalization.CultureInfo.InvariantCulture);
				}
				outcomePatterns[currentOutcomePattern] = patternData;
			}
			return outcomePatterns;
		}

		///
		/// Reads the outcome labels from the model file.
		///
		protected virtual string[] ReadPredicateLabels()
		{
			_predicateCount = ReadInt32();
			var predicateLabels = new string[_predicateCount];
			for (int currentPredicate = 0; currentPredicate < _predicateCount; currentPredicate++)
			{
				predicateLabels[currentPredicate] = ReadString();
			}
			return predicateLabels;
		}

		///
		/// Reads the predicate parameter information from the model file.
		///
        protected virtual Dictionary<string, PatternedPredicate> ReadParameters(int[][] outcomePatterns, string[] predicateLabels)
		{
            var predicates = new Dictionary<string, PatternedPredicate>(predicateLabels.Length);
			int parameterIndex = 0;

			for (int currentOutcomePattern = 0; currentOutcomePattern < outcomePatterns.Length; currentOutcomePattern++)
			{
				for (int currentOutcomeInfo = 0; currentOutcomeInfo < outcomePatterns[currentOutcomePattern][0]; currentOutcomeInfo++)
				{
					var parameters = new double[outcomePatterns[currentOutcomePattern].Length - 1];
					for (int currentParameter = 0; currentParameter < outcomePatterns[currentOutcomePattern].Length - 1; currentParameter++)
					{
						parameters[currentParameter] = ReadDouble();
					}
					predicates.Add(predicateLabels[parameterIndex], new PatternedPredicate(currentOutcomePattern, parameters));
					parameterIndex++;
				}
			}
			return predicates;
		}

		///
		/// Implement as needed for the format the model is stored in.
		///
		protected abstract int ReadInt32();

		///
		/// Implement as needed for the format the model is stored in.
		///
		protected abstract double ReadDouble();

		///
		/// Implement as needed for the format the model is stored in.
		///
		protected abstract string ReadString();

		///
		/// The model's correction constant.
		///
		public int CorrectionConstant
		{
			get
			{
				return _correctionConstant;
			}
		}

		///
		/// The model's correction constant parameter.
		///
		public double CorrectionParameter
		{
			get
			{
				return _correctionParameter;
			}
		}

		///
		/// Returns the labels for all the outcomes in the model.
		///
		/// <returns>
		/// string array containing outcome labels.
		/// </returns>
		public string[] GetOutcomeLabels()
		{
			return _outcomeLabels;
		}

		///
		/// Returns the outcome patterns in the model.
		///
		/// <returns>
		/// Array of integer arrays containing the information for
		/// each outcome pattern in the model.
		/// </returns>
		public int[][] GetOutcomePatterns()
		{
			return _outcomePatterns;
		}

		///
		/// Returns the predicates in the model.
		///
		/// <returns>
		/// Dictionary containing PatternedPredicate objects keyed
		/// by predicate label.
		/// </returns>
        public Dictionary<string, PatternedPredicate> GetPredicates()
		{
			return _predicates;
		}

		///
		/// Returns model information for a predicate, given the predicate label.
		///
		/// <param name="predicateLabel">
		/// The predicate label to fetch information for.
		/// </param>
		/// <param name="featureCounts">
		/// Array to be passed in to the method; it should have a length equal to the number of outcomes
		/// in the model.  The method increments the count of each outcome that is active in the specified
		/// predicate.
		/// </param>
		/// <param name="outcomeSums">
		/// Array to be passed in to the method; it should have a length equal to the number of outcomes
		/// in the model.  The method adds the parameter values for each of the active outcomes in the
		/// predicate.
		/// </param>
		public virtual void GetPredicateData(string predicateLabel, int[] featureCounts, double[] outcomeSums)
		{
            try
            {
                if (predicateLabel != null && _predicates.ContainsKey(predicateLabel))
                {
                    PatternedPredicate predicate = _predicates[predicateLabel];
                    int[] activeOutcomes = _outcomePatterns[predicate.OutcomePattern];

                    for (int currentActiveOutcome = 1; currentActiveOutcome < activeOutcomes.Length; currentActiveOutcome++)
                    {
                        int outcomeIndex = activeOutcomes[currentActiveOutcome];
                        featureCounts[outcomeIndex]++;
                        outcomeSums[outcomeIndex] += predicate.GetParameter(currentActiveOutcome - 1);
                    }
                }
            }
            catch (ArgumentNullException ex)
            {
                throw new ArgumentException(string.Format("Try to find key '{0}' in predicates dictionary ({1} entries)", predicateLabel, _predicates.Count), ex);
            }
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.tvd12.ezyfox.database.annotation;

import java.lang.annotation.*;

@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface EzyQueryResult {}


text:
@implementation StringEncryptioned

@end


text:
package android.support.test.runner.lifecycle;

/**
 * An enumeration of the lifecycle stages an activity undergoes.
 * <p>
 * See the {@link android.app.Activity} javadoc for detailed documentation.
 * </p>
 */
public enum Stage {
    /** Indicates that onCreate is being called before any onCreate code executes.*/
    PRE_ON_CREATE,
    /** Indicates that onCreate has been called. */
    CREATED,
    /** Indicates that onStart has been called. */
    STARTED,
    /** Indicates that onResume has been called - activity is now visible to user. */
    RESUMED,
    /** Indicates that onPause has been called - activity is no longer in the foreground. */
    PAUSED,
    /** Indicates that onStop has been called - activity is no longer visible to the user. */
    STOPPED,
    /** Indicates that onResume has been called - we have navigated back to the activity. */
    RESTARTED,
    /** Indicates that onDestroy has been called - system is shutting down the activity. */
    DESTROYED
}


text:
using namespace std;
using namespace mmt;
using namespace mmt::fastalign;

const Vocabulary *Vocabulary::FromCorpus(const Corpus &corpus) {
    // For model efficiency all source words have the lowest id possible
    unordered_set<string> src_terms;
    unordered_set<string> trg_terms;

    CorpusReader reader(corpus);
    vector<string> src, trg;

    while (reader.Read(src, trg)) {
        src_terms.insert(src.begin(), src.end());
        trg_terms.insert(trg.begin(), trg.end());
    }

    for (auto term = src_terms.begin(); term != src_terms.end(); ++term)
        trg_terms.erase(*term);

    Vocabulary *result = new Vocabulary();
    result->terms.insert(result->terms.end(), src_terms.begin(), src_terms.end());
    result->terms.insert(result->terms.end(), trg_terms.begin(), trg_terms.end());

    for (word_t id = 0; id < result->terms.size(); ++id)
        result->vocab[result->terms[id]] = (id + 2);

    return result;
}

Vocabulary::Vocabulary(const std::string &filename, bool direct, bool reverse) {
    ifstream input(filename);

    word_t index = 2;
    for (std::string line; getline(input, line); ++index) {
        if (direct)
            vocab[line] = index;

        if (reverse)
            terms.push_back(line);
    }
}

void Vocabulary::Store(const std::string &filename) const {
    ofstream output(filename);

    for (auto term = terms.begin(); term != terms.end(); ++term)
        output << (*term) << '\n';
}


text:
require 'spec_helper'

describe 'cfndsl', type: :aruba do
  let(:usage) do
    <<-USAGE.gsub(/^ {6}/, '').chomp
      Usage: cfndsl [options] FILE
          -o, --output FILE                Write output to file
          -y, --yaml FILE                  Import yaml file as local variables
          -r, --ruby FILE                  Evaluate ruby file before template
          -j, --json FILE                  Import json file as local variables
          -p, --pretty                     Pretty-format output JSON
          -D, --define "VARIABLE=VALUE"    Directly set local VARIABLE as VALUE
          -v, --verbose                    Turn on verbose ouptut
          -b, --disable-binding            Disable binding configuration
          -h, --help                       Display this screen
    USAGE
  end

  let(:template_content) do
    <<-TEMPLATE.gsub(/^ {6}/, '')
      CloudFormation do
        Description(external_parameters[:DESC] || 'default')
      end
    TEMPLATE
  end

  before(:each) { write_file('template.rb', template_content) }

  context 'cfndsl' do
    it 'displays the usage' do
      run 'cfndsl'
      expect(last_command_started).to have_output(usage)
      expect(last_command_started).to have_exit_status(1)
    end
  end

  context 'cfndsl --help' do
    it 'displays the usage' do
      run_simple 'cfndsl --help'
      expect(last_command_started).to have_output(usage)
    end
  end

  context 'cfndsl FILE' do
    it 'gives a deprecation warning about bindings' do
      run_simple 'cfndsl template.rb'
      expect(last_command_started).to have_output_on_stderr(<<-WARN.gsub(/^ {8}/, '').chomp)
        The creation of constants as config is deprecated!
        Please switch to the #external_parameters method within your templates to access variables
        See https://github.com/stevenjack/cfndsl/issues/170
        Use the --disable-binding flag to suppress this message
      WARN
    end

    it 'generates a JSON CloudFormation template' do
      run_simple 'cfndsl template.rb'
      expect(last_command_started).to have_output_on_stdout('{"AWSTemplateFormatVersion":"2010-09-09","Description":"default"}')
    end
  end

  context 'cfndsl FILE --pretty' do
    it 'generates a pretty JSON CloudFormation template' do
      run_simple 'cfndsl template.rb --pretty'
      expect(last_command_started).to have_output_on_stdout(<<-OUTPUT.gsub(/^ {8}/, '').chomp)
        {
          "AWSTemplateFormatVersion": "2010-09-09",
          "Description": "default"
        }
      OUTPUT
    end
  end

  context 'cfndsl FILE --output FILE' do
    it 'writes the JSON CloudFormation template to a file' do
      run_simple 'cfndsl template.rb --output template.json'
      expect(read('template.json')).to eq(['{"AWSTemplateFormatVersion":"2010-09-09","Description":"default"}'])
    end
  end

  context 'cfndsl FILE --yaml FILE' do
    before { write_file('params.yaml', 'DESC: yaml') }

    it 'interpolates the YAML file in the CloudFormation template' do
      run_simple 'cfndsl template.rb --yaml params.yaml'
      expect(last_command_started).to have_output_on_stdout('{"AWSTemplateFormatVersion":"2010-09-09","Description":"yaml"}')
    end
  end

  context 'cfndsl FILE --json FILE' do
    before { write_file('params.json', '{"DESC":"json"}') }

    it 'interpolates the JSON file in the CloudFormation template' do
      run_simple 'cfndsl template.rb --json params.json'
      expect(last_command_started).to have_output_on_stdout('{"AWSTemplateFormatVersion":"2010-09-09","Description":"json"}')
    end
  end

  context 'cfndsl FILE --ruby FILE' do
    let(:template_content) do
      <<-TEMPLATE.gsub(/^ {8}/, '')
        CloudFormation do
          DESC = 'default' unless defined? DESC
          Description DESC
        end
      TEMPLATE
    end

    before(:each) { write_file('params.rb', 'DESC = "ruby"') }

    it 'interpolates the Ruby file in the CloudFormation template' do
      run_simple 'cfndsl template.rb --ruby params.rb'
      expect(last_command_started).to have_output_on_stdout('{"AWSTemplateFormatVersion":"2010-09-09","Description":"ruby"}')
    end

    it 'gives a deprecation warning and does not interpolate if bindings are disabled' do
      run_simple 'cfndsl template.rb --ruby params.rb --disable-binding --verbose'
      deprecation_warning = /Interpreting Ruby files was disabled\. .*params.rb will not be read/
      expect(last_command_started).to have_output_on_stderr(deprecation_warning)
      expect(last_command_started).to have_output_on_stdout('{"AWSTemplateFormatVersion":"2010-09-09","Description":"default"}')
    end
  end

  context 'cfndsl FILE --define VARIABLE=VALUE' do
    it 'interpolates the command line variables in the CloudFormation template' do
      run "cfndsl template.rb --define \"DESC='cli'\""
      expect(last_command_started).to have_output_on_stdout("{\"AWSTemplateFormatVersion\":\"2010-09-09\",\"Description\":\"'cli'\"}")
    end
  end

  context 'cfndsl FILE --verbose' do
    before { write_file('params.yaml', 'DESC: yaml') }

    it 'displays the variables as they are interpolated in the CloudFormation template' do
      run_simple 'cfndsl template.rb --yaml params.yaml --verbose'
      verbose = /
        Loading \s YAML \s file \s .* params\.yaml \n
        Setting \s local \s variable \s DESC \s to \s yaml \n
        Loading \s template \s file \s .* template.rb \n
        Writing \s to \s STDOUT
      /x
      template = '{"AWSTemplateFormatVersion":"2010-09-09","Description":"yaml"}'
      expect(last_command_started).to have_output_on_stderr(verbose)
      expect(last_command_started).to have_output_on_stdout(template)
    end
  end
end


text:
"""
Test parsing of simple date and times using the French locale

Note: requires PyICU
"""
import sys
import time
import datetime
import unittest
import pytest
import parsedatetime as pdt
from parsedatetime.context import pdtContext
from . import utils

class test(unittest.TestCase):

    @utils.assertEqualWithComparator
    def assertExpectedResult(self, result, check, **kwargs):
        return utils.compareResultByTimeTuplesAndFlags(result, check, **kwargs)

    def setUp(self):
        self.ptc = pdt.Constants('fr_FR')
        self.cal = pdt.Calendar(self.ptc)

        (self.yr, self.mth, self.dy, self.hr,
         self.mn, self.sec, self.wd, self.yd, self.isdst) = time.localtime()

    def testTimes(self):
        if self.ptc.localeID == 'fr_FR':
            start = datetime.datetime(
                self.yr, self.mth, self.dy,
                self.hr, self.mn, self.sec).timetuple()
            target = datetime.datetime(
                self.yr, self.mth, self.dy, 23, 0, 0).timetuple()

            self.assertExpectedResult(
                self.cal.parse('2300', start), (target, pdtContext(pdtContext.ACU_HOUR | pdtContext.ACU_MIN)))
            self.assertExpectedResult(
                self.cal.parse('23:00', start), (target, pdtContext(pdtContext.ACU_HOUR | pdtContext.ACU_MIN)))

            target = datetime.datetime(
                self.yr, self.mth, self.dy, 11, 0, 0).timetuple()

            self.assertExpectedResult(
                self.cal.parse('1100', start), (target, pdtContext(pdtContext.ACU_HOUR | pdtContext.ACU_MIN)))
            self.assertExpectedResult(
                self.cal.parse('11:00', start), (target, pdtContext(pdtContext.ACU_HOUR | pdtContext.ACU_MIN)))

            target = datetime.datetime(
                self.yr, self.mth, self.dy, 7, 30, 0).timetuple()

            self.assertExpectedResult(
                self.cal.parse('730', start), (target, pdtContext(pdtContext.ACU_HOUR | pdtContext.ACU_MIN)))
            self.assertExpectedResult(
                self.cal.parse('0730', start), (target, pdtContext(pdtContext.ACU_HOUR | pdtContext.ACU_MIN)))

            target = datetime.datetime(
                self.yr, self.mth, self.dy, 17, 30, 0).timetuple()

            self.assertExpectedResult(
                self.cal.parse('1730', start), (target, pdtContext(pdtContext.ACU_HOUR | pdtContext.ACU_MIN)))
            self.assertExpectedResult(
                self.cal.parse('173000', start), (target, pdtContext(pdtContext.ACU_HOUR | pdtContext.ACU_MIN | pdtContext.ACU_SEC)))

    def testDates(self):
        if self.ptc.localeID == 'fr_FR':
            start = datetime.datetime(
                self.yr, self.mth, self.dy,
                self.hr, self.mn, self.sec).timetuple()
            target = datetime.datetime(
                2006, 8, 25, self.hr, self.mn, self.sec).timetuple()

            self.assertExpectedResult(
                self.cal.parse('25/08/2006', start), (target, pdtContext(pdtContext.ACU_YEAR | pdtContext.ACU_MONTH | pdtContext.ACU_DAY)))
            self.assertExpectedResult(
                self.cal.parse('25/8/06', start), (target, pdtContext(pdtContext.ACU_YEAR | pdtContext.ACU_MONTH | pdtContext.ACU_DAY)))
            self.assertExpectedResult(
                self.cal.parse('août 25, 2006', start), (target, pdtContext(pdtContext.ACU_YEAR | pdtContext.ACU_MONTH | pdtContext.ACU_DAY)))
            self.assertExpectedResult(
                self.cal.parse('août 25 2006', start), (target, pdtContext(pdtContext.ACU_YEAR | pdtContext.ACU_MONTH | pdtContext.ACU_DAY)))

            if self.mth > 8 or (self.mth == 8 and self.dy > 25):
                target = datetime.datetime(
                    self.yr + 1, 8, 25, self.hr, self.mn, self.sec).timetuple()
            else:
                target = datetime.datetime(
                    self.yr, 8, 25, self.hr, self.mn, self.sec).timetuple()

            self.assertExpectedResult(
                self.cal.parse('25/8', start), (target, pdtContext(pdtContext.ACU_MONTH | pdtContext.ACU_DAY)))
            self.assertExpectedResult(
                self.cal.parse('25/08', start), (target, pdtContext(pdtContext.ACU_MONTH | pdtContext.ACU_DAY)))

    def testWeekDays(self):
        if self.ptc.localeID == 'fr_FR':
            start = datetime.datetime(
                self.yr, self.mth, self.dy,
                self.hr, self.mn, self.sec).timetuple()

            o1 = self.ptc.CurrentDOWParseStyle
            o2 = self.ptc.DOWParseStyle

            # set it up so the current dow returns current day
            self.ptc.CurrentDOWParseStyle = True
            self.ptc.DOWParseStyle = 1

            for i in range(0, 7):
                dow = self.ptc.shortWeekdays[i]

                result = self.cal.parse(dow, start)

                yr, mth, dy, hr, mn, sec, wd, yd, isdst = result[0]

                self.assertEqual(wd, i)

            self.ptc.CurrentDOWParseStyle = o1
            self.ptc.DOWParseStyle = o2

class TestDayOffsets(test):
    # test how Aujourd'hui/Demain/Hier are parsed

    def setUp(self):
        super(TestDayOffsets, self).setUp()
        self.ptc = pdt.Constants('fr_FR', usePyICU=False)
        self.cal = pdt.Calendar(self.ptc)

    def test_dayoffsets(self):
        start = datetime.datetime(self.yr, self.mth, self.dy, 9)
        for date_string, expected_day_offset in [
                ("Aujourd'hui", 0),
                ("aujourd'hui", 0),
                ("Demain", 1),
                ("demain", 1),
                ("Hier", -1),
                ("hier", -1),
                ("au jour de hui", None)]:
            got_dt, rc = self.cal.parseDT(date_string, start)
            if expected_day_offset is not None:
                self.assertEqual(rc, pdtContext(pdtContext.ACU_DAY))
                target = (start + datetime.timedelta(days=expected_day_offset))
                self.assertEqual(got_dt, target)
            else:
                self.assertEqual(rc, pdtContext())

if __name__ == "__main__":
    unittest.main()


text:
package com.xpfriend.fixture.cast.temp;

import java.lang.reflect.Array;

import org.apache.commons.beanutils.DynaProperty;

import com.xpfriend.fixture.staff.Column;

class TempDynaProperty extends DynaProperty {
	private static final long serialVersionUID = 1L;

	public TempDynaProperty(Column column) throws ClassNotFoundException {
		super(column.getName(), toClass(column), MapFactory.toClass(column.getComponentType()));
	}

	private static Class<?> toClass(Column column) throws ClassNotFoundException {
		if(column.isArray()) {
			return toArrayClass(column.getComponentType());
		}
		return MapFactory.toClass(column.getType());
	}

	private static Class<?> toArrayClass(String type) throws ClassNotFoundException {
		Class<?> componentType = MapFactory.toClass(type);
		return Array.newInstance(componentType, 0).getClass();
	}
}


text:
<?php

namespace Sonata\NewsBundle\Model;

use Sonata\CoreBundle\Model\ManagerInterface;
use Sonata\CoreBundle\Model\PageableManagerInterface;

interface PostManagerInterface extends ManagerInterface, PageableManagerInterface
{
}


text:
using ACT.TTSYukkuri.SAPI5;
using Prism.Mvvm;

namespace ACT.TTSYukkuri.Config
{
    public class SAPI5Configs :
        BindableBase
    {
        private string voiceID;
        private int rate;
        private int volume = 100;
        private Pitches pitch = Pitches.Default;

        public string VoiceID
        {
            get => this.voiceID;
            set => this.SetProperty(ref this.voiceID, value);
        }

        /// <summary>
        /// 読み上げ速さ -10 ~ 10
        /// </summary>
        public int Rate
        {
            get => this.rate;
            set => this.SetProperty(ref this.rate, value);
        }

        /// <summary>
        /// ボリューム 0 ~ 100
        /// </summary>
        public int Volume
        {
            get => this.volume;
            set => this.SetProperty(ref this.volume, value);
        }

        /// <summary>
        /// ピッチ
        /// </summary>
        public Pitches Pitch
        {
            get => this.pitch;
            set => this.SetProperty(ref this.pitch, value);
        }

        public override string ToString() =>
            $"{nameof(this.VoiceID)}:{this.VoiceID}," +
            $"{nameof(this.Rate)}:{this.Rate}," +
            $"{nameof(this.Volume)}:{this.Volume}," +
            $"{nameof(this.Pitch)}:{this.Pitch}";
    }
}


text:
package org.apache.logging.log4j.message;

import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import org.apache.logging.log4j.util.BiConsumer;
import org.apache.logging.log4j.util.Chars;
import org.apache.logging.log4j.util.EnglishEnums;
import org.apache.logging.log4j.util.IndexedReadOnlyStringMap;
import org.apache.logging.log4j.util.IndexedStringMap;
import org.apache.logging.log4j.util.MultiFormatStringBuilderFormattable;
import org.apache.logging.log4j.util.PerformanceSensitive;
import org.apache.logging.log4j.util.ReadOnlyStringMap;
import org.apache.logging.log4j.util.SortedArrayStringMap;
import org.apache.logging.log4j.util.StringBuilders;
import org.apache.logging.log4j.util.Strings;
import org.apache.logging.log4j.util.TriConsumer;

/**
 * Represents a Message that consists of a Map.
 *

 * Thread-safety note: the contents of this message can be modified after construction.
 * When using asynchronous loggers and appenders it is not recommended to modify this message after the message is
 * logged, because it is undefined whether the logged message string will contain the old values or the modified
 * values.
 *

 *

 * This class was pulled up from {@link StringMapMessage} to allow for Objects as values.
 *

 * @param <M> Allow subclasses to use fluent APIs and override methods that return instances of subclasses.
 * @param <V> The value type
 */
@PerformanceSensitive("allocation")
@AsynchronouslyFormattable
public class MapMessage<M extends MapMessage<M, V>, V> implements MultiFormatStringBuilderFormattable {

    private static final long serialVersionUID = -5031471831131487120L;

    /**
     * When set as the format specifier causes the Map to be formatted as XML.
     */
    public enum MapFormat {

        /** The map should be formatted as XML. */
        XML,

        /** The map should be formatted as JSON. */
        JSON,

        /** The map should be formatted the same as documented by {@link AbstractMap#toString()}. */
        JAVA,

        /**
         * The map should be formatted the same as documented by {@link AbstractMap#toString()} but without quotes.
         *
         * @since 2.11.2
         */
        JAVA_UNQUOTED;

        /**
         * Maps a format name to an {@link MapFormat} while ignoring case.
         *
         * @param format a MapFormat name
         * @return a MapFormat
         */
        public static MapFormat lookupIgnoreCase(final String format) {
            return XML.name().equalsIgnoreCase(format) ? XML //
                    : JSON.name().equalsIgnoreCase(format) ? JSON //
                    : JAVA.name().equalsIgnoreCase(format) ? JAVA //
                    : JAVA_UNQUOTED.name().equalsIgnoreCase(format) ? JAVA_UNQUOTED //
                    : null;
        }

        /**
         * All {@code MapFormat} names.
         *
         * @return All {@code MapFormat} names.
         */
        public static String[] names() {
            return new String[] {XML.name(), JSON.name(), JAVA.name(), JAVA_UNQUOTED.name()};
        }
    }

    private final IndexedStringMap data;

    /**
     * Constructs a new instance.
     */
    public MapMessage() {
        this.data = new SortedArrayStringMap();
    }

    /**
     * Constructs a new instance.
     *
     * @param  initialCapacity the initial capacity.
     */
    public MapMessage(final int initialCapacity) {
        this.data = new SortedArrayStringMap(initialCapacity);
    }

    /**
     * Constructs a new instance based on an existing {@link Map}.
     * @param map The Map.
     */
    public MapMessage(final Map<String, V> map) {
        this.data = new SortedArrayStringMap(map);
    }

    @Override
    public String[] getFormats() {
        return MapFormat.names();
    }

    /**
     * Returns the data elements as if they were parameters on the logging event.
     * @return the data elements.
     */
    @Override
    public Object[] getParameters() {
        final Object[] result = new Object[data.size()];
        for (int i = 0; i < data.size(); i++) {
            result[i] = data.getValueAt(i);
        }
        return result;
    }

    /**
     * Returns the message.
     * @return the message.
     */
    @Override
    public String getFormat() {
        return Strings.EMPTY;
    }

    /**
     * Returns the message data as an unmodifiable Map.
     * @return the message data as an unmodifiable map.
     */
    @SuppressWarnings("unchecked")
    public Map<String, V> getData() {
        final TreeMap<String, V> result = new TreeMap<>(); // returned map must be sorted
        for (int i = 0; i < data.size(); i++) {
            // The Eclipse compiler does not need the typecast to V, but the Oracle compiler sure does.
            result.put(data.getKeyAt(i), (V) data.getValueAt(i));
        }
        return Collections.unmodifiableMap(result);
    }

    /**
     * Returns a read-only view of the message data.
     * @return the read-only message data.
     */
    public IndexedReadOnlyStringMap getIndexedReadOnlyStringMap() {
        return data;
    }

    /**
     * Clear the data.
     */
    public void clear() {
        data.clear();
    }

    /**
     * Returns {@code true} if this data structure contains the specified key, {@code false} otherwise.
     *
     * @param key the key whose presence to check. May be {@code null}.
     * @return {@code true} if this data structure contains the specified key, {@code false} otherwise
     * @since 2.9
     */
    public boolean containsKey(final String key) {
        return data.containsKey(key);
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     */
    public void put(final String candidateKey, final String value) {
        if (value == null) {
            throw new IllegalArgumentException("No value provided for key " + candidateKey);
        }
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
    }

    /**
     * Adds all the elements from the specified Map.
     * @param map The Map to add.
     */
    public void putAll(final Map<String, String> map) {
        for (final Map.Entry<String, String> entry : map.entrySet()) {
            data.putValue(entry.getKey(), entry.getValue());
        }
    }

    /**
     * Retrieves the value of the element with the specified key or null if the key is not present.
     * @param key The name of the element.
     * @return The value of the element or null if the key is not present.
     */
    public String get(final String key) {
        final Object result = data.getValue(key);
        return ParameterFormatter.deepToString(result);
    }

    /**
     * Removes the element with the specified name.
     * @param key The name of the element.
     * @return The previous value of the element.
     */
    public String remove(final String key) {
        final String result = get(key);
        data.remove(key);
        return result;
    }

    /**
     * Formats the Structured data as described in RFC 5424.
     *
     * @return The formatted String.
     */
    public String asString() {
        return format((MapFormat) null, new StringBuilder()).toString();
    }

    /**
     * Formats the Structured data as described in RFC 5424.
     *
     * @param format The format identifier.
     * @return The formatted String.
     */
    public String asString(final String format) {
        try {
            return format(EnglishEnums.valueOf(MapFormat.class, format), new StringBuilder()).toString();
        } catch (final IllegalArgumentException ex) {
            return asString();
        }
    }

    /**
     * Performs the given action for each key-value pair in this data structure
     * until all entries have been processed or the action throws an exception.
     *

     * Some implementations may not support structural modifications (adding new elements or removing elements) while
     * iterating over the contents. In such implementations, attempts to add or remove elements from the
     * {@code BiConsumer}'s {@link BiConsumer#accept(Object, Object)} accept} method may cause a
     * {@code ConcurrentModificationException} to be thrown.
     *

     *
     * @param action The action to be performed for each key-value pair in this collection
     * @param <CV> type of the consumer value
     * @throws java.util.ConcurrentModificationException some implementations may not support structural modifications
     *          to this data structure while iterating over the contents with {@link #forEach(BiConsumer)} or
     *          {@link #forEach(TriConsumer, Object)}.
     * @see ReadOnlyStringMap#forEach(BiConsumer)
     * @since 2.9
     */
    public <CV> void forEach(final BiConsumer<String, ? super CV> action) {
        data.forEach(action);
    }

    /**
     * Performs the given action for each key-value pair in this data structure
     * until all entries have been processed or the action throws an exception.
     *

     * The third parameter lets callers pass in a stateful object to be modified with the key-value pairs,
     * so the TriConsumer implementation itself can be stateless and potentially reusable.
     *

     *

     * Some implementations may not support structural modifications (adding new elements or removing elements) while
     * iterating over the contents. In such implementations, attempts to add or remove elements from the
     * {@code TriConsumer}'s {@link TriConsumer#accept(Object, Object, Object) accept} method may cause a
     * {@code ConcurrentModificationException} to be thrown.
     *

     *
     * @param action The action to be performed for each key-value pair in this collection
     * @param state the object to be passed as the third parameter to each invocation on the specified
     *          triconsumer
     * @param <CV> type of the consumer value
     * @param <S> type of the third parameter
     * @throws java.util.ConcurrentModificationException some implementations may not support structural modifications
     *          to this data structure while iterating over the contents with {@link #forEach(BiConsumer)} or
     *          {@link #forEach(TriConsumer, Object)}.
     * @see ReadOnlyStringMap#forEach(TriConsumer, Object)
     * @since 2.9
     */
    public <CV, S> void forEach(final TriConsumer<String, ? super CV, S> action, final S state) {
        data.forEach(action, state);
    }

    /**
     * Formats the Structured data as described in RFC 5424.
     *
     * @param format The format identifier.
     * @return The formatted String.
     */
    private StringBuilder format(final MapFormat format, final StringBuilder sb) {
        if (format == null) {
            appendMap(sb);
        } else {
            switch (format) {
                case XML : {
                    asXml(sb);
                    break;
                }
                case JSON : {
                    asJson(sb);
                    break;
                }
                case JAVA : {
                    asJava(sb);
                    break;
                }
                case JAVA_UNQUOTED:
                    asJavaUnquoted(sb);
                    break;
                default : {
                    appendMap(sb);
                }
            }
        }
        return sb;
    }

    /**
     * Formats this message as an XML fragment String into the given builder.
     *
     * @param sb format into this builder.
     */
    public void asXml(final StringBuilder sb) {
        sb.append("<Map>\n");
        for (int i = 0; i < data.size(); i++) {
            sb.append("  <Entry key=\"")
                    .append(data.getKeyAt(i))
                    .append("\">");
            final int size = sb.length();
            ParameterFormatter.recursiveDeepToString(data.getValueAt(i), sb);
            StringBuilders.escapeXml(sb, size);
            sb.append("</Entry>\n");
        }
        sb.append("</Map>");
    }

    /**
     * Formats the message and return it.
     * @return the formatted message.
     */
    @Override
    public String getFormattedMessage() {
        return asString();
    }

    /**
     *
     * @param formats
     *            An array of Strings that provide extra information about how to format the message. MapMessage uses
     *            the first format specifier it recognizes. The supported formats are XML, JSON, and JAVA. The default
     *            format is key1="value1" key2="value2" as required by RFC
     *            5424 messages.
     *
     * @return The formatted message.
     */
    @Override
    public String getFormattedMessage(final String[] formats) {
        return format(getFormat(formats), new StringBuilder()).toString();
    }

    private MapFormat getFormat(final String[] formats) {
        if (formats == null || formats.length == 0) {
            return null;
        }
        for (int i = 0; i < formats.length; i++) {
            final MapFormat mapFormat = MapFormat.lookupIgnoreCase(formats[i]);
            if (mapFormat != null) {
                return mapFormat;
            }
        }
        return null;
    }

    protected void appendMap(final StringBuilder sb) {
        for (int i = 0; i < data.size(); i++) {
            if (i > 0) {
                sb.append(' ');
            }
            sb.append(data.getKeyAt(i)).append(Chars.EQ).append(Chars.DQUOTE);
            ParameterFormatter.recursiveDeepToString(data.getValueAt(i), sb);
            sb.append(Chars.DQUOTE);
        }
    }

    protected void asJson(final StringBuilder sb) {
        MapMessageJsonFormatter.format(sb, data);
    }

    protected void asJavaUnquoted(final StringBuilder sb) {
        asJava(sb, false);
    }

    protected void asJava(final StringBuilder sb) {
        asJava(sb, true);
    }

    private void asJava(final StringBuilder sb, boolean quoted) {
        sb.append('{');
        for (int i = 0; i < data.size(); i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append(data.getKeyAt(i)).append(Chars.EQ);
            if (quoted) {
                sb.append(Chars.DQUOTE);
            }
            ParameterFormatter.recursiveDeepToString(data.getValueAt(i), sb);
            if (quoted) {
                sb.append(Chars.DQUOTE);
            }
        }
        sb.append('}');
    }

    /**
     * Constructs a new instance based on an existing Map.
     * @param map The Map.
     * @return A new MapMessage
     */
    @SuppressWarnings("unchecked")
    public M newInstance(final Map<String, V> map) {
        return (M) new MapMessage<>(map);
    }

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

    @Override
    public void formatTo(final StringBuilder buffer) {
        format((MapFormat) null, buffer);
    }

    @Override
    public void formatTo(final String[] formats, final StringBuilder buffer) {
        format(getFormat(formats), buffer);
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || this.getClass() != o.getClass()) {
            return false;
        }

        final MapMessage<?, ?> that = (MapMessage<?, ?>) o;

        return this.data.equals(that.data);
    }

    @Override
    public int hashCode() {
        return data.hashCode();
    }

    /**
     * Always returns null.
     *
     * @return null
     */
    @Override
    public Throwable getThrowable() {
        return null;
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final boolean value) {
        // do nothing
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final byte value) {
        // do nothing
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final char value) {
        // do nothing
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final double value) {
        // do nothing
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final float value) {
        // do nothing
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final int value) {
        // do nothing
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final long value) {
        // do nothing
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final Object value) {
        // do nothing
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final short value) {
        // do nothing
    }

    /**
     * Default implementation does nothing.
     *
     * @since 2.9
     */
    protected void validate(final String key, final String value) {
        // do nothing
    }

    /**
     * Allows subclasses to change a candidate key to an actual key.
     *
     * @param candidateKey The candidate key.
     * @return The candidate key.
     * @since 2.12
     */
    protected String toKey(final String candidateKey) {
    	return candidateKey;
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return this object
     * @since 2.9
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final boolean value) {
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
        return (M) this;
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return this object
     * @since 2.9
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final byte value) {
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
        return (M) this;
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return this object
     * @since 2.9
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final char value) {
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
        return (M) this;
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return this object
     * @since 2.9
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final double value) {
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
        return (M) this;
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return this object
     * @since 2.9
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final float value) {
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
        return (M) this;
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return this object
     * @since 2.9
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final int value) {
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
        return (M) this;
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return this object
     * @since 2.9
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final long value) {
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
        return (M) this;
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return this object
     * @since 2.9
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final Object value) {
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
        return (M) this;
    }

    /**
     * Adds an item to the data Map.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return this object
     * @since 2.9
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final short value) {
    	final String key = toKey(candidateKey);
        validate(key, value);
        data.putValue(key, value);
        return (M) this;
    }

    /**
     * Adds an item to the data Map in fluent style.
     * @param candidateKey The name of the data item.
     * @param value The value of the data item.
     * @return {@code this}
     */
    @SuppressWarnings("unchecked")
    public M with(final String candidateKey, final String value) {
    	final String key = toKey(candidateKey);
        put(key, value);
        return (M) this;
    }

}


text:
#include <linux/kernel.h>
#include <linux/fs.h>

#include "replayfs_fs.h"
#include "replayfs_file_log.h"
#include "replayfs_log.h"
#include "replayfs_inode.h"
#include "replayfs_perftimer.h"

/*#define REPLAYFS_FILE_DEBUG*/

#ifdef REPLAYFS_FILE_DEBUG
#define debugk(...) printk(__VA_ARGS__)
#else
#define debugk(...)
#endif

/*
 * Instead of doing generic file operations we're programming our own, so that
 * we can save a log of the data instead of the data itself.
 */

struct perftimer *read_total = NULL;
struct perftimer *between_reads = NULL;
struct perftimer *write_total = NULL;
struct perftimer *between_writes = NULL;

ssize_t replayfs_file_write(struct file *filp, const char __user *buf,
		size_t len, loff_t *ppos) {

	struct replayfs_inode_info *info;
	replayfs_log_t log;
	replayfs_log_inode_t log_inode;

	if (between_writes == NULL || write_total == NULL) {
		between_writes = perftimer_create("between writes", "Writes");
		write_total = perftimer_create("write total", "Writes");
	}

	perftimer_tick(between_writes);
	perftimer_start(write_total);

	debugk("%s %d: In write\n", __func__, __LINE__);
	debugk("%s %d: Write args: (%p, %p, %u, %p (%llu))\n", __func__, __LINE__,
			filp, buf, (unsigned int)len, ppos, (unsigned long long)*ppos);

	info = REPLAYFS_I(filp->f_dentry->d_inode);

	/* Record everything, including the data */
	debugk("%s %d: calling file_log_add_next with argument %p\n", __func__,
			__LINE__, info->file_log);

	if (!replayfs_begin_log_operation(&log)) {

		replayfs_log_add_inode(&log, &log_inode, &info->vfs_inode);

		/* Report to the underlying storage the write has happened */
		replayfs_log_add_mod(&log, &log_inode, (void *)buf, len, (*ppos)+PAGE_SIZE);

		/* Update the size before reporting it to the file_log */
		if (!test_thread_flag(TIF_REPLAY)) {
			i_size_write(&info->vfs_inode, info->vfs_inode.i_size + len);
		}

		replayfs_log_inode_done(&log, &log_inode, info->vfs_inode.i_size);
		replayfs_end_log_operation(&log);
	}

	*ppos += len;

	perftimer_stop(write_total);

	return len;
}

/* How do we allocate arbitrary address ranges for this algorithm? */
ssize_t replayfs_file_read(struct file *filp, char __user *buf, size_t len,
		loff_t *ppos) {
	int num_to_read;
	loff_t version;
	struct inode *inode;
	loff_t pppos;

	if (between_reads == NULL || read_total == NULL) {
		between_reads = perftimer_create("between reads", "Reads");
		read_total = perftimer_create("read total", "Reads");
	}

	perftimer_tick(between_reads);
	perftimer_start(read_total);

	pppos = *ppos + PAGE_SIZE;

	/*
	 * They are reading from a recorded file, reconstruct the file with the file's
	 * log
	 */

	inode = filp->f_dentry->d_inode;

	debugk("%s %d: len %d, *ppos %llu, size %d\n", __func__, __LINE__,
			(unsigned int)len, (unsigned long long)*ppos,
			(unsigned int)inode->i_size);

	/* Step 0, standard error checking (permission, size, bla bla blah) */
	/* If they want more data then we have, adjust */
	if (*ppos + len > inode->i_size) {
		num_to_read = inode->i_size - *ppos;
	} else {
		num_to_read = len;
	}

	version = replayfs_inode_version(inode);

	/* Extract the data from the log */
	debugk("%s %d: Attempting to read version %lld\n", __func__, __LINE__, version);
	num_to_read = replayfs_file_log_read_user(REPLAYFS_I(inode)->file_log,
			version, buf, num_to_read, &pppos);
	*ppos = pppos - PAGE_SIZE;

	debugk("Data read is %.*s\n", num_to_read, buf);

	debugk("%s %d: num_to_read (num read) is %d\n", __func__, __LINE__,
			num_to_read);

	perftimer_stop(read_total);

	/* return the number of bytes we read */
	return num_to_read;
}


text:
<?php
/**
 * A special type Int field used for primary keys.
 *
 * @todo Allow for custom limiting/filtering of scaffoldFormField dropdown
 *
 * @package sapphire
 * @subpackage model
 */
class PrimaryKey extends Int {
	/**
	 * @var DataObject
	 */
	protected $object;

	public static $default_search_filter_class = 'ExactMatchMultiFilter';

	/**
	 * @param string $name
	 * @param DataOject $object The object that this is primary key for (should have a relation with $name)
	 */
	function __construct($name, $object) {
		$this->object = $object;
		parent::__construct($name);
	}

	public function scaffoldFormField($title = null, $params = null) {
		$titleField = ($this->object->hasField('Title')) ? "Title" : "Name";
		$map = new SQLMap($this->object->extendedSQL(), "ID", $titleField);
		return new DropdownField($this->name, $title, $map, null, null, ' ');
	}
}

?>


text:
title: Software
layout: archive
permalink: /software/
image:
  feature: banner-short-apb.png
---
{% assign sorted_software = (site.software | sort: 'date') %}
<p>
{% for code in sorted_software reversed %}
        {% include software-list.html %}
{% endfor %}


text:
package com.hazelcast.jet.pipeline.test;

import com.hazelcast.jet.Traverser;
import com.hazelcast.jet.core.AbstractProcessor;
import com.hazelcast.jet.core.AppendableTraverser;
import com.hazelcast.jet.core.EventTimeMapper;
import com.hazelcast.jet.core.EventTimePolicy;
import com.hazelcast.logging.ILogger;

import javax.annotation.Nonnull;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * Implements the {@link TestSources#longStream} source.
 *
 * @since 4.3
 */
public class LongStreamSourceP extends AbstractProcessor {

    private static final long SOURCE_THROUGHPUT_REPORTING_PERIOD_SECONDS = 5;
    private static final long HICCUP_REPORT_THRESHOLD_NANOS = MILLISECONDS.toNanos(10);
    private static final long NANOS_PER_SECOND = SECONDS.toNanos(1);

    private final long nanoTimeMillisToCurrentTimeMillis = determineTimeOffset();
    private final long eventsPerSecond;
    private final EventTimeMapper<? super Long> eventTimeMapper;
    private long startNanoTime;
    private long globalProcessorIndex;
    private long totalParallelism;

    private long lastReportNanos;
    private long valueAtLastReport;
    private long lastCallNanos;
    private long valueToEmit;
    private long nowNanoTime;
    private ILogger logger;
    private Traverser<Object> traverser = new AppendableTraverser<>(2);

    LongStreamSourceP(long startTime, long eventsPerSecond, EventTimePolicy<? super Long> eventTimePolicy) {
        this.startNanoTime = startTime; // temporarily holds the parameter value until init
        this.eventsPerSecond = eventsPerSecond;
        this.eventTimeMapper = new EventTimeMapper<>(eventTimePolicy);
        eventTimeMapper.addPartitions(1);
    }

    @Override
    protected void init(@Nonnull Context context) {
        logger = context.logger();
        totalParallelism = context.totalParallelism();
        globalProcessorIndex = context.globalProcessorIndex();
        valueToEmit = globalProcessorIndex;
        startNanoTime = MILLISECONDS.toNanos(startNanoTime + nanoTimeMillisToCurrentTimeMillis) +
                valueToEmit * NANOS_PER_SECOND / eventsPerSecond;
        lastCallNanos = lastReportNanos = startNanoTime;
    }

    @Override
    public boolean complete() {
        nowNanoTime = System.nanoTime();
        emitEvents();
        detectAndReportHiccup();
        if (logger.isFineEnabled()) {
            reportThroughput();
        }
        return false;
    }

    private void emitEvents() {
        long emitValuesUpTo = (nowNanoTime - startNanoTime) * eventsPerSecond / NANOS_PER_SECOND;
        while (emitFromTraverser(traverser) && valueToEmit < emitValuesUpTo) {
            long timestampNanoTime = startNanoTime + valueToEmit * NANOS_PER_SECOND / eventsPerSecond;
            long timestamp = NANOSECONDS.toMillis(timestampNanoTime) - nanoTimeMillisToCurrentTimeMillis;
            traverser = eventTimeMapper.flatMapEvent(nowNanoTime, valueToEmit, 0, timestamp);
            valueToEmit += totalParallelism;
        }
    }

    private void detectAndReportHiccup() {
        if ((nowNanoTime - lastCallNanos) > HICCUP_REPORT_THRESHOLD_NANOS) {
            logger.info(String.format("*** Source #%d hiccup: %,d ms%n",
                    globalProcessorIndex,
                    NANOSECONDS.toMillis(nowNanoTime - lastCallNanos)
            ));
        }
        lastCallNanos = nowNanoTime;
    }

    private void reportThroughput() {
        long nanosSinceLastReport = nowNanoTime - lastReportNanos;
        if (nanosSinceLastReport < SECONDS.toNanos(SOURCE_THROUGHPUT_REPORTING_PERIOD_SECONDS)) {
            return;
        }
        lastReportNanos = nowNanoTime;
        long localItemCountSinceLastReport = (valueToEmit - valueAtLastReport) / totalParallelism;
        valueAtLastReport = valueToEmit;
        logger.fine(String.format("p%d: %,.0f items/second",
                globalProcessorIndex,
                localItemCountSinceLastReport / ((double) nanosSinceLastReport / NANOS_PER_SECOND)));
    }

    private static long determineTimeOffset() {
        return NANOSECONDS.toMillis(System.nanoTime()) - System.currentTimeMillis();
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<AutoSaveDataInSettings>Use</AutoSaveDataInSettings>
	<VerticalScroll>useIfNecessary</VerticalScroll>
	<CommandSet>
		<ExcludedCommand>Copy</ExcludedCommand>
		<ExcludedCommand>List</ExcludedCommand>
	</CommandSet>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1"/>
	<Events>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
	</Events>
	<ChildItems>
		<Table name="Список" id="1">
			<Representation>Tree</Representation>
			<CommandBarLocation>None</CommandBarLocation>
			<DefaultItem>true</DefaultItem>
			<RowSelectionMode>Row</RowSelectionMode>
			<UseAlternationRowColor>true</UseAlternationRowColor>
			<InitialTreeView>ExpandTopLevel</InitialTreeView>
			<DataPath>Список</DataPath>
			<RowPictureDataPath>Список.DefaultPicture</RowPictureDataPath>
			<SearchStringLocation>None</SearchStringLocation>
			<ViewStatusLocation>None</ViewStatusLocation>
			<SearchControlLocation>None</SearchControlLocation>
			<AutoRefresh>false</AutoRefresh>
			<AutoRefreshPeriod>60</AutoRefreshPeriod>
			<Period xsi:type="v8:StandardPeriod">
				<v8:variant xsi:type="v8:StandardPeriodVariant">Custom</v8:variant>
				<v8:startDate>0001-01-01T00:00:00</v8:startDate>
				<v8:endDate>0001-01-01T00:00:00</v8:endDate>
			</Period>
			<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
			<RestoreCurrentRow>true</RestoreCurrentRow>
			<TopLevelParent xsi:nil="true"/>
			<ShowRoot>false</ShowRoot>
			<AllowRootChoice>false</AllowRootChoice>
			<UpdateOnDataChange>Auto</UpdateOnDataChange>
			<ContextMenu name="СписокКонтекстноеМеню" id="2"/>
			<AutoCommandBar name="СписокКоманднаяПанель" id="3"/>
			<ExtendedTooltip name="СписокExtendedTooltip" id="6"/>
			<SearchStringAddition name="СписокSearchString" id="7">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>0</lf:additionId>
				</Source>
				<ContextMenu name="СписокSearchStringContextMenu" id="8"/>
				<ExtendedTooltip name="СписокSearchStringExtendedTooltip" id="9"/>
			</SearchStringAddition>
			<ViewStatusAddition name="СписокViewStatus" id="10">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>1</lf:additionId>
				</Source>
				<ContextMenu name="СписокViewStatusContextMenu" id="11"/>
				<ExtendedTooltip name="СписокViewStatusExtendedTooltip" id="12"/>
			</ViewStatusAddition>
			<SearchControlAddition name="СписокSearchControl" id="13">
				<Source>
					<lf:elementId>1</lf:elementId>
					<lf:additionId>2</lf:additionId>
				</Source>
				<ContextMenu name="СписокSearchControlContextMenu" id="14"/>
				<ExtendedTooltip name="СписокSearchControlExtendedTooltip" id="15"/>
			</SearchControlAddition>
			<ChildItems>
				<LabelField name="Наименование" id="4">
					<DataPath>Список.Description</DataPath>
					<DefaultItem>true</DefaultItem>
					<ContextMenu name="НаименованиеКонтекстноеМеню" id="5"/>
					<ExtendedTooltip name="НаименованиеExtendedTooltip" id="16"/>
				</LabelField>
			</ChildItems>
		</Table>
	</ChildItems>
	<Attributes>
		<Attribute name="Список" id="1">
			<Type>
				<v8:Type>cfg:DynamicList</v8:Type>
			</Type>
			<MainAttribute>true</MainAttribute>
			<UseAlways>
				<Field>Список.ПредопределеннаяПапка</Field>
			</UseAlways>
			<Settings xsi:type="DynamicList">
				<ManualQuery>false</ManualQuery>
				<DynamicDataRead>true</DynamicDataRead>
				<MainTable>Catalog.ПапкиЭлектронныхПисем</MainTable>
				<ListSettings>
					<dcsset:filter>
						<dcsset:item xsi:type="dcsset:FilterItemComparison">
							<dcsset:use>false</dcsset:use>
							<dcsset:left xsi:type="dcscor:Field">Владелец</dcsset:left>
							<dcsset:comparisonType>Equal</dcsset:comparisonType>
							<dcsset:right xsi:type="dcscor:DesignTimeValue">Справочник.УчетныеЗаписиЭлектроннойПочты.ПустаяСсылка</dcsset:right>
							<dcsset:viewMode>Inaccessible</dcsset:viewMode>
						</dcsset:item>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>dfcece9d-5077-440b-b6b3-45a5cb4538eb</dcsset:userSettingID>
					</dcsset:filter>
					<dcsset:order>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>88619765-ccb3-46c6-ac52-38e9c992ebd4</dcsset:userSettingID>
					</dcsset:order>
					<dcsset:conditionalAppearance>
						<dcsset:viewMode>Normal</dcsset:viewMode>
						<dcsset:userSettingID>b75fecce-942b-4aed-abc9-e6a02e460fb3</dcsset:userSettingID>
					</dcsset:conditionalAppearance>
				</ListSettings>
			</Settings>
		</Attribute>
	</Attributes>
</Form>


text:
$(document).ready(function(){

	var url = $("#base_url").val();

	var tabla = $("#lista-citas").DataTable( {
        "language": {
            	"sProcessing":     "Procesando...",
    			"sLengthMenu":     "Mostrar _MENU_ registros",
    			"sZeroRecords":    "No se encontraron resultados",
    			"sEmptyTable":     "Ningún dato disponible en esta tabla",
    			"sInfo":           "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
    			"sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
    			"sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
    			"sInfoPostFix":    "",
    			"sSearch":         "Buscar:",
    			"sUrl":            "",
    			"sInfoThousands":  ",",
    			"sLoadingRecords": "Cargando...",
    			"oPaginate": {
    				"sFirst":    "Primero",
    				"sLast":     "Último",
    				"sNext":     "Siguiente",
    				"sPrevious": "Anterior"
    			},
    			"oAria": {
    				"sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
    				"sSortDescending": ": Activar para ordenar la columna de manera descendente"
    			}
        	}
        });

     if ($("#alert-message").length) {

        setTimeout( function(){
            $("#alert-message").hide('fast');
        }, 10000);
    }

    /*$(".table-responsive").on("click", "#lista-citas tbody tr td .detalle-cita", function(e){

        var idcita = $(this).data("idcita");

        var request;
        if (request) {
            request.abort();
        }

        $("#portada-cita").attr('src',url+"assets/img/loading.gif");
        $("#titulo-cita").html('');
    	$("#descripcion-cita").html('');
    	$("#fecha_inicio").html('');
    	$("#hora_inicio").html('');
    	$("#fecha_fin").html('');
    	$("#hora_fin").html('');

        request = $.ajax({
            url: url+"cita/Vercita",
            type: "POST",
            dataType: "json",
            data: "id="+idcita
        });

        request.done(function (response, textStatus, jqXHR){

            if (response['result'] == true) {

            	if (response['img'] != null) {

            		$("#portada-cita").attr('src',url+"assets/img/citas/"+response['img']);
            	}else{
            		$("#portada-cita").attr('src',url+"assets/img/citas.jpg");
            	}

            	$("#titulo-cita").html(response['titulo']);
            	$("#descripcion-cita").html(response['descripcion']);
            	$("#fecha_inicio").html(response['fecha_inicio']);
            	$("#hora_inicio").html(response['hora_inicio']);
            	$("#fecha_fin").html(response['fecha_fin']);
            	$("#hora_fin").html(response['hora_fin']);
            }else{
            	alert(response['message']);
            }

        });

        request.fail(function (jqXHR, textStatus, thrown){
            alert('Error: '+textStatus);
            alert(thrown);
        });

        e.preventDefault();
    });*/

    $(".table-responsive").on("click", "#lista-citas tbody tr td .eliminar-cita", function(e){

    	var idcita = $(this).data("idcita"),
            fila= $(this).closest("tr"),
            nombre= fila.find(".listanombre").text(),
            apellido= fila.find(".listaapellido").text(),
            fecha= fila.find(".listafecha").text();
        $("#delete-message").hide();

    	$("#nom_paciente").html(nombre + " " + apellido);
        $("#fecha_cita").html(fecha);
    	$("#accion-eliminar-cita").data('idcita', idcita);
    });

    $(".modal-footer").on("click", "#accion-eliminar-cita", function(e){

        var idcita = $(this).data("idcita");

        var request;
        if (request) {
            request.abort();
        }

        request = $.ajax({
            url: url+"citas/CancelarCita",
            type: "POST",
            dataType: "json",
            data: "id="+idcita
        });

        request.done(function (response, textStatus, jqXHR){

            if (response['result'] == true) {

            	$("#delete-title").hide();
            	$("#delete-message").removeClass('alert-danger').addClass('alert-success').removeClass('hidden').html(response['message']).show();
            	$("#accion-eliminar-cita").attr('disabled','disabled');
                setTimeout(function() {
                    window.location=  url+"Citas/ListarCitas";
                }, 2000);

            }else{
            	//alert(response['message']);
            	$("#delete-message").removeClass('alert-success').addClass('alert-danger').removeClass('hidden').html(response['message']).show();
            }

            setTimeout( function(){

                $('#Eliminarcita').modal('hide');
            }, 5000);

            setTimeout( function(){
                $("#delete-message").hide();
                $("#delete-title").show();
                $("#accion-eliminar-cita").removeAttr('disabled');
            }, 6000);
        });

        request.fail(function (jqXHR, textStatus, thrown){
            alert('Error: '+textStatus);
            alert(thrown);
        });

        e.preventDefault();
    });

    function dump(obj) {

        var out = "";
        for (var i in obj) {
            out += i + ": " + obj[i] + "\n";
        }

        alert(out);

        // or, if you wanted to avoid alerts...

        /*var pre = document.createElement("pre");
        pre.innerHTML = out;
        document.body.appendChild(pre)*/
    }

    $(".table-responsive").on("click", "#lista-citas tbody tr td .detalle-cita",function(e){
        e.preventDefault();
    });

    $("#lista-citas tbody tr td .detalle-cita").each(function(i,v){
        var titulo=$(this).attr("title"),
            contenido=$(this).data("content"),
            popover= {
                title: titulo,
                content: contenido,
                trigger: "hover",
                plasement: "left",
            }
        $(this).popover(popover);
    });
});


text:
"""
Unit tests for pytils' dt templatetags for Django web framework
"""

import datetime
from pytils.test.templatetags import helpers

class DtDefaultTestCase(helpers.TemplateTagTestCase):

    def setUp(self):
        self.date = datetime.datetime(2007, 1, 26, 15, 50)
        self.date_before = datetime.datetime.now() - datetime.timedelta(1, 2000)

    def testLoad(self):
        self.check_template_tag('load_tag', u'{% load pytils_dt %}', {}, u'')

    def testRuStrftimeFilter(self):
        self.check_template_tag('ru_strftime_filter',
            u'{% load pytils_dt %}{{ val|ru_strftime:"%d %B %Y, %A" }}',
            {'val': self.date},
            u'26 января 2007, пятница')

    def testRuStrftimeInflectedFilter(self):
        self.check_template_tag('ru_strftime_inflected_filter',
            u'{% load pytils_dt %}{{ val|ru_strftime_inflected:"в %A, %d %B %Y" }}',
            {'val': self.date},
            u'в пятницу, 26 января 2007')

    def testRuStrftimePrepositionFilter(self):
        self.check_template_tag('ru_strftime_preposition_filter',
            u'{% load pytils_dt %}{{ val|ru_strftime_preposition:"%A, %d %B %Y" }}',
            {'val': self.date},
            u'в\xa0пятницу, 26 января 2007')

    def testDistanceFilter(self):
        self.check_template_tag('distance_filter',
            u'{% load pytils_dt %}{{ val|distance_of_time }}',
            {'val': self.date_before},
            u'вчера')

        self.check_template_tag('distance_filter',
            u'{% load pytils_dt %}{{ val|distance_of_time:3 }}',
            {'val': self.date_before},
            u'1 день 0 часов 33 минуты назад')

    # без отладки, если ошибка -- по умолчанию пустая строка
    def testRuStrftimeError(self):
        self.check_template_tag('ru_strftime_error',
            u'{% load pytils_dt %}{{ val|ru_strftime:"%d %B %Y" }}',
            {'val': 1},
            u'')

if __name__ == '__main__':
    import unittest
    unittest.main()


text:
'use strict'

let utf8 = require('./util').utf8

module.exports = {
  broker: null,
  configuration: null,

  create: function (broker, configuration) {
    this.broker = broker
    this.configuration = configuration
    return true
  },

  receive: function (message) {
    console.log(message.properties.type == "sentinel-message" ? "\nSENTINEL MESSAGE" : "\nMESSAGE");
      console.log(`Properties: ${JSON.stringify(message.properties)}`);
      console.log(`Content: ${utf8.decode(message.content)}`)
  },

  destroy: function () { }
}


text:
    var javaCCJobInfoTable = new UIMaster.ui.objectlist
    ({
        ui: elementList["javaCCJobInfoTable"]
    });

    var javaccJobInfoPanel = new UIMaster.ui.panel
    ({
        ui: elementList["javaccJobInfoPanel"]
        ,items: [javaCCJobInfoTable]
    });

    defaultname.javaCCJobInfoTable=javaCCJobInfoTable;
defaultname.javaccJobInfoPanel = javaccJobInfoPanel;
defaultname.javaccJobInfoPanel.init();

defaultname.Form.items.push(elementList['javaccJobInfoPanel']);


text:
package com.tja.frame.web;

import java.beans.PropertyEditorSupport;

/**
 * 将空串转换成null
 *
 * @author liufang
 *
 */
public class StringEmptyEditor extends PropertyEditorSupport {
	@Override
	public void setAsText(String text) {
		if (text == null || "".equals(text)) {
			setValue(null);
		} else {
			setValue(text);
		}
	}

	@Override
	public String getAsText() {
		Object value = getValue();
		return (value != null ? value.toString() : "");
	}

}


text:
package net.community.chest.net.proto.text;

import java.io.IOException;
import java.io.StreamCorruptedException;
import java.nio.channels.SocketChannel;

import net.community.chest.io.FileUtil;
import net.community.chest.net.BufferedTextSocket;
import net.community.chest.net.TextNetConnection;
import net.community.chest.reflect.ClassUtil;

public abstract class AbstractTextProtocolNetConnectionHelper extends
                                AbstractTextProtocolNetConnection {
    protected AbstractTextProtocolNetConnectionHelper ()
    {
        super();
    }
    /**
     * Actual text connection
     */
    private TextNetConnection    _conn    /* =null */;
    /*
     * @see net.community.chest.net.proto.text.AbstractTextProtocolNetConnection#getTextNetConnection()
     */
    @Override
    public TextNetConnection getTextNetConnection ()
    {
        return _conn;
    }
    /* Break the symmetry
     * @see net.community.chest.net.AbstractNetConnection#getChannel()
     */
    @Override
    public SocketChannel getChannel ()
    {
        final TextNetConnection    conn=getTextNetConnection();
        if (conn != null)
            return conn.getChannel();

        return null;
    }
    /* Break the symmetry
     * @see net.community.chest.net.AbstractNetConnection#detachChannel()
     */
    @Override
    public SocketChannel detachChannel () throws IOException
    {
        final TextNetConnection    conn=getTextNetConnection();
        if (conn != null)
            return conn.detachChannel();
        return null;
    }

    public void setTextNetConnection (TextNetConnection conn)
    {
        _conn = conn;
    }
    /**
     * Timeout (msec.) for waiting on response from the remote server
     */
    private int _timeMillis    /* =0 */;
    /*
     * @see net.community.chest.net.NetConnection#getReadTimeout()
     */
    @Override
    public int getReadTimeout ()
    {
        return _timeMillis;
    }
    /*
     * @see net.community.chest.net.NetConnection#setReadTimeout(int)
     */
    @Override
    public void setReadTimeout (final int timeMillis) throws IOException
    {
        final TextNetConnection    conn=getTextNetConnection();
        if (conn != null)
            conn.setReadTimeout(timeMillis);
        else if (timeMillis < 0)
            throw new IOException(ClassUtil.getArgumentsExceptionLocation(getClass(), "setReadTimeout", Integer.valueOf(timeMillis)) + " bad/illegal value");

        _timeMillis = timeMillis;
    }
    /*
     * @see net.community.chest.net.proto.text.AbstractTextProtocolNetConnection#connect(java.lang.String, int)
     */
    @Override
    public void connect (String host, int port) throws IOException
    {
        final TextNetConnection    conn=getTextNetConnection();
        if (null == conn)
            throw new IOException("No set text next connection to connect through");
        // do not allow connecting to an already connected session
        if (isOpen())
            throw new StreamCorruptedException(ClassUtil.getArgumentsExceptionLocation(getClass(), "connect", host, Integer.valueOf(port)) + " already connected/attached");

        conn.connect(host, port);
    }
    /*
     * @see net.community.chest.net.AbstractNetConnection#attach(java.nio.channels.SocketChannel)
     */
    @Override
    public void attach (SocketChannel channel) throws IOException
    {
        if (null == channel)
            throw new IOException(ClassUtil.getExceptionLocation(getClass(), "attach") + " no " + SocketChannel.class.getName() + " instance provided");

        // do not allow connecting to an already connected session
        if (isOpen())
            throw new StreamCorruptedException(ClassUtil.getExceptionLocation(getClass(), "attach") + " already connected/attached");

        final BufferedTextSocket    tmpConn=new BufferedTextSocket();
        tmpConn.setReadTimeout(_timeMillis);
        tmpConn.attach(channel);
        _conn = tmpConn;
    }
    /*
     * @see net.community.chest.net.AbstractNetConnection#close()
     */
    @Override
    public void close () throws IOException
    {
        IOException superExc=null;
        try
        {
            super.close();
        }
        catch(IOException e)
        {
            superExc = e;
        }

        if (_conn != null)
        {
            try
            {
                FileUtil.closeAll(_conn);
            }
            finally
            {
                _conn = null;
            }
        }

        if (superExc != null)
            throw superExc;
    }
    /* Override to ensure closure
     * @see java.lang.Object#finalize()
     */
    @Override
    protected void finalize() throws Throwable
    {
        close();
        super.finalize();
    }
}


text:
import { LivetickerListDataService } from './../services/liveticker-list-data-service.service';
import { Liveticker } from './../liveticker';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-feed',
  templateUrl: './feed.component.html',
  styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit {

  livetickers: Liveticker[] = [];

  constructor(private dataListService: LivetickerListDataService) { }

  ngOnInit() {
    this.dataListService.getLivetickerList().subscribe(result => {
      console.log(result);
      this.livetickers = [];
      for (let i = 0; i < result.length; i++) {
        //this.livetickers.push(new Liveticker(result[i].$key, result[i].authorID, result[i].title, result[i].status, result[i].state));
      }
    });
  }
}


text:
package com.jadic.excel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * @author Jadic
 * @created 2012-12-4
 */
public class ExcelDemo {

	public static void main(String[] args) {
		createNewTransDataXLSFile();
//		Workbook wb = new HSSFWorkbook();
//	    //Workbook wb = new XSSFWorkbook();
//	    CreationHelper createHelper = wb.getCreationHelper();
//	    Sheet sheet = wb.createSheet("new sheet");
//
//	    // Create a row and put some cells in it. Rows are 0 based.
//	    Row row = sheet.createRow(0);
//
//	    // Create a cell and put a date value in it.  The first cell is not styled
//	    // as a date.
//	    Cell cell = row.createCell(0);
//	    cell.setCellValue(new Date());
//
//	    // we style the second cell as a date (and time).  It is important to
//	    // create a new cell style from the workbook otherwise you can end up
//	    // modifying the built in style and effecting not only this cell but other cells.
//	    CellStyle cellStyle = wb.createCellStyle();
//	    cellStyle.setDataFormat(
//	        createHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
//	    cell = row.createCell(1);
//	    cell.setCellValue(new Date());
//	    cell.setCellStyle(cellStyle);
//
//	    //you can also set date as java.util.Calendar
//	    cell = row.createCell(2);
//	    cell.setCellValue(Calendar.getInstance());
//	    cell.setCellStyle(cellStyle);
//		Workbook wb = new HSSFWorkbook();
//	    Sheet sheet = wb.createSheet("new sheet");
//	    Row row = sheet.createRow((short)2);
//	    row.createCell(0).setCellValue(1.1);
//	    row.createCell(1).setCellValue(new Date());
//	    row.createCell(2).setCellValue(Calendar.getInstance());
//	    row.createCell(3).setCellValue("a string");
//	    row.createCell(4).setCellValue(true);
//	    row.createCell(5).setCellType(Cell.CELL_TYPE_ERROR);
		Workbook wb = new HSSFWorkbook(); //or new HSSFWorkbook();
		Sheet sheet = wb.createSheet("new sheet");

	    // Create a row and put some cells in it. Rows are 0 based.
	    Row row = sheet.createRow((short) 1);

	    CellStyle style = wb.createCellStyle();
	    Cell cell = row.createCell((short) 0);
	    style.setFillForegroundColor(IndexedColors.RED.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(1);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(2);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.VIOLET.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(3);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.TEAL.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(4);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(5);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(6);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.CORNFLOWER_BLUE.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(7);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.MAROON.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(8);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(9);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.ORCHID.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(10);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.CORAL.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(11);
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.ROYAL_BLUE.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell.setCellStyle(style);

	    cell = row.createCell(12);
	    style = wb.createCellStyle();
	    style.setAlignment(CellStyle.ALIGN_CENTER);
	    cell.setCellValue("aaa");
	    cell.setCellStyle(style);
	    ExcelUtils.setCellBackgroudColor(cell, IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
//	    style = cell.getCellStyle();
//	    style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
//	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
//        Sheet sheet = wb.createSheet();
//        Row row = sheet.createRow((short) 2);
//        row.setHeightInPoints(30);
//
//        createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
//        createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM);
//        createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER);
//        createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER);
//        createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY);
//        createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP);
//        createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP);
//        sheet.autoSizeColumn(2);
//        sheet.addMergedRegion(new CellRangeAddress(2, 3, 2, 2));
//	    Workbook wb = new HSSFWorkbook();
//	    Sheet sheet = wb.createSheet("new sheet");
//
//	    Row row = sheet.createRow((short) 1);
//	    Cell cell = row.createCell((short) 1);
//	    cell.setCellValue("This is a test of merging");
//
//	    sheet.addMergedRegion(new CellRangeAddress(
//	            1, //first row (0-based)
//	            1, //last row  (0-based)
//	            1, //first column (0-based)
//	            2  //last column  (0-based)
//	    ));
		try {
			FileOutputStream fos = new FileOutputStream("d:/交易明细.xls");
			wb.write(fos);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void createCell(Workbook wb, Row row, short column, short halign, short valign) {
        Cell cell = row.createCell(column);
        cell.setCellValue("Align It");
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(halign);
        cellStyle.setFillBackgroundColor(IndexedColors.AQUA.getIndex());
        cellStyle.setVerticalAlignment(valign);
        cell.setCellStyle(cellStyle);
    }

	public static void createNewTransDataXLSFile() {
		Workbook wb = ExcelUtils.getWorkbook4Fuzhou("d:/icbc.xls");
		int lastRowNum = wb.getSheetAt(0).getLastRowNum();
		System.out.println(lastRowNum);
		try {
			FileOutputStream fos = new FileOutputStream("d:/工行交易明细.xls");
			wb.write(fos);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}