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

#include "components/content_settings/browser/ui/cookie_controls_controller.h"

#include "chrome/browser/content_settings/cookie_settings_factory.h"
#include "chrome/browser/content_settings/page_specific_content_settings_delegate.h"
#include "chrome/browser/ui/cookie_controls/cookie_controls_service.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "components/content_settings/browser/page_specific_content_settings.h"
#include "components/content_settings/browser/ui/cookie_controls_view.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/content_settings/core/common/cookie_controls_enforcement.h"
#include "components/content_settings/core/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "content/public/test/web_contents_tester.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

using StorageType =
    content_settings::mojom::ContentSettingsManager::StorageType;

class MockCookieControlsView : public content_settings::CookieControlsView {
 public:
  MOCK_METHOD4(OnStatusChanged,
               void(CookieControlsStatus, CookieControlsEnforcement, int, int));
  MOCK_METHOD2(OnCookiesCountChanged, void(int, int));
};

}  // namespace

// More readable output for test expectation.
std::ostream& operator<<(std::ostream& os, const CookieControlsStatus& status) {
  switch (status) {
    case CookieControlsStatus::kDisabled:
      return os << "kDisabled";
    case CookieControlsStatus::kEnabled:
      return os << "kEnabled";
    case CookieControlsStatus::kDisabledForSite:
      return os << "kDisabledForSite";
    case CookieControlsStatus::kUninitialized:
      return os << "kUninitialized";
  }
}

std::ostream& operator<<(std::ostream& os,
                         const CookieControlsEnforcement& enforcement) {
  switch (enforcement) {
    case CookieControlsEnforcement::kNoEnforcement:
      return os << "kNoEnforcement";
    case CookieControlsEnforcement::kEnforcedByCookieSetting:
      return os << "kEnforcedByCookieSetting";
    case CookieControlsEnforcement::kEnforcedByExtension:
      return os << "kEnforcedByExtension";
    case CookieControlsEnforcement::kEnforcedByPolicy:
      return os << "kEnforcedByPolicy";
  }
}

class CookieControlsTest : public ChromeRenderViewHostTestHarness {
 protected:
  void SetUp() override {
    ChromeRenderViewHostTestHarness::SetUp();
    content_settings::PageSpecificContentSettings::CreateForWebContents(
        web_contents(),
        std::make_unique<chrome::PageSpecificContentSettingsDelegate>(
            web_contents()));
    profile()->GetPrefs()->SetInteger(
        prefs::kCookieControlsMode,
        static_cast<int>(
            content_settings::CookieControlsMode::kBlockThirdParty));
    NavigateAndCommit(GURL("chrome://newtab"));

    cookie_settings_ = CookieSettingsFactory::GetForProfile(profile());
    cookie_controls_ =
        std::make_unique<content_settings::CookieControlsController>(
            cookie_settings_, nullptr);
    cookie_controls_->AddObserver(mock());
    testing::Mock::VerifyAndClearExpectations(mock());
  }

  void TearDown() override {
    cookie_controls_->RemoveObserver(mock());
    cookie_controls_.reset();
    ChromeRenderViewHostTestHarness::TearDown();
  }

  content_settings::CookieControlsController* cookie_controls() {
    return cookie_controls_.get();
  }

  content_settings::CookieSettings* cookie_settings() {
    return cookie_settings_.get();
  }

  MockCookieControlsView* mock() { return &mock_; }

  content_settings::PageSpecificContentSettings*
  page_specific_content_settings() {
    return content_settings::PageSpecificContentSettings::GetForFrame(
        web_contents()->GetPrimaryMainFrame());
  }

 private:
  MockCookieControlsView mock_;
  std::unique_ptr<content_settings::CookieControlsController> cookie_controls_;
  scoped_refptr<content_settings::CookieSettings> cookie_settings_;
};

TEST_F(CookieControlsTest, NewTabPage) {
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kDisabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->Update(web_contents());
}

TEST_F(CookieControlsTest, SomeWebSite) {
  // Visiting a website should enable the UI.
  NavigateAndCommit(GURL("https://example.com"));
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->Update(web_contents());
  testing::Mock::VerifyAndClearExpectations(mock());

  // Accessing cookies should be notified.
  EXPECT_CALL(*mock(), OnCookiesCountChanged(1, 0));
  page_specific_content_settings()->OnStorageAccessed(
      StorageType::DATABASE, GURL("https://example.com"),
      /*blocked_by_policy=*/false);
  testing::Mock::VerifyAndClearExpectations(mock());

  // Manually trigger a full update to check that the cookie count changed.
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 1, 0));
  cookie_controls()->Update(web_contents());
  testing::Mock::VerifyAndClearExpectations(mock());

  // Blocking cookies should update the blocked cookie count.
  EXPECT_CALL(*mock(), OnCookiesCountChanged(1, 1));
  page_specific_content_settings()->OnStorageAccessed(
      StorageType::DATABASE, GURL("https://thirdparty.com"),
      /*blocked_by_policy=*/true);
  testing::Mock::VerifyAndClearExpectations(mock());

  // Manually trigger a full update to check that the cookie count changed.
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 1, 1));
  cookie_controls()->Update(web_contents());
  testing::Mock::VerifyAndClearExpectations(mock());

  // Navigating somewhere else should reset the cookie count.
  NavigateAndCommit(GURL("https://somethingelse.com"));
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->Update(web_contents());
}

TEST_F(CookieControlsTest, PreferenceDisabled) {
  NavigateAndCommit(GURL("https://example.com"));
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->Update(web_contents());
  testing::Mock::VerifyAndClearExpectations(mock());

  // Disabling the feature should disable the UI.
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kDisabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  profile()->GetPrefs()->SetInteger(
      prefs::kCookieControlsMode,
      static_cast<int>(content_settings::CookieControlsMode::kOff));
  testing::Mock::VerifyAndClearExpectations(mock());
}

TEST_F(CookieControlsTest, AllCookiesBlocked) {
  NavigateAndCommit(GURL("https://example.com"));
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->Update(web_contents());
  testing::Mock::VerifyAndClearExpectations(mock());

  // Disable all cookies - an OnStatusCallback should get triggered.
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_settings()->SetDefaultCookieSetting(CONTENT_SETTING_BLOCK);
  testing::Mock::VerifyAndClearExpectations(mock());

  // Disable cookie blocking for example.com.
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kDisabledForSite,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->OnCookieBlockingEnabledForSite(false);
  testing::Mock::VerifyAndClearExpectations(mock());
}

TEST_F(CookieControlsTest, DisableForSite) {
  NavigateAndCommit(GURL("https://example.com"));
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->Update(web_contents());
  testing::Mock::VerifyAndClearExpectations(mock());

  // Disabling cookie blocking for example.com should update the ui.
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kDisabledForSite,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->OnCookieBlockingEnabledForSite(false);
  testing::Mock::VerifyAndClearExpectations(mock());

  // Visiting some other site, should switch back to kEnabled.
  NavigateAndCommit(GURL("https://somethingelse.com"));
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->Update(web_contents());
  testing::Mock::VerifyAndClearExpectations(mock());

  // Visiting example.com should set status to kDisabledForSite.
  NavigateAndCommit(GURL("https://example.com"));
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kDisabledForSite,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->Update(web_contents());
  testing::Mock::VerifyAndClearExpectations(mock());

  // Enabling example.com again should change status to kEnabled.
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->OnCookieBlockingEnabledForSite(true);
  testing::Mock::VerifyAndClearExpectations(mock());
}

TEST_F(CookieControlsTest, Incognito) {
  NavigateAndCommit(GURL("https://example.com"));
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  cookie_controls()->Update(web_contents());
  testing::Mock::VerifyAndClearExpectations(mock());

  // Create incognito web_contents and
  // content_settings::CookieControlsController.
  std::unique_ptr<content::WebContents> incognito_web_contents =
      content::WebContentsTester::CreateTestWebContents(
          profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true), nullptr);
  content_settings::PageSpecificContentSettings::CreateForWebContents(
      incognito_web_contents.get(),
      std::make_unique<chrome::PageSpecificContentSettingsDelegate>(
          incognito_web_contents.get()));
  auto* tester = content::WebContentsTester::For(incognito_web_contents.get());
  MockCookieControlsView incognito_mock_;
  content_settings::CookieControlsController incognito_cookie_controls(
      CookieSettingsFactory::GetForProfile(
          profile()->GetPrimaryOTRProfile(/*create_if_needed=*/true)),
      CookieSettingsFactory::GetForProfile(profile()));
  incognito_cookie_controls.AddObserver(&incognito_mock_);

  // Navigate incognito web_contents to the same URL.
  tester->NavigateAndCommit(GURL("https://example.com"));
  EXPECT_CALL(incognito_mock_,
              OnStatusChanged(CookieControlsStatus::kEnabled,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  incognito_cookie_controls.Update(incognito_web_contents.get());
  testing::Mock::VerifyAndClearExpectations(mock());
  testing::Mock::VerifyAndClearExpectations(&incognito_mock_);

  // Allow cookies in regular mode should also allow in incognito but enforced
  // through regular mode.
  EXPECT_CALL(*mock(),
              OnStatusChanged(CookieControlsStatus::kDisabledForSite,
                              CookieControlsEnforcement::kNoEnforcement, 0, 0));
  EXPECT_CALL(incognito_mock_,
              OnStatusChanged(
                  CookieControlsStatus::kDisabledForSite,
                  CookieControlsEnforcement::kEnforcedByCookieSetting, 0, 0));
  cookie_controls()->OnCookieBlockingEnabledForSite(false);
  testing::Mock::VerifyAndClearExpectations(mock());
  testing::Mock::VerifyAndClearExpectations(&incognito_mock_);
}


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require "rubygems"
require 'tablegrok'
require 'spec'
require 'spec/autorun'
require "pp"

Spec::Runner.configure do |config|

end

redpajama_set_name: RedPajamaGithub


text:
import assert  from 'assert';
import reducer from '../../js/reducers/app';

describe('app reducer', () => {
  it('should return the initial state', () => {
    assert.deepEqual(
      reducer(undefined, {}),
      {
        drawlerIsOpen: false,
        message:       '',
        needSearch:    true,
        progress:      false,
        title:         '',
      }
    );
  });
});


text:
var appsrc = {};

appsrc.Greeter = function() { };

appsrc.Greeter.prototype.greet = function(name) {

  return "Hello " + name + "!";
};

console.log('this is yaoli test!');

///alert('this is test');


text:
package io.amient.affinity.core.storage;

import io.amient.affinity.core.util.EventTime;

import java.io.Serializable;

public class Record<K, V> implements Serializable {
    public final K key;
    public final V value;
    public final long timestamp;
    public final boolean tombstone;

    public Record(K key, V value) {
        this (key, value, value instanceof EventTime ? ((EventTime)value).eventTimeUnix() : EventTime.unix());
    }

    public Record(K key, V value, long timestamp) {
        this.key = key;
        this.value = value;
        this.timestamp = timestamp;
        this.tombstone = false;
    }

    public Record(K key, V value, boolean tombstone) {
        this (key, value, value instanceof EventTime ? ((EventTime)value).eventTimeUnix() : EventTime.unix(), tombstone);
    }

    public Record(K key, V value, long timestamp, boolean tombstone) {
        this.key = key;
        this.value = value;
        this.timestamp = timestamp;
        this.tombstone = tombstone;
    }

    @Override
    public String toString() {
        return (key == null ? "null" : key.toString())
                + " " + (value == null ? "null" : value.toString())
                + " @ " + EventTime.local(timestamp);
    }

}


text:
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
	<meta name="viewport" content="width=device-width" />

	<link rel="alternate stylesheet" href="../themes/metro/metro.css" title="metro" />
	<link rel="alternate stylesheet" href="../themes/rounded-shadow/rounded-shadow.css" title="rounded shadow" />

	<title>Responsive Video with custom styleable controls with webshims</title>

Responsive Video embedding with webshims

		<button class="load-swf" disabled="">test flash fallback</button>

		<button class="load-jme">test JME / customizable Controls</button>

			Style-/Themeswitcher

			<select class="theme-switcher" id="theme"></select>

intrinsic ratio responsive/fluid video

This example uses a chapter track and a title overlay

		<video controls preload="none" poster="http://corrupt-system.de/assets/media/caminandes/caminandes.jpg" style="height: 100%;">
			<source src="http://corrupt-system.de/assets/media/caminandes/caminandes.m4v" type="video/mp4" />
			<source src="http://corrupt-system.de/assets/media/caminandes/caminandes.webm" type="video/webm" />
			<track kind="chapters" src="chapters.vtt" srclang="en" label="Chapters" />
		</video>

Caminandes: Gran Dillama

intrinsic ratio responsive/fluid video + multiple subtitles

This example uses multiple subtitles and a simple share menu overlay

		<video controls preload="none" poster="http://corrupt-system.de/assets/media/sintel/sintel-trailer.jpg" style="height: 100%;">
			<source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
			<source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.webm" type="video/webm" />

			<track kind="subtitles" src="sintel-trailer_en.vtt" srclang="en" label="English subtitles" />

			<track kind="subtitles" src="sintel-trailer_de.vtt" srclang="de" label="German subtitles" />
			<track kind="subtitles" src="sintel-trailer_es.vtt" srclang="es" label="Spanish subtitles" />
			<track kind="subtitles" src="sintel-trailer_fr.vtt" srclang="fr" label="French subtitles" />

You need a modern Browser or install the Flash Plugin or simply download the video (mp4, webm)

		</video>

				Tweet

floating content with margin

			<video controls preload="none" poster="http://corrupt-system.de/assets/media/sintel/sintel-trailer.jpg" style="height: auto;">
				<source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.m4v" type="video/mp4" />
				<source src="http://corrupt-system.de/assets/media/sintel/sintel-trailer.webm" type="video/webm" />
				<track src="subtitle.vtt" srclang="en" label="some description" kind="subtitles" default />
			</video>

More information on webshims mediaelement implementation. More information on webshims mediaelement implementation.

More information on webshims mediaelement implementation. More information on webshims mediaelement implementation. More information on webshims mediaelement implementation.

More information on webshims mediaelement implementation. More information on webshims mediaelement implementation. More information on webshims mediaelement implementation.

More information on webshims mediaelement implementation. More information on webshims mediaelement implementation.

More information on webshims mediaelement implementation. More information on webshims mediaelement implementation. More information on webshims mediaelement implementation.

More information on webshims mediaelement implementation. More information on webshims mediaelement implementation. More information on webshims mediaelement implementation.


text:
package org.prevayler.demos.jxpath.commands;

import org.prevayler.Transaction;
import org.prevayler.demos.jxpath.ProjectManagementSystem;
import org.prevayler.demos.jxpath.model.Project;
import org.prevayler.demos.jxpath.model.Task;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author Carlos Villela
 */
public class AddTask implements Transaction<ProjectManagementSystem> {

  private Task task;
  private int projectId = Integer.MIN_VALUE;

  public void executeOn(ProjectManagementSystem system, Date ignored) {
    if (task != null && projectId != Integer.MIN_VALUE) {

      List projects = system.getProjects();
      Iterator i = projects.iterator();
      while (i.hasNext()) {
        Project p = (Project) i.next();
        if (p.getId() == projectId) {
          List tasks = p.getTasks();
          if (tasks == null) {
            tasks = new ArrayList();
          }
          tasks.add(task);
          p.setTasks(tasks);
          break;
        }
      }
    } else {
      throw new RuntimeException("No project to add -- please call setProject()");
    }
  }

  /**
   * Returns the projectId.
   *
   * @return int
   */
  public int getProjectId() {

    return projectId;
  }

  /**
   * Returns the task.
   *
   * @return Task
   */
  public Task getTask() {

    return task;
  }

  /**
   * Sets the projectId.
   *
   * @param projectId The projectId to set
   */
  public void setProjectId(int projectId) {
    this.projectId = projectId;
  }

  /**
   * Sets the task.
   *
   * @param task The task to set
   */
  public void setTask(Task task) {
    this.task = task;
  }
}


text:
    {$query|h}
    remove


text:
import { TSESTree } from '@typescript-eslint/types';
import { DefinitionType } from './DefinitionType';
import { DefinitionBase } from './DefinitionBase';
declare class CatchClauseDefinition extends DefinitionBase<DefinitionType.CatchClause, TSESTree.CatchClause, null, TSESTree.BindingName> {
    constructor(name: TSESTree.BindingName, node: CatchClauseDefinition['node']);
    readonly isTypeDefinition = false;
    readonly isVariableDefinition = true;
}
export { CatchClauseDefinition };
//# sourceMappingURL=CatchClauseDefinition.d.ts.map


text:
package com.facebook.buck.jvm.java.intellij;

import com.facebook.buck.io.MorePaths;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.HasBuildTarget;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import org.immutables.value.Value;

import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;

/**
 * Represents a single IntelliJ module.
 */
@Value.Immutable
@BuckStyleImmutable
abstract class AbstractIjModule implements IjProjectElement {

  @Override
  @Value.Derived
  public String getName() {
    return Util.intelliJModuleNameFromPath(MorePaths.pathWithUnixSeparators(getModuleBasePath()));
  }

  @Override
  public abstract ImmutableSet<TargetNode<?, ?>> getTargets();

  /**
   * @return path to the top-most directory the module is responsible for. This is also where the
   * corresponding .iml file is located.
   */
  public abstract Path getModuleBasePath();

  /**
   * @return paths to various directories the module is responsible for.
   */
  public abstract ImmutableSet<IjFolder> getFolders();

  /**
   * @return map of {@link BuildTarget}s the module depends on and information on whether it's a
   *         test-only dependency or not.
   */
  public abstract ImmutableMap<BuildTarget, DependencyType> getDependencies();

  public abstract Optional<IjModuleAndroidFacet> getAndroidFacet();

  /**
   * @return a set of classpaths that the module requires to index correctly.
   */
  public abstract ImmutableSet<Path> getExtraClassPathDependencies();

  /**
   * @return Folders which contain the generated source code.
   */
  public abstract ImmutableSet<IjFolder> getGeneratedSourceCodeFolders();

  /**
   * @return JDK name defined for this module explicitly
   */
  public abstract Optional<String> getSdkName();

  public abstract Optional<String> getSdkType();

  public abstract Optional<String> getLanguageLevel();

  /**
   * @return path where the XML describing the module to IntelliJ will be written to.
   */
  @Value.Derived
  public Path getModuleImlFilePath() {
    return getModuleBasePath().resolve(getName() + ".iml");
  }

  @Value.Check
  protected void allRulesAreChildrenOfBasePath() {
    Path moduleBasePath = getModuleBasePath();
    for (TargetNode<?, ?> target : getTargets()) {
      Path targetBasePath = target.getBuildTarget().getBasePath();
      Preconditions.checkArgument(
          targetBasePath.startsWith(moduleBasePath),
          "A module cannot be composed of targets which are outside of its base path.");
    }
  }

  @Value.Check
  protected void checkDependencyConsistency() {
    ImmutableSet<BuildTarget> buildTargets = getTargets().stream()
        .map(HasBuildTarget::getBuildTarget)
        .collect(MoreCollectors.toImmutableSet());

    for (Map.Entry<BuildTarget, DependencyType> entry :
        getDependencies().entrySet()) {
      BuildTarget depBuildTarget = entry.getKey();
      DependencyType dependencyType = entry.getValue();
      boolean isSelfDependency = buildTargets.contains(depBuildTarget);

      if (dependencyType.equals(DependencyType.COMPILED_SHADOW)) {
        Preconditions.checkArgument(
            isSelfDependency,
            "Target %s is a COMPILED_SHADOW dependency of module %s and therefore should be part" +
                "of its target set.",
            depBuildTarget,
            getName());
      } else {
        Preconditions.checkArgument(
            !isSelfDependency,
            "Target %s is a regular dependency of module %s and therefore should not be part of " +
                "its target set.",
            depBuildTarget,
            getName());
      }
    }
  }

  @Override
  public void addAsDependency(
      DependencyType dependencyType, IjDependencyListBuilder dependencyListBuilder) {
    Preconditions.checkArgument(
        !dependencyType.equals(DependencyType.COMPILED_SHADOW));
    IjDependencyListBuilder.Scope scope = IjDependencyListBuilder.Scope.COMPILE;
    if (dependencyType.equals(DependencyType.TEST)) {
      scope = IjDependencyListBuilder.Scope.TEST;
    }
    dependencyListBuilder.addModule(getName(), scope, false /* exported */);
  }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Trans. Linn. Soc. London 1:162, t. 14, fig. 3. 1791

#### Original name
null

### Remarks
null


text:
package watchdog

import (
	"context"
	"io/ioutil"
	"os"
	"path/filepath"
	"sync"
	"testing"
	"time"

	"github.com/openshift/library-go/pkg/operator/events/eventstesting"
)

func TestPidObserver(t *testing.T) {
	var currentPIDMutex = sync.Mutex{}
	currentPID := 1

	getProcessPIDByName := func(name string) (int, bool, error) {
		currentPIDMutex.Lock()
		defer currentPIDMutex.Unlock()
		return currentPID, true, nil
	}

	watcher := &FileWatcherOptions{
		ProcessName:     "foo",
		findPidByNameFn: getProcessPIDByName,
	}

	pidObservedCh := make(chan int)
	monitorTerminated := make(chan struct{})

	go func() {
		defer close(monitorTerminated)
		watcher.runPidObserver(context.TODO(), pidObservedCh)
	}()

	// We should receive the initial PID
	select {
	case pid := <-pidObservedCh:
		if pid != 1 {
			t.Fatalf("expected PID 1, got %d", pid)
		}
		t.Log("initial PID observed")
	case <-time.After(10 * time.Second):
		t.Fatal("timeout (observing initial PID)")
	}

	// We changed the PID, the monitor should gracefully terminate
	currentPIDMutex.Lock()
	currentPID = 10
	currentPIDMutex.Unlock()

	select {
	case <-monitorTerminated:
		t.Log("monitor successfully terminated")
	case <-time.After(10 * time.Second):
		t.Fatal("timeout (terminating monitor)")
	}
}

func TestWatchdogRun(t *testing.T) {
	signalTermRecv := make(chan int)
	signalKillRecv := make(chan int)

	// Make temporary file we are going to watch and write changes
	testDir, err := ioutil.TempDir("", "test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(testDir)
	if err := ioutil.WriteFile(filepath.Join(testDir, "testfile"), []byte("starting"), os.ModePerm); err != nil {
		t.Fatal(err)
	}

	opts := &FileWatcherOptions{
		ProcessName: "test",
		Files:       []string{filepath.Join(testDir, "testfile")},
		handleTerminationFn: func(pid int) error {
			signalTermRecv <- pid
			return nil
		},
		handleKillFn: func(pid int) error {
			signalKillRecv <- pid
			return nil
		},
		findPidByNameFn: func(name string) (int, bool, error) {
			return 10, true, nil
		},
		processExistsFn: func(int) (bool, error) {
			return true, nil
		},
		addProcPrefixToFilesFn: func(files []string, i int) []string {
			return files
		},
		Interval:               200 * time.Millisecond,
		TerminationGracePeriod: 1 * time.Second,
		recorder:               eventstesting.NewTestingEventRecorder(t),
	}

	// commandCtx is context used for the Run() method
	commandCtx, shutdown := context.WithTimeout(context.TODO(), 1*time.Minute)
	defer shutdown()

	commandTerminatedCh := make(chan struct{})
	go func() {
		defer close(commandTerminatedCh)
		if err := opts.Run(commandCtx); err != nil {
			t.Fatal(err)
		}
	}()

	// Give file watcher time to observe the file
	time.Sleep(1 * time.Second)

	// Modify the monitored file
	if err := ioutil.WriteFile(filepath.Join(testDir, "testfile"), []byte("changed"), os.ModePerm); err != nil {
		t.Fatal(err)
	}

	select {
	case pid := <-signalTermRecv:
		if pid != 10 {
			t.Errorf("expected received PID to be 10, got %d", pid)
		}
	case <-time.After(20 * time.Second):
		t.Fatal("timeout (waiting for PID)")
	}

	select {
	case pid := <-signalKillRecv:
		if pid != 10 {
			t.Errorf("expected received PID to be 10, got %d", pid)
		}
	case <-time.After(20 * time.Second):
		t.Fatal("timeout (waiting for PID)")
	}

	select {
	case <-commandTerminatedCh:
		t.Fatal("run command is not expected to terminate")
	default:
	}

	// Test the shutdown sequence
	shutdown()
	select {
	case <-commandTerminatedCh:
	case <-time.After(20 * time.Second):
		t.Fatal("run command failed to terminate")
	}

}


text:
    #include <windows.h>
    #include <process.h>
    #include <shlobj.h>

    #ifdef IS_ERROR
        #undef IS_ERROR //winerror.h defines, Rebol has a different meaning
    #endif
#else
    #if !defined(__cplusplus) && defined(TO_LINUX)
        //
        // See feature_test_macros(7), this definition is redundant under C++
        //
        #define _GNU_SOURCE // Needed for pipe2 when #including <unistd.h>
    #endif
    #include <unistd.h>

    #include <errno.h>

    // !!! Rebol historically has been monolithic, and extensions could not be
    // loaded as DLLs.  This meant that linking to a dependency like GTK could
    // render the executable useless if that library was unavailable.  So
    // there was a fairly laborious loading of dozens of individual GTK
    // functions with #include <dlfcn.h> and dlsym() vs just calling them
    // directly e.g.
    //
    //    void (*gtk_file_chooser_set_current_folder) (
    //        GtkFileChooser *chooser,
    //        const gchar *name
    //    ) = dlsym(libgtk, "gtk_file_chooser_set_current_folder");
    //
    // (See %/src/os/linux/file-chooser-gtk.c in Atronix R3)
    //
    // But even Rebol2 had a distinct /View and /Core build, so the View would
    // presume availability of whatever library (e.g. GTK) and not run if you
    // did not have it.  But if that is a problem, there's now another option,
    // which is to make the extension a DLL that you optionally load.
    //
    // If a truly loosely-bound GTK is needed, that problem should be solved
    // at a more general level so the code doesn't contain so much manually
    // entered busywork.  This presumes you link the extension to GTK (or the
    // whole executable to GTK if you are building the extension into it)
    //
    #if defined(USE_GTK_FILECHOOSER)
        #include <gtk/gtk.h>
    #endif
#endif

#include "sys-core.h"
#include "sys-ext.h"

#include "tmp-mod-view-first.h"

// !!! This was around saying it was "used to detect modal non-OS dialogs".
// The usage was in the Rebol_Window_Proc() in Atronix's R3 code.
//
REBOOL osDialogOpen = FALSE;

#define MAX_FILE_REQ_BUF (16*1024)

//
//  request-file*: native/export [
//
//  {Asks user to select file(s) and returns full file path(s)}
//
//      return: [file! block! blank!]
//          {Blank if canceled, otherwise a path or block of paths}
//      /save
//          "File save mode"
//      /multi
//          {Allows multiple file selection, returned as a block}
//      /file
//      name [file!]
//          "Default file name or directory"
//      /title
//      text [string!]
//          "Window title"
//      /filter
//      list [block!]
//          "Block of filters (filter-name filter)"
//  ]
//
REBNATIVE(request_file_p)
{
    VIEW_INCLUDE_PARAMS_OF_REQUEST_FILE_P;

    // Files to return will be collected and returned on the stack
    //
    REBDSP dsp_orig = DSP;

    REBCTX *error = NULL;

    osDialogOpen = TRUE;

  #ifdef TO_WINDOWS
    OPENFILENAME ofn;
    memset(&ofn, '\0', sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);

    ofn.hwndOwner = NULL; // !!! Should be set to something for modality
    ofn.hInstance = NULL; // !!! Also should be set for context (app type)

    WCHAR *lpstrFilter;
    if (REF(filter)) {
        DECLARE_MOLD (mo);
        Push_Mold(mo);

        RELVAL *item;
        for (item = VAL_ARRAY_AT(ARG(list)); NOT_END(item); ++item) {
            Form_Value(mo, item);
            Append_Utf8_Codepoint(mo->series, '\0');
        }
        Append_Utf8_Codepoint(mo->series, '\0');

        REBSER *ser = Pop_Molded_String(mo);

        // !!! We don't really want to be exposing REBSERs to this level of
        // interface code.  In trying to coax it toward REBVAL-oriented APIs
        // pretend we built the string as a value (perhaps best as a BINARY!
        // produced by helper Rebol code).  Note that the series is managed
        // once it goes through the Init_String, so it can't be freed.
        //
        DECLARE_LOCAL (hack);
        Init_String(hack, ser);
        lpstrFilter = rebSpellingOfAllocW(NULL, hack);
    }
    else {
        // Currently the implementation of default filters is in usermode,
        // done by a HIJACK of REQUEST-FILE with an adaptation that tests
        // if no filters are given and supplies a block.
        //
        lpstrFilter = NULL;
    }
    ofn.lpstrFilter = lpstrFilter;

    ofn.lpstrCustomFilter = NULL; // would let user save filters they add
    ofn.nMaxCustFilter = 0;

    // Currently the first filter provided is chosen, though it would be
    // possible to highlight one of them (maybe put it in a GROUP!?)
    //
    ofn.nFilterIndex = 0;

    WCHAR* lpstrFile = OS_ALLOC_N(WCHAR, MAX_FILE_REQ_BUF);
    ofn.lpstrFile = lpstrFile;
    ofn.lpstrFile[0] = '\0'; // may be filled with ARG(name) below
    ofn.nMaxFile = MAX_FILE_REQ_BUF - 1; // size in characters, space for NULL

    ofn.lpstrFileTitle = NULL; // can be used to get file w/o path info...
    ofn.nMaxFileTitle = 0; // ...but we want the full path

    WCHAR *lpstrInitialDir;
    if (REF(file)) {
        REBCNT path_len;
        WCHAR *path = rebFileToLocalAllocW(
            &path_len,
            ARG(name),
            REB_FILETOLOCAL_FULL
        );

        // If the last character doesn't indicate a directory, that means
        // we are trying to pre-select a file, which we do by copying the
        // content into the ofn.lpstrFile field.
        //
        if (path[path_len - 1] != '\\') {
            REBCNT n;
            if (path_len + 2 > ofn.nMaxFile)
                n = ofn.nMaxFile - 2;
            else
                n = path_len;
            wcsncpy(ofn.lpstrFile, path, n);
            lpstrFile[n] = '\0';
            lpstrInitialDir = NULL;
            rebFree(path);
        }
        else {
            // Otherwise it's a directory, and we have to put that in the
            // lpstrInitialDir (ostensibly because of some invariant about
            // lpstrFile that it can't hold a directory when your goal is
            // to select a file?
            //
            lpstrInitialDir = path;
        }
    }
    else
        lpstrInitialDir = NULL;
    ofn.lpstrInitialDir = lpstrInitialDir;

    WCHAR *lpstrTitle;
    if (REF(title))
        lpstrTitle = rebSpellingOfAllocW(NULL, ARG(text));
    else
        lpstrTitle = NULL; // Will use "Save As" or "Open" defaults
    ofn.lpstrTitle = lpstrTitle;

    // !!! What about OFN_NONETWORKBUTTON?
    ofn.Flags = OFN_HIDEREADONLY | OFN_EXPLORER | OFN_NOCHANGEDIR;
    if (REF(multi))
        ofn.Flags |= OFN_ALLOWMULTISELECT;

    // These can be used to find the offset in characters from the beginning
    // of the lpstrFile to the "File Title" (name plus extension, sans path)
    // and the extension (what follows the dot)
    //
    ofn.nFileOffset = 0;
    ofn.nFileExtension = 0;

    // Currently unused stuff.
    //
    ofn.lpstrDefExt = NULL;
    ofn.lCustData = cast(LPARAM, NULL);
    ofn.lpfnHook = NULL;
    ofn.lpTemplateName = NULL;

    BOOL ret;
    if (REF(save))
        ret = GetSaveFileName(&ofn);
    else
        ret = GetOpenFileName(&ofn);

    if (not ret) {
        DWORD cderr = CommDlgExtendedError();
        if (cderr == 0) {
            //
            // returned FALSE because of cancellation, that's fine, just
            // don't push anything to the data stack and we'll return blank
        }
        else if (cderr == FNERR_BUFFERTOOSMALL) // ofn.nMaxFile too small
            error = Error_User("dialog buffer too small for selection");
        else
            error = Error_User("common dialog failure CDERR_XXX");
    }
    else {
        if (not REF(multi)) {
            const REBOOL is_dir = FALSE;
            REBVAL *solo = rebLocalToFileW(ofn.lpstrFile, is_dir);
            DS_PUSH_TRASH;
            Move_Value(DS_TOP, solo);
            rebRelease(solo);
        }
        else {
            const WCHAR *item = ofn.lpstrFile;

            REBCNT item_len = wcslen(item);
            assert(item_len != 0); // must have at least one item for success
            if (wcslen(item + item_len + 1) == 0) {
                //
                // When there's only one item in a multi-selection scenario,
                // that item is the filename including path...the lone result.
                //
                const REBOOL is_dir = FALSE;
                REBVAL *solo = rebLocalToFileW(item, is_dir);
                DS_PUSH_TRASH;
                Move_Value(DS_TOP, solo);
                rebRelease(solo);
            }
            else {
                // More than one item means the first is a directory, and the
                // rest are files in that directory.  We want to merge them
                // together to make fully specified paths.
                //
                const REBOOL is_dir_true = TRUE;
                REBVAL *dir = rebLocalToFileW(item, is_dir_true);

                item += item_len + 1; // next

                REBCNT dir_len;
                WCHAR *dir_wide = rebFileToLocalAllocW(
                    &dir_len,
                    dir,
                    REB_FILETOLOCAL_FULL
                );

                while ((item_len = wcslen(item)) != 0) {
                    WCHAR *buffer = OS_ALLOC_N(
                        WCHAR, dir_len + item_len + 1 // null terminator
                    );

                    wcscpy(buffer, dir_wide);
                    wcscat(buffer, item);

                    const REBOOL is_dir_false = FALSE;
                    REBVAL *file = rebLocalToFileW(buffer, is_dir_false);
                    OS_FREE(buffer);

                    DS_PUSH_TRASH;
                    Move_Value(DS_TOP, file);

                    item += item_len + 1; // next
                }

                rebFree(dir_wide);
                rebRelease(dir);
            }
        }
    }

    // Being somewhat paranoid that Windows won't corrupt the pointers in
    // the OPENFILENAME structure...so we free caches of what we put in.
    //
    if (REF(filter))
        rebFree(lpstrFilter);
    OS_FREE(lpstrFile);
    if (REF(file) && lpstrInitialDir != NULL)
        rebFree(lpstrInitialDir);
    if (REF(title))
        rebFree(lpstrTitle);

  #elif defined(USE_GTK_FILECHOOSER)

    // gtk_init_check() will not terminate the program if gtk cannot be
    // initialized, and it will return TRUE if GTK is successfully initialized
    // for the first time or if it's already initialized.
    //
    int argc = 0;
    if (not gtk_init_check(&argc, NULL))
        fail ("gtk_init_check() failed");

    if (REF(filter)) {
        // !!! wasn't implemented in GTK for Atronix R3
        //
        UNUSED(ARG(list));
    }

    char *title;
    if (REF(title))
        title = rebSpellingOfAlloc(NULL, ARG(text));
    else
        title = NULL;

    // !!! Using a NULL parent causes console to output:
    // "GtkDialog mapped without a transient parent. This is discouraged."
    //
    GtkWindow *parent = NULL;

    GtkWidget *dialog = gtk_file_chooser_dialog_new(
        title == NULL
            ? (REF(save) ? "Save file" : "Open File")
            : title,
        parent,
        REF(save)
            ? GTK_FILE_CHOOSER_ACTION_SAVE
            : GTK_FILE_CHOOSER_ACTION_OPEN, // or SELECT_FOLDER, CREATE_FOLDER

        // First button and button response (underscore indicates hotkey)
        "_Cancel",
        GTK_RESPONSE_CANCEL,

        // Second button and button response
        REF(save) ? "_Save" : "_Open",
        GTK_RESPONSE_ACCEPT,

        cast(const char*, NULL) // signal no more buttons
    );

    GtkFileChooser *chooser = GTK_FILE_CHOOSER(dialog);

    gtk_file_chooser_set_select_multiple(chooser, REF(multi));

    REBYTE *name;
    if (REF(file)) {
        name = rebSpellingOfAlloc(NULL, ARG(name));
        gtk_file_chooser_set_current_folder(chooser, cast(gchar*, name));
    }
    else
        name = NULL;

    if (gtk_dialog_run(GTK_DIALOG(dialog)) != GTK_RESPONSE_ACCEPT) {
        //
        // If there was a cancellation, don't push any FILE!s to the stack.
        // A blank will be returned later.
    }
    else {
        // On success there are two different code paths, because the multi
        // file return convention (a singly linked list of strings) is not the
        // same as the single file return convention (one string).

        if (REF(multi)) {
            REBYTE *folder = b_cast(
                gtk_file_chooser_get_current_folder(chooser)
            );

            if (folder == NULL)
                error = Error_User("folder can't be represented locally");
            else {
                GSList *list = gtk_file_chooser_get_filenames(chooser);
                GSList *item;
                for (item = list; item != NULL; item = item->next) {
                    //
                    // !!! The directory seems to already be included...though
                    // there was code here that tried to add it (?)  If it
                    // becomes relevant, `folder` is available to prepend.
                    //
                    REBVAL *file = rebFile(item->data); // UTF-8 data
                    DS_PUSH_TRASH;
                    Move_Value(DS_TOP, file);
                    rebRelease(file);
                }
                g_slist_free(list);

                g_free(folder);
            }
        }
        else {
            // filename is in UTF-8, directory seems to be included.
            //
            REBVAL *file = rebFile(gtk_file_chooser_get_filename(chooser));
            DS_PUSH_TRASH;
            Move_Value(DS_TOP, file);
            g_free(filename);
        }
    }

    gtk_widget_destroy(dialog);

    if (REF(file))
        rebFree(name);
    if (REF(title))
        rebFree(title);

    while (gtk_events_pending()) {
        //
        // !!! Commented out code here invoked gtk_main_iteration_do(0),
        // to whom it may concern who might be interested in any of this.
        //
        gtk_main_iteration ();
    }

  #else
    UNUSED(REF(save));
    UNUSED(REF(multi));
    UNUSED(REF(file));
    UNUSED(ARG(name));
    UNUSED(REF(title));
    UNUSED(ARG(text));
    UNUSED(REF(filter));
    UNUSED(ARG(list));

    error = Error_User("REQUEST-FILE only on GTK and Windows at this time");
  #endif

    osDialogOpen = FALSE;

    // The error is broken out this way so that any allocated strings can
    // be freed before the failure.
    //
    if (error != NULL)
        fail (error);

    if (DSP == dsp_orig)
        return R_BLANK;

    if (REF(multi)) {
        //
        // For the caller's convenience, return a BLOCK! if they requested
        // /MULTI and there's even just one file.  (An empty block might even
        // be better than BLANK! for that case?)
        //
        Init_Block(D_OUT, Pop_Stack_Values(dsp_orig));
        return R_OUT;
    }

    assert(IS_FILE(DS_TOP));
    Move_Value(D_OUT, DS_TOP);

    assert(DSP == dsp_orig + 1); // should be only one pushed, so check...
    DS_DROP_TO(dsp_orig); // ...but use DS_DROP_TO just to be safe in release

    return R_OUT;
}

#ifdef TO_WINDOWS
int CALLBACK ReqDirCallbackProc(
    HWND hWnd,
    UINT uMsg,
    LPARAM lParam,
    LPARAM lpData // counterintuitively, this is provided from bi.lParam
){
    UNUSED(lParam);

    const WCHAR* dir = cast(WCHAR*, lpData);

    static REBOOL inited = FALSE;
    switch (uMsg) {
    case BFFM_INITIALIZED:
        if (dir != NULL)
            SendMessage(hWnd, BFFM_SETSELECTION, TRUE, cast(LPARAM, dir));
        SetForegroundWindow(hWnd);
        inited = TRUE;
        break;

    case BFFM_SELCHANGED:
        if (inited && dir != NULL) {
            SendMessage(hWnd, BFFM_SETSELECTION, TRUE, cast(LPARAM, dir));
            inited = FALSE;
        }
        break;
    }
    return 0;
}
#endif

//
//  request-dir*: native/export [
//
//  "Asks user to select a directory and returns it as file path"
//
//      /title
//          "Custom dialog title text"
//      text [string!]
//      /path
//          "Default directory path"
//      dir [file!]
//  ]
//
REBNATIVE(request_dir_p)
//
// !!! This came from Saphirion/Atronix R3-View.  It said "WARNING: TEMPORARY
// implementation! Used only by host-core.c Will be most probably changed
// in future."  It was only implemented for Windows, and has a dependency
// on some esoteric shell APIs which requires linking to OLE32.
//
// The code that was there has been resurrected well enough to run, but is
// currently disabled to avoid the OLE32 dependency.
{
    VIEW_INCLUDE_PARAMS_OF_REQUEST_DIR_P;

    REBCTX *error = NULL;

  #if defined(USE_WINDOWS_DIRCHOOSER)
    //
    // COM must be initialized to use SHBrowseForFolder.  BIF_NEWDIALOGSTYLE
    // is incompatible with COINIT_MULTITHREADED, the dialog will hang and
    // do nothing.
    //
    HRESULT hresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
    if (hresult == S_OK) {
        // Worked fine
    }
    else if (hresult == S_FALSE) {
        // Already initialized on this thread
    }
    else
        fail ("Failure during CoInitializeEx()");

    BROWSEINFO bi;
    bi.hwndOwner = NULL;
    bi.pidlRoot = NULL;

    WCHAR display[MAX_PATH];
    display[0] = '\0';
    bi.pszDisplayName = display; // assumed length is MAX_PATH

    if (REF(title))
        bi.lpszTitle = rebSpellingOfAllocW(NULL, ARG(text));
    else
        bi.lpszTitle = L"Please, select a directory...";

    // !!! Using BIF_NEWDIALOGSTYLE is a much nicer dialog, but it appears to
    // be incompatible with BIF_RETURNONLYFSDIRS.  Internet reports confirm
    // inconsistent behavior (seen on Windows 10) and people having to
    // manually implement the return-only-directory feature in the dialog
    // callback.
    //
    bi.ulFlags = BIF_EDITBOX
        | BIF_RETURNONLYFSDIRS
        | BIF_SHAREABLE;

    // If you pass in a directory, there is a callback registered that will
    // set that directory as the default when it comes up.  (Although the
    // field is called `bi.lParam`, it gets passed as the `lpData`)
    //
    bi.lpfn = ReqDirCallbackProc;
    if (REF(path))
        bi.lParam = cast(LPARAM, rebSpellingOfAllocW(NULL, ARG(dir)));
    else
        bi.lParam = cast(LPARAM, NULL);

    osDialogOpen = TRUE;
    LPCITEMIDLIST pFolder = SHBrowseForFolder(&bi);
    osDialogOpen = FALSE;

    WCHAR folder[MAX_PATH];
    if (pFolder == NULL)
        Init_Blank(D_OUT);
    else if (not SHGetPathFromIDList(pFolder, folder))
        error = Error_User("SHGetPathFromIDList failed");
    else {
        REBVAL *file = rebFile(folder);
        Move_Value(D_OUT, file);
        rebRelease(file);
    }

    if (REF(title))
        rebFree(cast(WCHAR*, bi.lpszTitle));
    if (REF(path))
        rebFree(cast(WCHAR*, bi.lParam));
  #else
    UNUSED(REF(title));
    UNUSED(ARG(text));
    UNUSED(REF(path));
    UNUSED(ARG(dir));

    error = Error_User("Temporary implementation of REQ-DIR only on Windows");
  #endif

    if (error != NULL)
        fail (error);

    return R_OUT;
}

#include "tmp-mod-view-last.h"


text:
CVision
=======

Computer Vision WorkBench and Utilities. Written in WinForms. Wraps OpenCV.

![ScreenShot](screenshot.png?raw=true)

Features:
- Has all OpenCV color options and color maps.
- Histogram Equalization
- 4 Blurs
- Many Morph Modes:
            ERODE,
            DILATE,
            OPEN,
            CLOSE,
            GRADIENT,
            TOPHAT,
            BLACKHAT
- You can specify morph type (RECT, CROSS, ELLIPSE) as well as kernel size.
- Other transformations:
    NOT, SOBELX SOBELY, LAPLACIAN, SCHARRX1, SCHARRY1, CANNY, THRESHOLD
- Ability to group operations into 'recipes'.
- Boolean operations.
- Intelligent contours and rotation.
- Ability to process in batch mode across a directory full of images.
- All intermediate transformations are saved.

Just built it for my purposes. There is plenty to improve.


text:
.oo-ui-icon-stripeFlow {
	background-image: url("themes/mediawiki/images/icons/stripeFlow-ltr.png");
	background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/stripeFlow-ltr.svg");
	background-image:         linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/stripeFlow-ltr.svg");
	background-image:      -o-linear-gradient(transparent, transparent), url("themes/mediawiki/images/icons/stripeFlow-ltr.png");
}
.oo-ui-icon-stripeSideMenu {
	background-image: url("themes/mediawiki/images/icons/stripeSideMenu.png");
	background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/stripeSideMenu.svg");
	background-image:         linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/stripeSideMenu.svg");
	background-image:      -o-linear-gradient(transparent, transparent), url("themes/mediawiki/images/icons/stripeSideMenu.png");
}
.oo-ui-icon-stripeSummary {
	background-image: url("themes/mediawiki/images/icons/stripeSummary-ltr.png");
	background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/stripeSummary-ltr.svg");
	background-image:         linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/stripeSummary-ltr.svg");
	background-image:      -o-linear-gradient(transparent, transparent), url("themes/mediawiki/images/icons/stripeSummary-ltr.png");
}
.oo-ui-icon-stripeToC {
	background-image: url("themes/mediawiki/images/icons/stripeToC-ltr.png");
	background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/stripeToC-ltr.svg");
	background-image:         linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/stripeToC-ltr.svg");
	background-image:      -o-linear-gradient(transparent, transparent), url("themes/mediawiki/images/icons/stripeToC-ltr.png");
}
.oo-ui-icon-viewCompact {
	background-image: url("themes/mediawiki/images/icons/viewCompact.png");
	background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/viewCompact.svg");
	background-image:         linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/viewCompact.svg");
	background-image:      -o-linear-gradient(transparent, transparent), url("themes/mediawiki/images/icons/viewCompact.png");
}
.oo-ui-icon-viewDetails {
	background-image: url("themes/mediawiki/images/icons/viewDetails-ltr.png");
	background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/viewDetails-ltr.svg");
	background-image:         linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/viewDetails-ltr.svg");
	background-image:      -o-linear-gradient(transparent, transparent), url("themes/mediawiki/images/icons/viewDetails-ltr.png");
}
.oo-ui-icon-visionSimulator {
	background-image: url("themes/mediawiki/images/icons/visionSimulator.png");
	background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/visionSimulator.svg");
	background-image:         linear-gradient(transparent, transparent), /* @embed */ url("themes/mediawiki/images/icons/visionSimulator.svg");
	background-image:      -o-linear-gradient(transparent, transparent), url("themes/mediawiki/images/icons/visionSimulator.png");
}


text:
from django import VERSION as DJANGO_VERSION
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db import models
from django.test import TestCase

from modeltrans.fields import TranslationField
from modeltrans.manager import MultilingualManager, MultilingualQuerySet
from modeltrans.translator import get_i18n_field, get_translated_models, translate_model

from .app import models as app_models

class Translating_utils(TestCase):
    def test_get_i18n_field(self):
        self.assertEqual(get_i18n_field(app_models.Blog), app_models.Blog._meta.get_field("i18n"))

        class I18nFieldTestModel(models.Model):
            test = models.CharField(max_length=20)

            class Meta:
                app_label = "django-modeltrans_tests"

        self.assertEqual(get_i18n_field(I18nFieldTestModel), None)

        class I18nFieldTestModel2(models.Model):
            test = models.CharField(max_length=20)
            i18n = models.CharField(max_length=20)

            class Meta:
                app_label = "django-modeltrans_tests"

        self.assertEqual(get_i18n_field(I18nFieldTestModel2), None)

    def test_get_translated_models(self):
        expected = {
            app_models.Article,
            app_models.Blog,
            app_models.ChildArticle,
            app_models.Category,
            app_models.Person,
            app_models.TextModel,
            app_models.NullableTextModel,
            app_models.Attribute,
            app_models.Choice,
            app_models.Challenge,
            app_models.ChallengeContent,
        }
        self.assertEqual(set(get_translated_models("app")), expected)

class TranslateModelTest(TestCase):
    def test_translate_bad_required_languages_type(self):
        class BadRequiredLanguagesType(models.Model):
            title = models.CharField(max_length=100)

            i18n = TranslationField(fields=("title",), required_languages=("es"))

            class Meta:
                app_label = "django-modeltrans_tests"

        expected_message = '"required_languages" must be a tuple, list, set or dict'
        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
            translate_model(BadRequiredLanguagesType)

    def test_translate_required_languages_dict(self):
        class RequiredLanguagesType_dict(models.Model):
            title = models.CharField(max_length=100)
            body = models.CharField(max_length=100)

            i18n = TranslationField(
                fields=("title", "body"), required_languages={"body": ["nl"], "title": ["fr", "nl"]}
            )

            class Meta:
                app_label = "django-modeltrans_tests"

        translate_model(RequiredLanguagesType_dict)

    def test_translate_required_languages_dict_bad_value(self):
        class BadRequiredLanguagesType_dict(models.Model):
            title = models.CharField(max_length=100)
            body = models.CharField(max_length=100)

            i18n = TranslationField(
                fields=("title", "body"), required_languages={"body": ["nl"], "title": "es"}
            )

            class Meta:
                app_label = "django-modeltrans_tests"

        expected_message = 'required_languages["title"] must be a tuple, list or set'
        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
            translate_model(BadRequiredLanguagesType_dict)

    def test_translate_bad_required_language(self):
        class A(models.Model):
            title = models.CharField(max_length=100)

            i18n = TranslationField(fields=("title",), required_languages=("es",))

            class Meta:
                app_label = "django-modeltrans_tests"

        expected_message = (
            'Language "es" is in required_languages on '
            'Model "A" but not in settings.MODELTRANS_AVAILABLE_LANGUAGES.'
        )
        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
            translate_model(A)

    def test_translation_unsupported_field(self):
        class IntegerModel(models.Model):
            integer = models.IntegerField()
            i18n = TranslationField(fields=("integer",))

            class Meta:
                app_label = "django-modeltrans_tests"

        expected_message = "IntegerField is not supported by django-modeltrans."

        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
            translate_model(IntegerModel)

    def test_translation_field_is_not_named_i18n(self):
        expected_message = 'TranslationField must have name "i18n"'

        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):

            class BadlyNamedTranslationField(models.Model):
                i19n = TranslationField(fields=())

                class Meta:
                    app_label = "django-modeltrans_tests"

    def test_translate_nonexisting_field(self):
        class B(models.Model):
            i18n = TranslationField(fields=("foo",))

            class Meta:
                app_label = "django-modeltrans_tests"

        expected_message = (
            'Argument "fields" to TranslationField contains an item "foo", '
            "which is not a field (missing a comma?)."
        )

        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
            translate_model(B)

    def test_translate_model_with_custom_manager(self):
        """
        Verify the MultiLingualManager gets mixed in properly
        """

        class CustomQuerySet(models.query.QuerySet):
            pass

        class CustomManager(models.Manager):
            def get_queryset(self):
                return CustomQuerySet()

            def custom_method(self):
                return "foo"

        class TestModel1(models.Model):
            name = models.CharField(max_length=100)

            i18n = TranslationField(fields=("name",))

            objects = CustomManager()

            class Meta:
                app_label = "django-modeltrans_tests"

        translate_model(TestModel1)

        self.assertIsInstance(TestModel1.objects, CustomManager)
        self.assertIsInstance(TestModel1.objects, MultilingualManager)

        self.assertEqual(TestModel1.objects.custom_method(), "foo")
        self.assertIsInstance(TestModel1.objects.all(), MultilingualQuerySet)

    def test_translate_abstract_model_with_custom_manager(self):
        self.assertIsInstance(app_models.Article.objects, MultilingualManager)

    def test_translate_model_with_existing_field(self):
        class TestModel2(models.Model):
            title = models.CharField(max_length=100)
            title_nl = models.CharField(max_length=100)

            i18n = TranslationField(fields=("title",))

            class Meta:
                app_label = "django-modeltrans_tests"

        expected_message = (
            'Error adding translation field. Model "TestModel2" already '
            'contains a field named "title_nl".'
        )

        with self.assertRaisesMessage(ImproperlyConfigured, expected_message):
            translate_model(TestModel2)

    def test_translate_model_with_non_modeltrans_i18n_field(self):
        class TestModel3(models.Model):
            title = models.CharField(max_length=100)
            i18n = models.BooleanField()

            class Meta:
                app_label = "django-modeltrans_tests"

        translate_model(TestModel3)

    def test_translate_without_virtual_fields(self):
        class TestModel4(models.Model):
            title = models.CharField(max_length=100)

            i18n = TranslationField(fields=("title",), virtual_fields=False)

            class Meta:
                app_label = "django-modeltrans_tests"

        m = TestModel4(title="foo")
        self.assertTrue(hasattr(m, "i18n"))
        self.assertFalse(hasattr(m, "title_i18n"))
        self.assertFalse(hasattr(m, "title_en"))

        if DJANGO_VERSION < (2, 2):
            expected_message = "'title_nl' is an invalid keyword argument for this function"
        else:
            expected_message = "TestModel4() got an unexpected keyword argument 'title_nl'"

        with self.assertRaisesMessage(TypeError, expected_message):
            TestModel4(title="bar", title_nl="foo")

    def test_field_gets_original_validators(self):
        def validator(value):
            if value in (None, ""):
                return

            if int(value) < 20:
                raise ValidationError("must be equal to or greater than 20.")

        class TestModel5(models.Model):
            title = models.CharField(max_length=100, validators=[validator])

            i18n = TranslationField(fields=("title",))

            class Meta:
                app_label = "django-modeltrans_tests"

        translate_model(TestModel5)

        field = TestModel5._meta.get_field("title")
        self.assertTrue(validator in field.validators)

        field = TestModel5._meta.get_field("title_nl")
        self.assertTrue(validator in field.validators)

        m = TestModel5(title="22", title_nl="10")
        with self.assertRaises(ValidationError) as e:
            m.full_clean()

        self.assertEqual(
            list(e.exception), [("title_nl", ["must be equal to or greater than 20."])]
        )

    def test_model_meta_ordering_pk(self):
        """
        When Model.Meta.ordering contains 'pk'
        """

        class OrderByPkModel(models.Model):
            title = models.CharField(max_length=100)

            i18n = TranslationField(fields=("title",))

            class Meta:
                app_label = "django-modeltrans_tests"
                ordering = ("-pk",)

        translate_model(OrderByPkModel)
        sql = str(OrderByPkModel.objects.all().query)

        self.assertIn('ORDER BY "django-modeltrans_tests_orderbypkmodel"."id" DESC', sql)


text:
package stream.flarebot.flarebot.util;

import java.util.Collection;
import java.util.Random;

public class RandomUtils {

    private static final Random random = new Random();

    public static String getRandomString(Collection<String> collection) {
        return collection.toArray(new String[collection.size()])[random.nextInt(collection.size())];
    }

    public static String getRandomStringFromArray(String[] array) {
        return array[random.nextInt(array.length)];
    }

    public static int getInt(int min, int max) {
        return random.nextInt((Math.max(max + 1, Integer.MAX_VALUE)) - min) + min;
    }
}


text:
<?php

/**
 * Cross Site Request Forgery Class
 *
 */

/**
 * Instructions:
 *
 * At your form, before the submit button put:
 * <input type="hidden" name="csrf_token" value="<?= Csrf::makeToken(); ?>" />
 *
 * This validation needed in the controller action method to validate CSRF token submitted with the form:
 *
 * if (!Csrf::isTokenValid()) {
 *     LoginModel::logout();
 *     Redirect::home();
 * }
 *
 * To get simpler code it might be better to put the logout, redirect, exit into an own (static) method.
 */
class Csrf {

    /**
     * get CSRF token and generate a new one if expired
     *
     * @access public
     * @static static method
     * @return string
     */
    public static function makeToken()
    {
        // token is valid for 1 day
        $max_time    = 60 * 60 * 24;
        $stored_time = Session::get('csrf_token_time');
        $csrf_token  = Session::get('csrf_token');

        if($max_time + $stored_time <= time() || empty($csrf_token)){
            Session::set('csrf_token', md5(uniqid(rand(), true)));
            Session::set('csrf_token_time', time());
        }

        return Session::get('csrf_token');
    }

    /**
     * checks if CSRF token in session is same as in the form submitted
     *
     * @access public
     * @static static method
     * @return bool
     */
    public static function isTokenValid()
    {
        $token = Request::post('csrf_token');
        return $token === Session::get('csrf_token') && !empty($token);
    }
}


text:
<!--
   This file is part of the X12Parser library that provides tools to
   manipulate X12 messages using Ruby native syntax.

   http://x12parser.rubyforge.org

   Copyright (C) 2009 APP Design, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

   $Id: L4.xml 78 2009-05-12 22:27:26Z ikk $
-->

<Segment name="L4" comment="To describe physical dimensions and quantities">
  <Field name="Length" type="double" min="1" max="8" comment="Largest horizontal dimension of an object measured when the object is in the upright position"/>
  <Field name="Width" type="double" min="1" max="8" comment="Shorter measurement of the two horizontal dimensions measured with the object in the upright position"/>
  <Field name="Height" type="double" min="1" max="8" comment="Vertical dimension of an object measured when the object is in the upright position"/>
  <Field name="MeasurementUnitQualifier" min="1" max="1" validation="T90" comment="Code specifying the linear dimensional unit"/>
  <Field name="Quantity" type="double" required="y" min="1" max="15" comment="Numeric value of quantity"/>
  <Field name="IndustryCode" required="y" min="1" max="30" comment="Code indicating a code from a specific industry code list"/>
</Segment>


text:
Buffered stream reader allowing asynchronous requests for a specified number of bytes.

## Purpose
Node `ReadableStream` instances allow receiving data as a sequence of asynchronous `data` events or by calling the
synchronous `read([size])`. `data` events send blocks of data as it is avaialble, but the number and size of the blocks is unpredicatable, leaving the receiver to wait for and reassemble the desired data. The `read([size])` method will return a block of the requested size if enough data is available, but if not it returns null and the caller must try again.

In some use cases--such as for message protocols with messages of known size--the reader wants to wait for a block of
a specific size.

**node-stream-reader** allows a client to request a block of a specific size via an asynchronous callback.

## API
### constructor(stream)
Create a new instance to read from `stream`. The stream is paused until calling `read` so any incoming data will be buffered.

### read(read_size, callback(err, data) [, timeout])
Read a buffer of `read_size` bytes from the stream. When enough data is available, callback is called with the requested buffer.

If the read fails with an error, the first parameter `err` will be non-null.

Sequential reads can be performed with a single reader instance.

### close()
Close the reader and remove all event listeners installed by the reader. The socket is left open and paused.

## Usage Example
```js
const TIMEOUT_MS = 5000;
var StreamReader = require('node-stream-reader');

var stream = getReadableStreamSomehow();
var reader = new StreamReader(stream);

//Read 1K from the stream, waiting up to 5 seconds if necessary
reader.read(1024, function(err, data){
	if( err ) {
		//...handle the error...
	} else {
		//...do something with the data
	}
	reader.close();
}, TIMEOUT_MS);
```


text:
//
//  QDSearchViewController.m
//  qmuidemo
//
//  Created by MoLice on 16/5/25.
//  Copyright © 2016年 QMUI Team. All rights reserved.
//

#import "QDSearchViewController.h"

#import "QDCityList.h"
#import "QDCityGroup.h"
#import "QDCityModle.h"

#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

#import "DSectionIndexView.h"
#import "DSectionIndexItemView.h"

@interface QDSearchViewController ()<QMUISearchControllerDelegate,CLLocationManagerDelegate,DSectionIndexViewDataSource,DSectionIndexViewDelegate>

//@property(nonatomic,strong) NSArray<NSString *> *keywords;

@property(nonatomic,strong) NSArray *cityArray;
@property(nonatomic,retain)CLLocationManager *locationManager;
@property(nonatomic,strong) NSString *currentCity;

/**
 tableview右侧索引
 */
@property(nonatomic,strong) NSMutableArray *indexArray;
/**
 tableview右侧索引View
 */
@property (retain, nonatomic) DSectionIndexView *sectionIndexView;

@property(nonatomic,strong) NSMutableArray *searchResultsKeywords;
@property(nonatomic,strong) QMUISearchController *mySearchController;
@end

@implementation QDSearchViewController

- (instancetype)initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {
        self.cityArray = [[QDCityModle sharedObject] citiesArrary];
        self.searchResultsKeywords = [[NSMutableArray alloc] init];

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"城市选择"];
    [self locationStart];
    self.mySearchController = [[QMUISearchController alloc] initWithContentsViewController:self];
    self.mySearchController.searchResultsDelegate = self;
    self.tableView.tableHeaderView = self.mySearchController.searchBar;
    [self initSectionIndexView];
}

- (void)viewWillAppear:(BOOL)animated {
    [self.sectionIndexView reloadItemViews];
}

#pragma mark - <QMUITableViewDataSource,QMUITableViewDelegate>

- (BOOL)shouldShowSearchBarInTableView:(QMUITableView *)tableView {
    return YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.tableView) {
        return self.cityArray.count + 3;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        if (section == 0) {
            return 1;
        }else if (section == 1) {
            return 1;
        }else if (section == 2) {
            return 1;
        }else {
            //
            QDCityGroup *group = self.cityArray[section - 3];
            return group.arrayCitys.count;
        }

    }
    return self.searchResultsKeywords.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    QMUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[QMUITableViewCell alloc] initForTableView:self.tableView withReuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    if (tableView == self.tableView) {
        if (indexPath.section == 0) {
            cell.textLabel.text = self.currentCity?self.currentCity:@"定位中...";
        }else if (indexPath.section == 1) {
            cell.textLabel.text = @"无历史";
        }else if (indexPath.section == 2) {
            cell.textLabel.text = @"无热门";
        }else {
            QDCityGroup *group = self.cityArray[indexPath.section - 3];
            QDCityList *city = group.arrayCitys[indexPath.row];
            cell.textLabel.text = city.cityName;
        }

    } else {
        QDCityList *city = self.searchResultsKeywords[indexPath.row];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:city.cityName attributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
        NSRange range = [city.cityName rangeOfString:self.mySearchController.searchBar.text];
        if (range.location != NSNotFound) {
            [attributedString addAttributes:@{NSForegroundColorAttributeName: UIColorBlue} range:range];
        }
        cell.textLabel.attributedText = attributedString;
    }

    [cell updateCellAppearanceWithIndexPath:indexPath];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (tableView == self.tableView) {
        if (section == 0) {
            return @"当前城市";
        }else if (section == 1) {
            return @"历史记录";
        }else if (section == 2) {
            return @"热门城市";
        }else {
            QDCityGroup *group = self.cityArray[section - 3];
            return group.groupName;
        }
    }else {
        return @"搜索结果";
    }

}

#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.tableView) {

    }else {

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 24.0f;
}

#pragma mark <IndexView>
#define kSectionIndexWidth 30.f
#define kSectionIndexHeight ([UIScreen mainScreen].bounds.size.height - 64)
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
- (void)initSectionIndexView {
    // Custom initialization
    _sectionIndexView = [[DSectionIndexView alloc] init];
    _sectionIndexView.frame = CGRectMake(kScreenWidth - kSectionIndexWidth, 64, kSectionIndexWidth, kSectionIndexHeight);
    _sectionIndexView.backgroundColor = [UIColor clearColor];
    _sectionIndexView.dataSource = self;
    _sectionIndexView.delegate = self;
    _sectionIndexView.isShowCallout = YES;
    _sectionIndexView.calloutViewType = CalloutViewTypeForQQMusic;
    _sectionIndexView.calloutDirection = SectionIndexCalloutDirectionLeft;
    _sectionIndexView.calloutMargin = 100.f;
    [self.view addSubview:self.sectionIndexView];
}

- (NSMutableArray *)indexArray {
    if (!_indexArray) {
        _indexArray = [[NSMutableArray alloc] initWithObjects:@"@", @"#", @"$", @"*", nil];
        for (QDCityGroup *group in _cityArray) {
            [_indexArray addObject:group.groupName];
        }
    }
    return _indexArray;
}

#pragma mark DSectionIndexViewDataSource && delegate method
- (NSInteger)numberOfItemViewForSectionIndexView:(DSectionIndexView *)sectionIndexView
{
//    return self.tableView.numberOfSections;
    return self.indexArray.count;
}

- (DSectionIndexItemView *)sectionIndexView:(DSectionIndexView *)sectionIndexView itemViewForSection:(NSInteger)section
{
    DSectionIndexItemView *itemView = [[DSectionIndexItemView alloc] init];

    itemView.titleLabel.text = [self.indexArray objectAtIndex:section];
    itemView.titleLabel.font = [UIFont systemFontOfSize:12];
    itemView.titleLabel.textColor = [UIColor redColor];
    itemView.titleLabel.highlightedTextColor = [UIColor grayColor];
    itemView.titleLabel.shadowColor = [UIColor whiteColor];
    itemView.titleLabel.shadowOffset = CGSizeMake(0, 1);
    return itemView;

}

- (UIView *)sectionIndexView:(DSectionIndexView *)sectionIndexView calloutViewForSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc] init];

    label.frame = CGRectMake(0, 0, 80, 80);

    label.backgroundColor = [UIColor whiteColor];
    label.textColor = [UIColor greenColor];
    label.font = [UIFont boldSystemFontOfSize:36];
    label.text = [self.indexArray objectAtIndex:section];
    label.textAlignment = NSTextAlignmentCenter;

    [label.layer setCornerRadius:label.frame.size.width/2];
    [label.layer setBorderColor:[UIColor darkGrayColor].CGColor];
    [label.layer setBorderWidth:3.0f];
    [label.layer setShadowColor:[UIColor blackColor].CGColor];
    [label.layer setShadowOpacity:0.8];
    [label.layer setShadowRadius:5.0];
    [label.layer setShadowOffset:CGSizeMake(2.0, 2.0)];

    return label;
}

- (NSString *)sectionIndexView:(DSectionIndexView *)sectionIndexView
               titleForSection:(NSInteger)section
{
    return [self.indexArray objectAtIndex:section];
}

- (void)sectionIndexView:(DSectionIndexView *)sectionIndexView didSelectSection:(NSInteger)section
{
    if (section == 0) {
        [self.tableView qmui_scrollToTopAnimated:YES];
    }else {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section-1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }

}

#pragma mark - <QMUISearchControllerDelegate>

- (void)searchController:(QMUISearchController *)searchController updateResultsForSearchString:(NSString *)searchString {
    [self.searchResultsKeywords removeAllObjects];

    for (QDCityGroup *group in self.cityArray){
        for (QDCityList *city in group.arrayCitys) {
            if ([city.cityName qmui_includesString:searchString] || [city.pinyin qmui_includesString:searchString] || [city.initials qmui_includesString:searchString]) {
                [self.searchResultsKeywords addObject:city];
            }
        }
    }
    [searchController.tableView reloadData];

    if (self.searchResultsKeywords.count == 0) {
        [searchController showEmptyViewWithText:@"没有匹配结果" detailText:nil buttonTitle:nil buttonAction:NULL];
    } else {
        [searchController hideEmptyView];
    }
}

- (void)willPresentSearchController:(QMUISearchController *)searchController {
    [QMUIHelper renderStatusBarStyleDark];
}

- (void)willDismissSearchController:(QMUISearchController *)searchController {
    BOOL oldStatusbarLight = NO;
    if ([self respondsToSelector:@selector(shouldSetStatusBarStyleLight)]) {
        oldStatusbarLight = [self shouldSetStatusBarStyleLight];
    }
    if (oldStatusbarLight) {
        [QMUIHelper renderStatusBarStyleLight];
    } else {
        [QMUIHelper renderStatusBarStyleDark];
    }
}

#pragma mark 开始定位

- (void)locationStart {
    //判断定位操作是否被允许
    if([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init] ;
        self.locationManager.delegate = self;
        //设置定位精度
        self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;//每隔多少米定位一次(这里的设置为每隔百米)
        if (NSFoundationVersionNumber >= NSFoundationVersionNumber_iOS_8_0) {
            //使用应用程序期间允许访问位置数据
            [self.locationManager requestWhenInUseAuthorization];
        }
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        NSLog(@"%@",@"定位服务当前可能尚未打开,请设置打开!");
    }
}

#pragma mark - CoreLocation Delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *) locations {
    //系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
    [self.locationManager stopUpdatingLocation];
    //此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,如果不想让其持续更新位置,则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error) {
         if (array.count >0) {
             CLPlacemark *placemark = [array objectAtIndex:0];
             //获取城市  subLocality(xx区)   placemark.name (无锡惠山经济开发区) placemark.administrativeArea (江苏省)
             NSString *currCity = placemark.locality;
             if (!currCity) {
                 //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                 currCity = placemark.administrativeArea;
             }
             self.currentCity = currCity;
             [self.tableView reloadData];
         }else if (error ==nil && [array count] == 0) {
             NSLog(@"No results were returned.");
         }else if (error !=nil) {
             NSLog(@"An error occurred = %@", error);
         }
     }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if (error.code ==kCLErrorDenied) {
        // 提示用户出错原因,可按住Option键点击 KCLErrorDenied的查看更多出错信息,可打印error.code值查找原因所在
    }
}

@end


text:
require 'fileutils'
require 'yaml'

require 'rubygems'
require 'closure-compiler'
require "yui/compressor"
require 'sprockets'

class Bundle
  DIST_DIR = 'dist'
  SRC_DIR = 'src'

  attr_reader :path

  def initialize
    @path = "#{SRC_DIR}/question_chain.js"
  end

  def bundle!
    FileUtils.mkdir_p(DIST_DIR)

    secretary = Sprockets::Secretary.new(
      :load_path => [SRC_DIR],
      :source_files => [path],
      :expand_paths => false
    )
    concatenation = secretary.concatenation
    concatenation.save_to(bundle_path)
  end

  def bundle_path
    "#{DIST_DIR}/question_chain-#{version}.js"
  end

  def minify!
    file = File.open(bundle_path, 'r')
    compressor = YUI::JavaScriptCompressor.new(:munge => true)
    minified = compressor.compress(file.read)
    File.open(minify_path, 'w') do |f|
      f.write(extract_head(file))
      f.write(minified)
    end
  end

  def minify_path
    "#{DIST_DIR}/question_chain-#{version}.min.js"
  end

  def version
    @version ||= YAML.load_file("#{SRC_DIR}/constants.yml")['VERSION']
  end

  private
    def extract_head(file)
      head = ''
      file.rewind
      while (line = file.gets)
        if line =~ /^[\/\s]/
          head << line
        else
          break
        end
      end
      head
    end
end


text:
class 'FirstPerson'

function FirstPerson:__init()
	self.enabled = false

	Events:Subscribe( "CalcView", self, self.CalcView )
	Events:Subscribe( "LocalPlayerChat", self, self.LocalPlayerChat )

    Events:Subscribe( "ModuleLoad", self, self.ModuleLoad )
    Events:Subscribe( "ModuleUnload", self, self.ModuleUnload )
end

function FirstPerson:CalcView()
	if not self.enabled then return end

	local position = LocalPlayer:GetBonePosition( "ragdoll_Head" )

	if not LocalPlayer:InVehicle() then
		position = position + (Camera:GetAngle() * Vector3( 0, 0.25, 0.2 ))
	end

	Camera:SetPosition( position )
end

function FirstPerson:LocalPlayerChat( args )
	if args.text == "/fp" then
		self.enabled = not self.enabled
		return false
	end
end

function FirstPerson:ModuleLoad()
	Events:Fire( "HelpAddItem",
        {
            name = "First-Person View",
            text =
                "The first-person script lets you play JC2 in first-person mode.\n\n" ..
                "To toggle it, type /fp in chat."
        } )
end

function FirstPerson:ModuleUnload()
    Events:Fire( "HelpRemoveItem",
        {
            name = "First-Person View"
        } )
end

firstperson = FirstPerson()


text: <?php echo $error; ?>


text:
<?php

namespace PHPExiftool\Driver\Tag\CanonVRD;

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

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

    protected $Id = 217;

    protected $Name = 'CropCircleRadius';

    protected $FullName = 'CanonVRD::Ver2';

    protected $GroupName = 'CanonVRD';

    protected $g0 = 'CanonVRD';

    protected $g1 = 'CanonVRD';

    protected $g2 = 'Image';

    protected $Type = 'int16s';

    protected $Writable = true;

    protected $Description = 'Crop Circle Radius';

}


text:
package url

import (
	"math"
	"path/filepath"

	"github.com/pkg/errors"

	"github.com/mutagen-io/mutagen/pkg/comparison"
	"github.com/mutagen-io/mutagen/pkg/url/forwarding"
)

// EnsureValid ensures that URL's invariants are respected.
func (u *URL) EnsureValid() error {
	// Ensure that the URL is non-nil.
	if u == nil {
		return errors.New("nil URL")
	}

	// Ensure that the kind is supported.
	if !u.Kind.Supported() {
		return errors.New("unsupported URL kind")
	}

	// Validate the User, Host, Port, and Environment components based on
	// protocol.
	if u.Protocol == Protocol_Local {
		if u.User != "" {
			return errors.New("local URL with non-empty username")
		} else if u.Host != "" {
			return errors.New("local URL with non-empty hostname")
		} else if u.Port != 0 {
			return errors.New("local URL with non-zero port")
		} else if len(u.Environment) != 0 {
			return errors.New("local URL with environment variables")
		}
	} else if u.Protocol == Protocol_SSH {
		if u.Host == "" {
			return errors.New("SSH URL with empty hostname")
		} else if u.Port > math.MaxUint16 {
			return errors.New("SSH URL with invalid port")
		} else if len(u.Environment) != 0 {
			return errors.New("SSH URL with environment variables")
		}
	} else if u.Protocol == Protocol_Docker {
		// In the case of Docker, we intentionally avoid validating environment
		// variables since the values used could change over time. Since we
		// default to empty values for unspecified environment variables, this
		// works out fine, at least so long as Docker continues to treat empty
		// environment variables the same as unspecified ones.
		if u.Host == "" {
			return errors.New("Docker URL with empty container identifier")
		} else if u.Port != 0 {
			return errors.New("Docker URL with non-zero port")
		}
	} else {
		return errors.New("unknown or unsupported protocol")
	}

	// Validate the path component depending on the URL kind.
	if u.Kind == Kind_Synchronization {
		// Ensure the path is non-empty.
		if u.Path == "" {
			return errors.New("empty path")
		}

		// If this is a local URL, then ensure that the path is absolute.
		if u.Protocol == Protocol_Local && !filepath.IsAbs(u.Path) {
			return errors.New("local URL with relative path")
		}

		// If this is a Docker URL, we can actually do a bit of additional
		// validation.
		if u.Protocol == Protocol_Docker {
			if !(u.Path[0] == '/' || u.Path[0] == '~' || isWindowsPath(u.Path)) {
				return errors.New("incorrect first path character")
			}
		}
	} else if u.Kind == Kind_Forwarding {
		// Parse the forwarding endpoint URL to ensure that it's valid.
		protocol, address, err := forwarding.Parse(u.Path)
		if err != nil {
			return errors.Wrap(err, "invalid forwarding endpoint URL")
		}

		// If this is a local URL and represents a Unix domain socket endpoint,
		// then ensure that the socket path is absolute.
		if u.Protocol == Protocol_Local && protocol == "unix" && !filepath.IsAbs(address) {
			return errors.New("local Unix domain socket URL with relative path")
		}

		// TODO: It would be nice to perform some sort of validation on Windows
		// named pipe addresses, but there's not much we can do because the
		// allowed formats vary between source and destination endpoints (so
		// we'd have to weave that information through this function). The only
		// difference is that the ServerName component (see the link below) must
		// be "." for source endpoints but can also name a remote server in the
		// case of destination endpoints. But that's not really the biggest
		// issue. The problem is that the name specification is kind of vague.
		// It says that the PipeName component (again, see the link below) "can
		// include any character other than a backslash, including numbers and
		// special characters", but it doesn't mention whitespace characters
		// (for example a newline character), which, as far as I'm aware, are
		// not allowed. It also limits the "entire pipe name string" to 256
		// characters, but it's not clear if this refers to the PipeName
		// component or the entire address. Finding an appropriate matcher for
		// possible server names is also an uphill battle. This might be
		// specified in the UNC specification. In the end though, we're probably
		// just better off letting the OS decide what to accept and simply
		// returning its errors directly. For further reading, see:
		// https://docs.microsoft.com/en-us/windows/win32/ipc/pipe-names
	}

	// Success.
	return nil
}

// Supported returns whether or not a URL kind is supported.
func (k Kind) Supported() bool {
	switch k {
	case Kind_Synchronization:
		return true
	case Kind_Forwarding:
		return true
	default:
		return false
	}
}

// Equal returns whether or not the URL is equivalent to another. The result of
// this method is only valid if both URLs are valid.
func (u *URL) Equal(other *URL) bool {
	// Ensure that both are non-nil.
	if u == nil || other == nil {
		return false
	}

	// Perform an equivalence check.
	return u.Kind == other.Kind &&
		u.Protocol == other.Protocol &&
		u.User == other.User &&
		u.Host == other.Host &&
		u.Port == other.Port &&
		u.Path == other.Path &&
		comparison.StringMapsEqual(u.Environment, other.Environment) &&
		comparison.StringMapsEqual(u.Parameters, other.Parameters)
}


text:
package com.jetbrains.python.psi.types.functionalParser;

import com.intellij.openapi.util.Pair;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
* @author vlan
*/
public class ForwardDeclaration<R, T> extends FunctionalParserBase<R, T> {
  private FunctionalParser<R, T> myParser = null;

  @NotNull
  public static <R, T> ForwardDeclaration<R, T> create() {
    return new ForwardDeclaration<R, T>();
  }

  @NotNull
  public ForwardDeclaration<R, T> define(@NotNull FunctionalParser<R, T> parser) {
    myParser = parser;
    return this;
  }

  @NotNull
  @Override
  public Pair<R, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
    if (myParser != null) {
      return myParser.parse(tokens, state);
    }
    throw new IllegalStateException("Undefined forward parser declaration");
  }
}


text:
from setuptools import setup, find_packages

with open('README.md') as f:
    long_description = ''.join(f.readlines())

def get_requirements():
    with open("requirements.txt") as f:
        return f.readlines()

setup(
    author="Martin Chovanec",
    author_email="chovanecm@gmail.com",
    classifiers=[
        "Development Status :: 3 - Alpha",
        "License :: OSI Approved :: MIT License",
        "Natural Language :: English",
        "Operating System :: OS Independent",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
        "Programming Language :: Python :: 3.5",
    ],
    description="Genetic algorithm library",
    long_description=long_description,
    license="MIT License",
    url="https://github.com/chovanecm/python-genetic-algorithm",
    name="mchgenalg",
    keywords="genetic algorithm",
    packages=find_packages(),
#    entry_points={
#        "console_scripts": [
#            "sacredboard = sacredboard.webapp:run"
#        ]
#    },
    install_requires=get_requirements(),
    #    setup_requires=["numpy"],
    tests_require=["pytest"],
    version="0.2"
)


text:
module WinJSTests {

    "use strict";

    var COUNT = 6;

    function verifyDisplayedItem(flipView, rawData) {
        LiveUnit.LoggingCore.logComment("Verifying displayed page is correct");
        LiveUnit.Assert.isTrue(currentPageInView(flipView));
        flipView.itemTemplate.verifyOutput(getDisplayedElement(flipView), rawData);
    }

    function eventsTest(element, flipView, rawData, complete, useL0DomEvent) {
        var gotVisibilityChangedTrue,
            gotVisibilityChangedFalse,
            outgoingElement,
            expectedIncomingElement;

        function resetResults() {
            gotVisibilityChangedTrue = false;
            gotVisibilityChangedFalse = false;
            outgoingElement = null;
            expectedIncomingElement = null;
        }

        function verifyExpectedResults(targetIndex) {
            LiveUnit.Assert.isTrue(gotVisibilityChangedTrue);
            LiveUnit.Assert.isTrue(gotVisibilityChangedFalse);
            verifyDisplayedItem(flipView, rawData[targetIndex]);
            LiveUnit.Assert.isFalse(elementInView(flipView, outgoingElement));
            resetResults();
        }

        function customAnimation(outgoing, incoming) {
            outgoing = getElementFromContainer(outgoing);
            incoming = getElementFromContainer(incoming);
            LiveUnit.LoggingCore.logComment("Navigation animation triggered");
            LiveUnit.Assert.areEqual(expectedIncomingElement, incoming);
            expectedIncomingElement = null;
            outgoingElement = outgoing;
            return WinJS.Promise.timeout(25);
        }
        flipView.setCustomAnimations({
            next: customAnimation,
            previous: customAnimation,
            jump: customAnimation
        });

        function pageVisibilityHandler(e) {
            if (e.detail.visible) {
                LiveUnit.Assert.isFalse(gotVisibilityChangedTrue);
                gotVisibilityChangedTrue = true;
                expectedIncomingElement = e.target;
            } else {
                LiveUnit.Assert.isFalse(gotVisibilityChangedFalse);
                gotVisibilityChangedFalse = true;
                LiveUnit.Assert.areEqual(outgoingElement, e.target);
            }
        }

        if (useL0DomEvent) {
            flipView.onpagevisibilitychanged = pageVisibilityHandler;
        } else {
            flipView.addEventListener("pagevisibilitychanged", pageVisibilityHandler, false);
        }

        var tests = [
            function () {
                LiveUnit.Assert.areEqual(0, flipView.currentPage);
                resetResults();
                verifyDisplayedItem(flipView, rawData[0]);
                LiveUnit.Assert.isTrue(flipView.next());
            },
            function () {
                LiveUnit.Assert.areEqual(1, flipView.currentPage);
                verifyExpectedResults(1);
                LiveUnit.Assert.isTrue(flipView.next());
            },
            function () {
                LiveUnit.Assert.areEqual(2, flipView.currentPage);
                verifyExpectedResults(2);
                flipView.currentPage = 5;
            },
            function () {
                LiveUnit.Assert.areEqual(5, flipView.currentPage);
                verifyExpectedResults(5);
                flipView.currentPage = 6;
                return true;
            },
            function () {
                LiveUnit.Assert.areEqual(5, flipView.currentPage);
                verifyDisplayedItem(flipView, rawData[5]);
                LiveUnit.Assert.isFalse(gotVisibilityChangedTrue);
                LiveUnit.Assert.isFalse(gotVisibilityChangedFalse);
                LiveUnit.Assert.isFalse(flipView.next());
                return true;
            },
            function () {
                LiveUnit.Assert.areEqual(5, flipView.currentPage);
                verifyDisplayedItem(flipView, rawData[5]);
                LiveUnit.Assert.isFalse(gotVisibilityChangedTrue);
                LiveUnit.Assert.isFalse(gotVisibilityChangedFalse);
                flipView.currentPage = 0;
            },
            function () {
                LiveUnit.Assert.areEqual(0, flipView.currentPage);
                verifyExpectedResults(0);
                complete();
            }
        ];

        runFlipViewTests(flipView, tests);
    }

    export class FlipViewEventsTests {

        setUp() {
            LiveUnit.LoggingCore.logComment("In setup");
            var newNode = document.createElement("div");
            newNode.id = "BasicFlipView";
            newNode.style.width = "400px";
            newNode.style.height = "400px";
            document.body.appendChild(newNode);
        }

        tearDown() {
            LiveUnit.LoggingCore.logComment("In tearDown");
            var element = document.getElementById("BasicFlipView");
            if (element) {
                WinJS.Utilities.disposeSubTree(element);
                document.body.removeChild(element);
            }
        }

    }

    function generate(name, testFunction) {
        function generateTest(orientation, useL0DomEvent) {
            FlipViewEventsTests.prototype[name + "_" + orientation + (useL0DomEvent ? "_useL0DomEvent" : "")] = function (complete) {
                var element = document.getElementById("BasicFlipView"),
                    testData = createArraySource(COUNT, ["400px"], ["400px"]),
                    rawData = testData.rawData,
                    options = { itemDataSource: testData.dataSource, itemTemplate: basicInstantRenderer, orientation: orientation };

                var flipView = new WinJS.UI.FlipView(element, options);
                testFunction(element, flipView, rawData, complete, useL0DomEvent);
            };
        }

        [true, false].forEach(function (useL0DomEvent) {
            generateTest("horizontal", useL0DomEvent);
            generateTest("vertical", useL0DomEvent);
        });

    }
    generate("testFlipViewPageEvents", eventsTest);
}
LiveUnit.registerTestClass("WinJSTests.FlipViewEventsTests");


text:
Inductive logic game

## Getting Started

To bring project alive (for example after `git clone`):

```sh
npm install
bower install
grunt devel
```

Developing the project (after brought alive):

Start server with `amber serve` and go to `http://localhost:4000/` in your browser and follow the instructions


text:
//
//  SPPillAttachmentCell.h
//  sequel-pro
//
//  Created by Max Lohrmann on 01.11.15.
//  Copyright (c) 2015 Max Lohrmann. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person
//  obtaining a copy of this software and associated documentation
//  files (the "Software"), to deal in the Software without
//  restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following
//  conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//  OTHER DEALINGS IN THE SOFTWARE.
//
//  More info at <https://github.com/sequelpro/sequelpro>

#import <Foundation/Foundation.h>

/**
 * This is a simple TextAttachmentCell which takes the stringValue
 * and displays it in a "pill", much like the tokens in an NSTokenTextField.
 *
 * It is designed to be used with static labels rather than inside user input text fields.
 *
 * To use it:
 *
 * NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
 * SPPillAttachmentCell *cell   = [[SPPillAttachmentCell alloc] init];
 * [cell setStringValue:@"..."];
 * [attachment setAttachmentCell:[cell autorelease];
 * NSAttributedString *att = [NSAttributedString attributedStringWithAttachment:[attachment autorelease]];
 * [otherAttributedString appendAttributedString:att];
 *
 */
@interface SPPillAttachmentCell : NSTextAttachmentCell {
    NSColor *_borderColor;
    NSGradient *_gradient;
}
@end