text:
package functional.rdf;

import functional.ApplicationTests;
import org.junit.Test;
import play.libs.ws.WSResponse;

import static org.fest.assertions.Assertions.assertThat;
import static play.mvc.Http.Status.OK;

public class RdfSanityTest extends ApplicationTests {
    public static final String TEST_JSON = "{\"test-register\":\"testregisterkey\",\"name\":\"The Entry\",\"key1\": \"value1\",\"key2\": [\"A\",\"B\"]}";
    public static final String EXPECTED_HASH = "4686f89b9c983f331c7deef476fda719148de4fb";

    public static final String EXPECTED_TURTLE = "@prefix field: <http://field.openregister.org/field/>.\n" +
            "\n" +
            "<http://localhost:8888/hash/4686f89b9c983f331c7deef476fda719148de4fb>\n" +
            "  field:test-register <http://localhost:8888/test-register/testregisterkey> ;\n" +
            "  field:name \"The Entry\" ;\n" +
            "  field:key1 \"value1\" ;\n" +
            "  field:key2 \"A\", \"B\" .\n";
    public static final String TEXT_TURTLE = "text/turtle; charset=utf-8";

    @Test
    public void testFindOneByKey() throws Exception {
        postJson("/create", TEST_JSON);

        WSResponse response = getByKV("key1", "value1", "ttl");
        assertThat(response.getStatus()).isEqualTo(OK);
        assertThat(response.getHeader("Content-type")).isEqualTo("text/turtle; charset=utf-8");
        assertThat(response.getBody()).isEqualTo(EXPECTED_TURTLE);
    }

    @Test
    public void testFindOneByHash() throws Exception {
        postJson("/create", TEST_JSON);

        WSResponse response = getByHash(EXPECTED_HASH, "ttl");

        assertThat(response.getStatus()).isEqualTo(OK);
        assertThat(response.getHeader("Content-type")).isEqualTo(TEXT_TURTLE);
        assertThat(response.getBody()).isEqualTo(EXPECTED_TURTLE);
    }

    private static final String firstDoc = "<http://localhost:8888/hash/39837068f586ab19bcb2b5f2408b024438e75c43>\n" +
            "  field:test-register <http://localhost:8888/test-register/testregisterkey1> ;\n" +
            "  field:name \"The Entry1\" ;\n" +
            "  field:key1 \"value1\" ;\n" +
            "  field:key2 \"A\", \"B\" .\n";
    private static final String secondDoc = "<http://localhost:8888/hash/b0c762fd934019b14a3ec88d775c6a037a09a74e>\n" +
            "  field:test-register <http://localhost:8888/test-register/testregisterkey2> ;\n" +
            "  field:name \"The Entry2\" ;\n" +
            "  field:key1 \"value2\" ;\n" +
            "  field:key2 \"C\", \"D\" .\n";
    private static final String ttlPrefix = "@prefix field: <http://field.openregister.org/field/>.\n";

    @Test
    public void testSearchAndRenderListOfResults() throws Exception {
        postJson("/create", "{\"test-register\":\"testregisterkey2\",\"name\":\"The Entry2\",\"key1\": \"value2\",\"key2\": [\"C\",\"D\"]}");
        postJson("/create", "{\"test-register\":\"testregisterkey1\",\"name\":\"The Entry1\",\"key1\": \"value1\",\"key2\": [\"A\",\"B\"]}");

        WSResponse response = get("/search?_query=&_representation=ttl");
        assertThat(response.getStatus()).isEqualTo(OK);
        assertThat(response.getHeader("Content-type")).isEqualTo(TEXT_TURTLE);
        assertThat(response.getBody()).contains(firstDoc);
        assertThat(response.getBody()).contains(secondDoc);
        assertThat(response.getBody()).contains(ttlPrefix);
    }
}


text:
"""The edx_lint write command."""

from edx_lint.write import write_file

def write_main(argv):
    """
    write FILENAME
        Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.
    """
    if len(argv) != 1:
        print("Please provide the name of a file to write.")
        return 1

    filename = argv[0]
    ret = write_file(filename, output_fn=print)
    return ret

redpajama_set_name: RedPajamaGithub


text:
package com.spider.tool;
//=======================================================
//		          .----.
//		       _.'__    `.
//		   .--(^)(^^)---/!\
//		 .' @          /!!!\
//		 :         ,    !!!!
//		  `-..__.-' _.-\!!!/
//		        `;_:    `"'
//		      .'"""""`.
//		     /,  ya ,\\
//		    //狗神保佑\\
//		    `-._______.-'
//		    ___`. | .'___
//		   (______|______)
//=======================================================

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class LRUCache<K> {
    private final LinkedHashMap<K, Object> map;
    private volatile int size;
    private int maxSize;
    private volatile AtomicInteger putCount=new AtomicInteger(0);
    private volatile AtomicInteger evictionCount=new AtomicInteger(0);;
    private volatile AtomicInteger hitCount=new AtomicInteger(0);;
    private volatile AtomicInteger missCount=new AtomicInteger(0);;
    private final Object value = new Object();

    public LRUCache(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }
        this.maxSize = maxSize;
        this.map = new LinkedHashMap(maxSize, 0.75f, true);
    }

    public void init(List<K> list) {
        list.stream().forEach(a -> this.map.put(a, value));
    }

    public void resize(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }

        synchronized (this) {
            this.maxSize = maxSize;
        }
        trimToSize(maxSize);
    }

    public final Boolean get(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        Object mapValue;
        synchronized (this) {
            mapValue = map.get(key);
            if (mapValue != null) {
                hitCount.incrementAndGet();
                return true;
            }
            this.put(key);
            missCount.incrementAndGet();
        }
        return false;
    }

    public final Object put(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        Object previous;
        synchronized (this) {
            putCount.incrementAndGet();
            size += safeSizeOf(key, value);
            previous = map.put(key, value);
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }

        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }

        trimToSize(maxSize);
        return previous;
    }

    public void trimToSize(int maxSize) {
        while (true) {
            K key;
            synchronized (this) {
                if (size < 0 || (map.isEmpty() && size != 0)) {
                    throw new IllegalStateException(getClass().getName()
                            + ".sizeOf() is reporting inconsistent results!");
                }

                if (size <= maxSize || map.isEmpty()) {
                    break;
                }

                Map.Entry<K, Object> toEvict = map.entrySet().iterator().next();
                key = toEvict.getKey();
                map.remove(key);
                size -= safeSizeOf(key, value);
                evictionCount.intValue();
            }

            entryRemoved(true, key, value, null);
        }
    }

    public final Object remove(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        Object previous;
        synchronized (this) {
            previous = map.remove(key);
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }

        if (previous != null) {
            entryRemoved(false, key, previous, null);
        }

        return previous;
    }

    protected void entryRemoved(boolean evicted, K key, Object oldValue, Object newValue) {
        remove(key);
    }

    protected Object create(K key) {
        return null;
    }

    private int safeSizeOf(K key, Object value) {
        int result = sizeOf(key, value);
        if (result < 0) {
            throw new IllegalStateException("Negative size: " + key + "=" + value);
        }
        return result;
    }

    protected int sizeOf(K key, Object value) {
        return 1;
    }

    public final void evictAll() {
        trimToSize(-1);
    }

    public synchronized final int mapSize() {
        return this.map.size();
    }

    public synchronized final int size() {
        return size;
    }

    public synchronized final int maxSize() {
        return maxSize;
    }

    public synchronized final int hitCount() {
        return hitCount.intValue();
    }

    public synchronized final int missCount() {
        return missCount.intValue();
    }

    public synchronized final int putCount() {
        return putCount.intValue();
    }

    public synchronized final int evictionCount() {
        return evictionCount.intValue();
    }

    public synchronized final Map<K, Object> snapshot() {
        return new LinkedHashMap<K, Object>(map);
    }

    @Override
    public final String toString() {
        int accesses = hitCount.intValue() + missCount.intValue();
        int hitPercent = accesses != 0 ? (100 * hitCount.intValue() / accesses) : 0;
        return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",
                maxSize, hitCount.intValue(), missCount.intValue(), hitPercent);
    }
}


text:
package ru.carabi.server.entities;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author sasha
 */
@Entity
@Table(name="QUERY_CATEGORY")
public class QueryCategory implements Serializable {

	@Id
	@Column(name="CATEGORY_ID")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	private String name;
	private String description;

	@Column(name="PARENT_ID")
	private Integer parentId;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Integer getParentId() {
		return parentId;
	}

	public void setParentId(Integer parentId) {
		this.parentId = parentId;
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Psalliota arvensis var. buchananii W.G. Sm.

### Remarks
null


text:
namespace TheXDS.MCART.ValueConverters;
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using TheXDS.MCART.Types.Extensions;

/// <summary>
/// Devuelve <see langword="true" /> si el elemento a convertir es <see langword="null" />
/// </summary>
public sealed class NullToBooleanConverter : IValueConverter
{
    /// <summary>
    /// Obtiene un <see cref="Visibility" /> a partir del valor.
    /// </summary>
    /// <param name="value">Objeto a convertir.</param>
    /// <param name="targetType">Tipo del destino.</param>
    /// <param name="parameter">
    /// Parámetros personalizados para este <see cref="IValueConverter" />.
    /// </param>
    /// <param name="culture">
    /// <see cref="CultureInfo" /> a utilizar para la conversión.
    /// </param>
    /// <returns>
    /// <see cref="Visibility.Visible" /> si el elemento es
    /// <see langword="null" />, <see cref="Visibility.Collapsed" /> en caso
    /// contrario.
    /// </returns>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value is null;
    }

    /// <summary>
    /// Implementa <see cref="IValueConverter.ConvertBack" />.
    /// </summary>
    /// <param name="value">Objeto a convertir.</param>
    /// <param name="targetType">Tipo del destino.</param>
    /// <param name="parameter">
    /// Parámetros personalizados para este <see cref="IValueConverter" />.
    /// </param>
    /// <param name="culture">
    /// <see cref="CultureInfo" /> a utilizar para la conversión.
    /// </param>
    /// <exception cref="InvalidCastException">
    /// Se produce si <paramref name="value" /> no es un <see cref="bool" />.
    /// </exception>
    /// <exception cref="TypeLoadException">
    /// Se produce si <paramref name="targetType" /> no es una clase o estructura instanciable con un constructor sin
    /// parámetros.
    /// </exception>
    /// <returns>
    /// Una nueva instancia de tipo <paramref name="targetType" /> si <paramref name="value" /> se evalúa como
    /// <see langword="true" />, <see langword="null" /> en caso contrario.
    /// </returns>
    public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool b) return b ? null : targetType.New();
        throw new InvalidCastException();
    }
}


text:
package org.apache.taverna.workbench.report;

import org.apache.taverna.scufl2.api.profiles.Profile;

/**
 * @author alanrw
 */
public class ProfileReportEvent implements ReportManagerEvent {
	private final Profile profile;

	public ProfileReportEvent(Profile d) {
		this.profile = d;
	}

	public Profile getProfile() {
		return profile;
	}
}


text:
static const lldb_private::RegisterInfo *
GetRegisterInfoPtr(const lldb_private::ArchSpec &target_arch) {
  switch (target_arch.GetMachine()) {
  case llvm::Triple::ppc64le:
    return g_register_infos_ppc64le;
  default:
    assert(false && "Unhandled target architecture.");
    return NULL;
  }
}

static uint32_t
GetRegisterInfoCount(const lldb_private::ArchSpec &target_arch) {
  switch (target_arch.GetMachine()) {
  case llvm::Triple::ppc64le:
    return static_cast<uint32_t>(sizeof(g_register_infos_ppc64le) /
                                 sizeof(g_register_infos_ppc64le[0]));
  default:
    assert(false && "Unhandled target architecture.");
    return 0;
  }
}

RegisterInfoPOSIX_ppc64le::RegisterInfoPOSIX_ppc64le(
    const lldb_private::ArchSpec &target_arch)
    : lldb_private::RegisterInfoInterface(target_arch),
      m_register_info_p(GetRegisterInfoPtr(target_arch)),
      m_register_info_count(GetRegisterInfoCount(target_arch)) {}

size_t RegisterInfoPOSIX_ppc64le::GetGPRSize() const {
  return sizeof(GPR);
}

const lldb_private::RegisterInfo *
RegisterInfoPOSIX_ppc64le::GetRegisterInfo() const {
  return m_register_info_p;
}

uint32_t RegisterInfoPOSIX_ppc64le::GetRegisterCount() const {
  return m_register_info_count;
}


text:
using content::BrowserThread;

static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("encoding_tests");

class BrowserEncodingTest : public InProcessBrowserTest {
 protected:
  BrowserEncodingTest() {}

  // Saves the current page and verifies that the output matches the expected
  // result.
  void SaveAndCompare(const char* filename_to_write, const FilePath& expected) {
    // Dump the page, the content of dump page should be identical to the
    // expected result file.
    FilePath full_file_name = save_dir_.AppendASCII(filename_to_write);
    // We save the page as way of complete HTML file, which requires a directory
    // name to save sub resources in it. Although this test file does not have
    // sub resources, but the directory name is still required.
    content::WindowedNotificationObserver observer(
        content::NOTIFICATION_SAVE_PACKAGE_SUCCESSFULLY_FINISHED,
        content::NotificationService::AllSources());
    chrome::GetActiveWebContents(browser())->SavePage(
        full_file_name, temp_sub_resource_dir_,
        content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML);
    observer.Wait();

    FilePath expected_file_name = ui_test_utils::GetTestFilePath(
        FilePath(kTestDir), expected);

    EXPECT_TRUE(file_util::ContentsEqual(full_file_name, expected_file_name));
  }

  virtual void SetUpOnMainThread() OVERRIDE {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    save_dir_ = temp_dir_.path();
    temp_sub_resource_dir_ = save_dir_.AppendASCII("sub_resource_files");

    BrowserThread::PostTask(
        BrowserThread::IO, FROM_HERE,
        base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
  }

  ScopedTempDir temp_dir_;
  FilePath save_dir_;
  FilePath temp_sub_resource_dir_;
};

// TODO(jnd): 1. Some encodings are missing here. It'll be added later. See
// http://crbug.com/13306.
// 2. Add more files with multiple encoding name variants for each canonical
// encoding name). Webkit layout tests cover some, but testing in the UI test is
// also necessary.
// SLOW_ is added for XP debug bots. These tests should really be unittests...
IN_PROC_BROWSER_TEST_F(BrowserEncodingTest, SLOW_TestEncodingAliasMapping) {
  struct EncodingTestData {
    const char* file_name;
    const char* encoding_name;
  };

  const EncodingTestData kEncodingTestDatas[] = {
    { "Big5.html", "Big5" },
    { "EUC-JP.html", "EUC-JP" },
    { "gb18030.html", "gb18030" },
    { "iso-8859-1.html", "ISO-8859-1" },
    { "ISO-8859-2.html", "ISO-8859-2" },
    { "ISO-8859-4.html", "ISO-8859-4" },
    { "ISO-8859-5.html", "ISO-8859-5" },
    { "ISO-8859-6.html", "ISO-8859-6" },
    { "ISO-8859-7.html", "ISO-8859-7" },
    { "ISO-8859-8.html", "ISO-8859-8" },
    { "ISO-8859-13.html", "ISO-8859-13" },
    { "ISO-8859-15.html", "ISO-8859-15" },
    { "KOI8-R.html", "KOI8-R" },
    { "KOI8-U.html", "KOI8-U" },
    { "macintosh.html", "macintosh" },
    { "Shift-JIS.html", "Shift_JIS" },
    { "US-ASCII.html", "ISO-8859-1" },  // http://crbug.com/15801
    { "UTF-8.html", "UTF-8" },
    { "UTF-16LE.html", "UTF-16LE" },
    { "windows-874.html", "windows-874" },
    // http://crbug.com/95963
    // { "windows-949.html", "windows-949" },
    { "windows-1250.html", "windows-1250" },
    { "windows-1251.html", "windows-1251" },
    { "windows-1252.html", "windows-1252" },
    { "windows-1253.html", "windows-1253" },
    { "windows-1254.html", "windows-1254" },
    { "windows-1255.html", "windows-1255" },
    { "windows-1256.html", "windows-1256" },
    { "windows-1257.html", "windows-1257" },
    { "windows-1258.html", "windows-1258" }
  };
  const char* const kAliasTestDir = "alias_mapping";

  FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAliasTestDir);
  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kEncodingTestDatas); ++i) {
    FilePath test_file_path(test_dir_path);
    test_file_path = test_file_path.AppendASCII(
        kEncodingTestDatas[i].file_name);

    GURL url = content::URLRequestMockHTTPJob::GetMockUrl(test_file_path);

    // When looping through all the above files in one WebContents, there's a
    // race condition on Windows trybots that causes the previous encoding to be
    // seen sometimes. Create a new tab for each one.  http://crbug.com/122053
    ui_test_utils::NavigateToURLWithDisposition(
        browser(), url, NEW_FOREGROUND_TAB,
        ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

    EXPECT_EQ(kEncodingTestDatas[i].encoding_name,
              chrome::GetActiveWebContents(browser())->GetEncoding());
    chrome::CloseTab(browser());
  }
}

// Marked as flaky: see  http://crbug.com/44668
IN_PROC_BROWSER_TEST_F(BrowserEncodingTest, TestOverrideEncoding) {
  const char* const kTestFileName = "gb18030_with_iso88591_meta.html";
  const char* const kExpectedFileName =
      "expected_gb18030_saved_from_iso88591_meta.html";
  const char* const kOverrideTestDir = "user_override";

  FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kOverrideTestDir);
  test_dir_path = test_dir_path.AppendASCII(kTestFileName);
  GURL url = content::URLRequestMockHTTPJob::GetMockUrl(test_dir_path);
  ui_test_utils::NavigateToURL(browser(), url);
  content::WebContents* web_contents = chrome::GetActiveWebContents(browser());
  EXPECT_EQ("ISO-8859-1", web_contents->GetEncoding());

  // Override the encoding to "gb18030".
  const std::string selected_encoding =
      CharacterEncoding::GetCanonicalEncodingNameByAliasName("gb18030");
  content::TestNavigationObserver navigation_observer(
      content::Source<content::NavigationController>(
          &web_contents->GetController()));
  web_contents->SetOverrideEncoding(selected_encoding);
  navigation_observer.Wait();
  EXPECT_EQ("gb18030", web_contents->GetEncoding());

  FilePath expected_filename =
      FilePath().AppendASCII(kOverrideTestDir).AppendASCII(kExpectedFileName);
  SaveAndCompare(kTestFileName, expected_filename);
}

// The following encodings are excluded from the auto-detection test because
// it's a known issue that the current encoding detector does not detect them:
// ISO-8859-4
// ISO-8859-13
// KOI8-U
// macintosh
// windows-874
// windows-1252
// windows-1253
// windows-1257
// windows-1258

// For Hebrew, the expected encoding value is ISO-8859-8-I. See
// http://crbug.com/2927 for more details.
//
// This test fails frequently on the win_rel trybot. See http://crbug.com/122053
#if defined(OS_WIN)
#define MAYBE_TestEncodingAutoDetect DISABLED_TestEncodingAutoDetect
#else
#define MAYBE_TestEncodingAutoDetect TestEncodingAutoDetect
#endif
IN_PROC_BROWSER_TEST_F(BrowserEncodingTest, MAYBE_TestEncodingAutoDetect) {
  struct EncodingAutoDetectTestData {
    const char* test_file_name;   // File name of test data.
    const char* expected_result;  // File name of expected results.
    const char* expected_encoding;   // expected encoding.
  };
  const EncodingAutoDetectTestData kTestDatas[] = {
      { "Big5_with_no_encoding_specified.html",
        "expected_Big5_saved_from_no_encoding_specified.html",
        "Big5" },
      { "gb18030_with_no_encoding_specified.html",
        "expected_gb18030_saved_from_no_encoding_specified.html",
        "gb18030" },
      { "iso-8859-1_with_no_encoding_specified.html",
        "expected_iso-8859-1_saved_from_no_encoding_specified.html",
        "ISO-8859-1" },
      { "ISO-8859-5_with_no_encoding_specified.html",
        "expected_ISO-8859-5_saved_from_no_encoding_specified.html",
        "ISO-8859-5" },
      { "ISO-8859-6_with_no_encoding_specified.html",
        "expected_ISO-8859-6_saved_from_no_encoding_specified.html",
        "ISO-8859-6" },
      { "ISO-8859-7_with_no_encoding_specified.html",
        "expected_ISO-8859-7_saved_from_no_encoding_specified.html",
        "ISO-8859-7" },
      { "ISO-8859-8_with_no_encoding_specified.html",
        "expected_ISO-8859-8_saved_from_no_encoding_specified.html",
        "ISO-8859-8-I" },
      { "KOI8-R_with_no_encoding_specified.html",
        "expected_KOI8-R_saved_from_no_encoding_specified.html",
        "KOI8-R" },
      { "Shift-JIS_with_no_encoding_specified.html",
        "expected_Shift-JIS_saved_from_no_encoding_specified.html",
        "Shift_JIS" },
      { "UTF-8_with_no_encoding_specified.html",
        "expected_UTF-8_saved_from_no_encoding_specified.html",
        "UTF-8" },
      { "windows-949_with_no_encoding_specified.html",
        "expected_windows-949_saved_from_no_encoding_specified.html",
        "windows-949-2000" },
      { "windows-1251_with_no_encoding_specified.html",
        "expected_windows-1251_saved_from_no_encoding_specified.html",
        "windows-1251" },
      { "windows-1254_with_no_encoding_specified.html",
        "expected_windows-1254_saved_from_no_encoding_specified.html",
        "windows-1254" },
      { "windows-1255_with_no_encoding_specified.html",
        "expected_windows-1255_saved_from_no_encoding_specified.html",
        "windows-1255" },
      { "windows-1256_with_no_encoding_specified.html",
        "expected_windows-1256_saved_from_no_encoding_specified.html",
        "windows-1256" }
    };
  const char* const kAutoDetectDir = "auto_detect";
  // Directory of the files of expected results.
  const char* const kExpectedResultDir = "expected_results";

  FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAutoDetectDir);

  // Set the default charset to one of encodings not supported by the current
  // auto-detector (Please refer to the above comments) to make sure we
  // incorrectly decode the page. Now we use ISO-8859-4.
  browser()->profile()->GetPrefs()->SetString(prefs::kDefaultCharset,
                                              "ISO-8859-4");

  content::WebContents* web_contents = chrome::GetActiveWebContents(browser());
  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestDatas); ++i) {
    // Disable auto detect if it is on.
    browser()->profile()->GetPrefs()->SetBoolean(
        prefs::kWebKitUsesUniversalDetector, false);

    FilePath test_file_path(test_dir_path);
    test_file_path = test_file_path.AppendASCII(kTestDatas[i].test_file_name);
    GURL url = content::URLRequestMockHTTPJob::GetMockUrl(test_file_path);
    ui_test_utils::NavigateToURL(browser(), url);

    // Get the encoding used for the page, it must be the default charset we
    // just set.
    EXPECT_EQ("ISO-8859-4", web_contents->GetEncoding());

    // Enable the encoding auto detection.
    browser()->profile()->GetPrefs()->SetBoolean(
        prefs::kWebKitUsesUniversalDetector, true);

    content::TestNavigationObserver observer(
        content::Source<content::NavigationController>(
            &web_contents->GetController()));
    chrome::Reload(browser(), CURRENT_TAB);
    observer.Wait();

    // Re-get the encoding of page. It should return the real encoding now.
    EXPECT_EQ(kTestDatas[i].expected_encoding, web_contents->GetEncoding());

    // Dump the page, the content of dump page should be equal with our expect
    // result file.
    FilePath expected_result_file_name =
        FilePath().AppendASCII(kAutoDetectDir).AppendASCII(kExpectedResultDir).
        AppendASCII(kTestDatas[i].expected_result);
    SaveAndCompare(kTestDatas[i].test_file_name, expected_result_file_name);
  }
}


text:
using System.Configuration;

namespace Amido.WebDriver.Utilities.Configuration
{
    public class SupportedBrowsersCollection : ConfigurationElementCollection
    {
        public new SupportedBrowserConfigurationElement this[string key]
        {
            get
            {
                return this.BaseGet(key) as SupportedBrowserConfigurationElement;
            }
        }

        public SupportedBrowserConfigurationElement this[int index]
        {
            get
            {
                return this.BaseGet(index) as SupportedBrowserConfigurationElement;
            }
            set
            {
                if (this.BaseGet(index) != null)
                {
                    this.BaseRemoveAt(index);
                }

                this.BaseAdd(index, value);
            }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new SupportedBrowserConfigurationElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((SupportedBrowserConfigurationElement)element).Key;
        }
    }
}


text:
<?php
include './classes/Time.php';

class Player {
  public $login;
  public $email;
  public $administrator;
  public $maxPerDay;
  public $maxPerWeek;
  public $extraDay;
  public $extraMaxPerDay;
  public $extraMaxPerWeek;
  public $extraComment;
  public $lockedUntil;
  public $loginSource;
  public $loginIp;
  public $loginDate;
  public $logoutDate;
  public $confirmDate;
  public $playedDay;
  public $playedWeek;
  public $passwordHash;

  function isLocked() {
    if ($this->lockedUntil) {
      return time() < $this->lockedUntil;
    }
    return false;
  }

  function isExtraDay() {
    return Time::isToday($this->extraDay);
  }

  function isExtraWeek() {
    return Time::isThisWeek($this->extraDay);
  }

  function getExtraComment() {
    if ($this->isExtraWeek()) {
      return htmlspecialchars($this->extraComment);
    }
    return '';
  }

  function getMaxToday() {
    if ($this->isLocked()) {
      return 0;
    }
    if ($this->extraMaxPerDay && $this->isExtraDay()) {
      return $this->extraMaxPerDay;
    }
    return $this->maxPerDay;
  }

  function getMaxThisWeek() {
    if ($this->isLocked()) {
      return 0;
    }
    if ($this->extraMaxPerWeek && $this->isExtraWeek()) {
      return $this->extraMaxPerWeek;
    }
    return $this->maxPerWeek;
  }

  function getPlayedToday() {
    global $config;
    $played = 0;
    if (Time::isToday($this->loginDate)) {
      if ($this->logoutDate == NULL) {
        $played = (time() - $this->loginDate - $config['loginLogoutDelay']);
        if ($played < 0) {
          $played = 0;
        }
        //if ($played > $config['reloginMaxPenalty']) {
        //  $played = $config['reloginMaxPenalty'];
        //}
      }
    }
    return $played;
  }

  function getPlayedThisWeek() {
    global $config;
    $played = 0;
    if (Time::isThisWeek($this->loginDate)) {
      $played = $this->playedWeek + $this->getPlayedToday();
      if (!Time::isToday($this->loginDate)) {
        if ($this->logoutDate == NULL) {
          $played = $played + $config['reloginMaxPenalty'];
        }
      }
    }
    return $played;
  }

  function getRestToday() {
    $rest = $this->getMaxToday() - $this->getPlayedToday();
    if ($rest < 0) {
      return 0;
    }
    return $rest;
  }

  function getRestThisWeek() {
    $rest = $this->getMaxThisWeek() - $this->getPlayedThisWeek();
    if ($rest < 0) {
      return 0;
    }
    return $rest;
  }

  function getRest() {
    $rest = $this->getRestToday();
    if ($rest == 0) {
      return 0;
    }
    $restThisWeek = $this->getRestThisWeek();
    if ($restThisWeek < $rest) {
      $rest = $restThisWeek;
    }
    return $rest;
  }

  public function getLoginSource() {
    return htmlspecialchars($this->loginSource);
  }

  public function getLoginIp() {
    return htmlspecialchars($this->loginIp);
  }

  public static function getPasswordHash($password) {
    return password_hash($password, PASSWORD_BCRYPT);
  }

  function setPassword($password) {
    $this->passwordHash = getPasswordHash($password);
  }

  function checkPassword($password) {
    return password_verify($password, $this->passwordHash);
  }

  function verifySource($source) {
    if ($source != $this->loginSource) {
      header('HTTP/1.1 909 Source Missmatch');
      echo  $source . ' vs ' . $this->loginSource;
      exit;
    }
  }
}
?>


text:
package com.duckspot.roadie;

import com.duckspot.util.FileUtil;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

public class PackageTest {

    static String toolName = "test";
    static String version = "1.0";
    static URI packageURI;
    static ToolVersion toolVersion;
    static Path cachePath;

    public PackageTest() {
    }

    @BeforeClass
    public static void setUpClass() throws URISyntaxException {
        RoadiePaths.setDevRoot("dev");
        packageURI = new URI("http://duckspot.com/roadie-tools/test/test/test_install.json");
        toolVersion = new ToolVersion(toolName, version);
        toolVersion.addSource(packageURI);
        cachePath = RoadiePaths.get("cache").resolve(toolName).resolve(version);
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() throws IOException {
        FileUtil.deleteDirectory(RoadiePaths.get(""));
    }

    @After
    public void tearDown() throws IOException {
//        FileUtil.deleteDirectory(RoadiePaths.get(""));
    }

    /**
     * Test of download method, of class Package.
     */
    @Test
    public void testInstall() {
        System.out.println("download");
        Package instance = toolVersion.getPackage();
        Path testZip = cachePath.resolve("test.zip");
        System.out.println("PackageTest(69): testZip: "+testZip);
        assertFalse(Files.exists(testZip));
        instance.install();
        assertTrue(Files.exists(testZip));
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@implementation SDLUnsubscribeVehicleDataResponse

- (instancetype)init {
    if (self = [super initWithName:SDLNameUnsubscribeVehicleData]) {
    }
    return self;
}

- (void)setGps:(nullable SDLVehicleDataResult *)gps {
    [parameters sdl_setObject:gps forName:SDLNameGPS];
}

- (nullable SDLVehicleDataResult *)gps {
    return [parameters sdl_objectForName:SDLNameGPS ofClass:SDLVehicleDataResult.class];
}

- (void)setSpeed:(nullable SDLVehicleDataResult *)speed {
    [parameters sdl_setObject:speed forName:SDLNameSpeed];
}

- (nullable SDLVehicleDataResult *)speed {
    return [parameters sdl_objectForName:SDLNameSpeed ofClass:SDLVehicleDataResult.class];
}

- (void)setRpm:(nullable SDLVehicleDataResult *)rpm {
    [parameters sdl_setObject:rpm forName:SDLNameRPM];
}

- (nullable SDLVehicleDataResult *)rpm {
    return [parameters sdl_objectForName:SDLNameRPM ofClass:SDLVehicleDataResult.class];
}

- (void)setFuelLevel:(nullable SDLVehicleDataResult *)fuelLevel {
    [parameters sdl_setObject:fuelLevel forName:SDLNameFuelLevel];
}

- (nullable SDLVehicleDataResult *)fuelLevel {
    return [parameters sdl_objectForName:SDLNameFuelLevel ofClass:SDLVehicleDataResult.class];
}

- (void)setFuelLevel_State:(nullable SDLVehicleDataResult *)fuelLevel_State {
    [parameters sdl_setObject:fuelLevel_State forName:SDLNameFuelLevelState];
}

- (nullable SDLVehicleDataResult *)fuelLevel_State {
    return [parameters sdl_objectForName:SDLNameFuelLevelState ofClass:SDLVehicleDataResult.class];
}

- (void)setFuelRange:(nullable SDLVehicleDataResult *)fuelRange {
    [parameters sdl_setObject:fuelRange forName:SDLNameFuelRange];
}

- (nullable SDLVehicleDataResult *)fuelRange {
    return [parameters sdl_objectForName:SDLNameFuelRange ofClass:SDLVehicleDataResult.class];
}

- (void)setInstantFuelConsumption:(nullable SDLVehicleDataResult *)instantFuelConsumption {
    [parameters sdl_setObject:instantFuelConsumption forName:SDLNameInstantFuelConsumption];
}

- (nullable SDLVehicleDataResult *)instantFuelConsumption {
    return [parameters sdl_objectForName:SDLNameInstantFuelConsumption ofClass:SDLVehicleDataResult.class];
}

- (void)setExternalTemperature:(nullable SDLVehicleDataResult *)externalTemperature {
    [parameters sdl_setObject:externalTemperature forName:SDLNameExternalTemperature];
}

- (nullable SDLVehicleDataResult *)externalTemperature {
    return [parameters sdl_objectForName:SDLNameExternalTemperature ofClass:SDLVehicleDataResult.class];
}

- (void)setPrndl:(nullable SDLVehicleDataResult *)prndl {
    [parameters sdl_setObject:prndl forName:SDLNamePRNDL];
}

- (nullable SDLVehicleDataResult *)prndl {
    return [parameters sdl_objectForName:SDLNamePRNDL ofClass:SDLVehicleDataResult.class];
}

- (void)setTirePressure:(nullable SDLVehicleDataResult *)tirePressure {
    [parameters sdl_setObject:tirePressure forName:SDLNameTirePressure];
}

- (nullable SDLVehicleDataResult *)tirePressure {
    return [parameters sdl_objectForName:SDLNameTirePressure ofClass:SDLVehicleDataResult.class];
}

- (void)setOdometer:(nullable SDLVehicleDataResult *)odometer {
    [parameters sdl_setObject:odometer forName:SDLNameOdometer];
}

- (nullable SDLVehicleDataResult *)odometer {
    return [parameters sdl_objectForName:SDLNameOdometer ofClass:SDLVehicleDataResult.class];
}

- (void)setBeltStatus:(nullable SDLVehicleDataResult *)beltStatus {
    [parameters sdl_setObject:beltStatus forName:SDLNameBeltStatus];
}

- (nullable SDLVehicleDataResult *)beltStatus {
    return [parameters sdl_objectForName:SDLNameBeltStatus ofClass:SDLVehicleDataResult.class];
}

- (void)setBodyInformation:(nullable SDLVehicleDataResult *)bodyInformation {
    [parameters sdl_setObject:bodyInformation forName:SDLNameBodyInformation];
}

- (nullable SDLVehicleDataResult *)bodyInformation {
    return [parameters sdl_objectForName:SDLNameBodyInformation ofClass:SDLVehicleDataResult.class];
}

- (void)setDeviceStatus:(nullable SDLVehicleDataResult *)deviceStatus {
    [parameters sdl_setObject:deviceStatus forName:SDLNameDeviceStatus];
}

- (nullable SDLVehicleDataResult *)deviceStatus {
    return [parameters sdl_objectForName:SDLNameDeviceStatus ofClass:SDLVehicleDataResult.class];
}

- (void)setDriverBraking:(nullable SDLVehicleDataResult *)driverBraking {
    [parameters sdl_setObject:driverBraking forName:SDLNameDriverBraking];
}

- (nullable SDLVehicleDataResult *)driverBraking {
    return [parameters sdl_objectForName:SDLNameDriverBraking ofClass:SDLVehicleDataResult.class];
}

- (void)setWiperStatus:(nullable SDLVehicleDataResult *)wiperStatus {
    [parameters sdl_setObject:wiperStatus forName:SDLNameWiperStatus];
}

- (nullable SDLVehicleDataResult *)wiperStatus {
    return [parameters sdl_objectForName:SDLNameWiperStatus ofClass:SDLVehicleDataResult.class];
}

- (void)setHeadLampStatus:(nullable SDLVehicleDataResult *)headLampStatus {
    [parameters sdl_setObject:headLampStatus forName:SDLNameHeadLampStatus];
}

- (nullable SDLVehicleDataResult *)headLampStatus {
    return [parameters sdl_objectForName:SDLNameHeadLampStatus ofClass:SDLVehicleDataResult.class];
}

- (void)setEngineOilLife:(nullable SDLVehicleDataResult *)engineOilLife {
    [parameters sdl_setObject:engineOilLife forName:SDLNameEngineOilLife];
}

- (nullable SDLVehicleDataResult *)engineOilLife {
    return [parameters sdl_objectForName:SDLNameEngineOilLife];
}

- (void)setEngineTorque:(nullable SDLVehicleDataResult *)engineTorque {
    [parameters sdl_setObject:engineTorque forName:SDLNameEngineTorque];
}

- (nullable SDLVehicleDataResult *)engineTorque {
    return [parameters sdl_objectForName:SDLNameEngineTorque ofClass:SDLVehicleDataResult.class];
}

- (void)setAccPedalPosition:(nullable SDLVehicleDataResult *)accPedalPosition {
    [parameters sdl_setObject:accPedalPosition forName:SDLNameAccelerationPedalPosition];
}

- (nullable SDLVehicleDataResult *)accPedalPosition {
    return [parameters sdl_objectForName:SDLNameAccelerationPedalPosition ofClass:SDLVehicleDataResult.class];
}

- (void)setSteeringWheelAngle:(nullable SDLVehicleDataResult *)steeringWheelAngle {
    [parameters sdl_setObject:steeringWheelAngle forName:SDLNameSteeringWheelAngle];
}

- (nullable SDLVehicleDataResult *)steeringWheelAngle {
    return [parameters sdl_objectForName:SDLNameSteeringWheelAngle ofClass:SDLVehicleDataResult.class];
}

- (void)setECallInfo:(nullable SDLVehicleDataResult *)eCallInfo {
    [parameters sdl_setObject:eCallInfo forName:SDLNameECallInfo];
}

- (nullable SDLVehicleDataResult *)eCallInfo {
    return [parameters sdl_objectForName:SDLNameECallInfo ofClass:SDLVehicleDataResult.class];
}

- (void)setAirbagStatus:(nullable SDLVehicleDataResult *)airbagStatus {
    [parameters sdl_setObject:airbagStatus forName:SDLNameAirbagStatus];
}

- (nullable SDLVehicleDataResult *)airbagStatus {
    return [parameters sdl_objectForName:SDLNameAirbagStatus ofClass:SDLVehicleDataResult.class];
}

- (void)setEmergencyEvent:(nullable SDLVehicleDataResult *)emergencyEvent {
    [parameters sdl_setObject:emergencyEvent forName:SDLNameEmergencyEvent];
}

- (nullable SDLVehicleDataResult *)emergencyEvent {
    return [parameters sdl_objectForName:SDLNameEmergencyEvent ofClass:SDLVehicleDataResult.class];
}

- (void)setClusterModes:(nullable SDLVehicleDataResult *)clusterModes {
    [parameters sdl_setObject:clusterModes forName:SDLNameClusterModes];
}

- (nullable SDLVehicleDataResult *)clusterModes {
    return [parameters sdl_objectForName:SDLNameClusterModes ofClass:SDLVehicleDataResult.class];
}

- (void)setMyKey:(nullable SDLVehicleDataResult *)myKey {
    [parameters sdl_setObject:myKey forName:SDLNameMyKey];
}

- (nullable SDLVehicleDataResult *)myKey {
    return [parameters sdl_objectForName:SDLNameMyKey ofClass:SDLVehicleDataResult.class];
}

- (void)setElectronicParkBrakeStatus:(nullable SDLVehicleDataResult *)electronicParkBrakeStatus {
    [parameters sdl_setObject:electronicParkBrakeStatus forName:SDLNameElectronicParkBrakeStatus];
}

- (nullable SDLVehicleDataResult *)electronicParkBrakeStatus {
    return [parameters sdl_objectForName:SDLNameElectronicParkBrakeStatus ofClass:[SDLVehicleDataResult class]];
}

- (void)setTurnSignal:(nullable SDLVehicleDataResult *)turnSignal {
    [parameters sdl_setObject:turnSignal forName:SDLNameTurnSignal];
}

- (nullable SDLVehicleDataResult *)turnSignal {
    return [parameters sdl_objectForName:SDLNameTurnSignal ofClass:SDLVehicleDataResult.class];
}

@end

NS_ASSUME_NONNULL_END


text:
package org.inbloom.content.controller;
import java.util.HashSet;
import java.util.Set;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.SolrDocument;
import org.inbloom.content.domain.AgeRange;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;

import flexjson.JSONSerializer;
import flexjson.transformer.IterableTransformer;

@RequestMapping("/ageranges")
@Controller
@RooWebScaffold(path = "ageranges", formBackingObject = AgeRange.class)
@RooWebJson(jsonObject = AgeRange.class)
public class AgeRangeController {

	@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJson(@RequestBody String json) {
        AgeRange ageRange = AgeRange.fromJsonToAgeRange(json);
        ageRange.persist();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Location", ServletUriComponentsBuilder.fromCurrentRequest().path("/").path(ageRange.getId().toString()).build().toString());
        return new ResponseEntity<String>(headers, HttpStatus.CREATED);
    }

	@RequestMapping(value = "/search", method = RequestMethod.GET, headers = "Accept=application/json")
	public ResponseEntity<String> searchSolr(@RequestParam("query") String query) {
		Set<AgeRange> ageRanges = new HashSet<AgeRange>();
		for (SolrDocument document: AgeRange.search(new SolrQuery(query)).getResults()) {
			Long ageRangeId = (Long) document.getFieldValue("ageRange.id_l");
			AgeRange ageRange = AgeRange.findAgeRange(ageRangeId);
			ageRanges.add(ageRange);
		}

		JSONSerializer serializer = new JSONSerializer().transform(new IterableTransformer(), Set.class);
		String responseString = serializer.serialize(ageRanges);
		HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
		return new ResponseEntity<String>(responseString, headers, HttpStatus.OK);
	}}


text:
from afs.util.AFSError import AFSError

class ORMError(AFSError):
        # No specific Method now
        pass

class createEngineError(AFSError):
    def __init__(self, conf):
        self.message = """Cannot create an engine (connect to DB) using following options : DB_USER='%s',DB_HOST='%s',DB_PORT='%s',DB_TYPE='%s',DB_SID='%s'
        """ % (conf.DB_USER,conf.DB_HOST,  conf.DB_PORT, conf.DB_TYPE, conf.DB_SID)
        return


text:
package net.brord.plugins.menuapi.menus;

import net.brord.plugins.menuapi.data.Menu;

import org.bukkit.entity.Player;

/**
 * Project menuapi

 * Class net.brord.plugins.menuapi.menus.InventoryMenu.java

 * @author Brord
 * @since 4 jun. 2014, 00:58:54
 */
public class InventoryMenu extends PlayerMenu {

	/**
	 * @param menu
	 */
	public InventoryMenu(Menu menu) {
		super(menu);
	}

	/**
	 * @see net.brord.plugins.menuapi.menus.GUI#assignToPlayer(org.bukkit.entity.Player)
	 */
	public boolean assignToPlayer(Player player) {
		return false;
	}

	/**
	 * @see net.brord.plugins.menuapi.menus.GUI#removeFromPlayer(org.bukkit.entity.Player)
	 */
	public boolean removeFromPlayer(Player player) {
		return false;
	}

}


text:
package net.bhira.sample.api.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.bhira.sample.api.dao.EmployeeDao;
import net.bhira.sample.common.exception.InvalidObjectException;
import net.bhira.sample.common.exception.InvalidReferenceException;
import net.bhira.sample.common.exception.ObjectNotFoundException;
import net.bhira.sample.model.Employee;

/**
 * Implementation of {@link net.bhira.sample.api.service.EmployeeService}. It provides CRUD
 * operations for {@link net.bhira.sample.model.Employee}.
 *
 * @author Baldeep Hira
 */
@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService {

	@Autowired
	EmployeeDao employeeDao;

	/**
	 * @see net.bhira.sample.api.service.EmployeeService#load(long)
	 */
	@Override
	public Employee load(long employeeId) {
		return employeeDao.load(employeeId);
	}

	/**
	 * @see net.bhira.sample.api.service.EmployeeService#save(net.bhira.sample.model.Employee)
	 */
	@Override
	public void save(Employee employee) throws ObjectNotFoundException, InvalidObjectException,
			InvalidReferenceException {
		employeeDao.save(employee);
	}

	/**
	 * @see net.bhira.sample.api.service.EmployeeService#delete(long)
	 */
	@Override
	public boolean delete(long employeeId) {
		return employeeDao.delete(employeeId);
	}

	/**
	 * @see net.bhira.sample.api.service.EmployeeService#loadByCompany()
	 */
	@Override
	public List<Employee> loadByCompany(long companyId) {
		return employeeDao.loadByCompany(companyId);
	}

	/**
	 * @see net.bhira.sample.api.service.EmployeeService#loadByDepartment()
	 */
	@Override
	public List<Employee> loadByDepartment(long departmentId) {
		return employeeDao.loadByDepartment(departmentId);
	}

}


text:
using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Appium.Net.Integration.Tests.helpers;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium.Enums;
using OpenQA.Selenium.Appium.iOS;

namespace Appium.Net.Integration.Tests.IOS
{
    [TestFixture(Category = "Device")]
    public class ClipboardTest
    {
        private IOSDriver<IWebElement> _driver;
        private const string ClipboardTestString = "Hello Clipboard";
        private const string Base64RegexPattern = @"^[a-zA-Z0-9\+/]*={0,2}$";

        [SetUp]
        public void Setup()
        {
            var capabilities = Caps.GetIosCaps(Apps.Get("iosUICatalogApp"));
            capabilities.AddAdditionalCapability(MobileCapabilityType.FullReset, true);
            var serverUri = Env.ServerIsRemote() ? AppiumServers.RemoteServerUri : AppiumServers.LocalServiceUri;

            _driver = new IOSDriver<IWebElement>(serverUri, capabilities, Env.InitTimeoutSec);
            _driver.Manage().Timeouts().ImplicitWait = Env.ImplicitTimeoutSec;
        }

        [Test]
        public void WhenSetClipboardContentTypeIsPlainText_GetClipboardShouldReturnEncodedBase64String()
        {
            var base64ClipboardTestString = Convert.ToBase64String(Encoding.UTF8.GetBytes(ClipboardTestString));
            _driver.SetClipboard(ClipboardContentType.PlainText, base64ClipboardTestString);
            Assert.That(() => Regex.IsMatch(_driver.GetClipboard(ClipboardContentType.PlainText), Base64RegexPattern),
                Is.True);
        }

        [Test]
        public void WhenClipboardContentTypeIsPlainText_GetClipboardTextShouldReturnActualText()
        {
            _driver.SetClipboardText(ClipboardTestString);
            Assert.That(() => _driver.GetClipboardText(), Does.Match(ClipboardTestString));
        }

        [Test]
        public void WhenSetClipboardContentTypeIsUrl_GetClipboardShouldReturnEncodedBase64String()
        {
            const string urlString = "https://github.com/appium/appium-dotnet-driver";
            var base64String = Convert.ToBase64String(Encoding.UTF8.GetBytes(urlString));
            _driver.SetClipboard(ClipboardContentType.Url, base64String);

            Assert.That(() => Regex.IsMatch(_driver.GetClipboard(ClipboardContentType.Url), Base64RegexPattern, RegexOptions.Multiline),
                Is.True);
        }

        [Test]
        public void WhenSetClipboardUrl_GetClipboardUrlShouldReturnUrl()
        {
            const string urlString = "https://github.com/appium/appium-dotnet-driver";
            _driver.SetClipboardUrl(urlString);

            Assert.That(() => _driver.GetClipboardUrl(), Does.Match(urlString));
        }

        [Test]
        public void WhenSetClipboardContentTypeIsImage_GetClipboardShouldReturnEncodedBase64String()
        {
            var testImageBytes = _driver.GetScreenshot().AsByteArray;
            var base64Image = Convert.ToBase64String(testImageBytes);
            _driver.SetClipboard(ClipboardContentType.Image, base64Image);

            Assert.That(() => Regex.IsMatch(_driver.GetClipboard(ClipboardContentType.Image), Base64RegexPattern, RegexOptions.Multiline),
                Is.True);
        }

        [Test]
        public void WhenSetClipboardImage_GetClipboardImageShouldReturnImage()
        {
            var imageBytes = _driver.GetScreenshot().AsByteArray;
            var testImage = Image.FromStream(new MemoryStream(imageBytes));

            _driver.SetClipboardImage(testImage);
            Assert.That(() => _driver.GetClipboardImage().Size, Is.EqualTo(testImage.Size));
        }

        [Test]
        public void WhenClipboardHasNoImage_GetClipboardImageShouldReturnNull()
        {
            _driver.SetClipboardText(ClipboardTestString);
            Assert.That(() => _driver.GetClipboardImage(), Is.Null);
        }

        [Test]
        public void WhenClipboardIsEmpty_GetClipboardShouldReturnEmptyString()
        {
            _driver.SetClipboardText(string.Empty);
            Assert.That(() => _driver.GetClipboard(ClipboardContentType.PlainText), Is.Empty);
        }

        [Test]
        public void WhenClipboardIsEmpty_GetClipboardTextShouldReturnEmptyString()
        {
            _driver.SetClipboardText(string.Empty, null);
            Assert.That(() => _driver.GetClipboardText(), Is.Empty);
        }

        [TearDown]
        public void TearDown()
        {
            if (_driver.IsLocked())
                _driver.Unlock();
            _driver?.Quit();

            if (!Env.ServerIsRemote())
            {
                AppiumServers.StopLocalService();
            }
        }
    }
}


text:
<?php

/**
 * Link filter form base class.
 *
 * @package    sf_sandbox
 * @subpackage filter
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormFilterGeneratedTemplate.php 29570 2010-05-21 14:49:47Z Kris.Wallsmith $
 */
abstract class BaseLinkFormFilter extends BaseFormFilterDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'user_id'     => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('User'), 'add_empty' => true)),
      'url'         => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'image'       => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'title'       => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'site_name'   => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'description' => new sfWidgetFormFilterInput(array('with_empty' => false)),
      'created_at'  => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate(), 'with_empty' => false)),
      'updated_at'  => new sfWidgetFormFilterDate(array('from_date' => new sfWidgetFormDate(), 'to_date' => new sfWidgetFormDate(), 'with_empty' => false)),
    ));

    $this->setValidators(array(
      'user_id'     => new sfValidatorDoctrineChoice(array('required' => false, 'model' => $this->getRelatedModelName('User'), 'column' => 'id')),
      'url'         => new sfValidatorPass(array('required' => false)),
      'image'       => new sfValidatorPass(array('required' => false)),
      'title'       => new sfValidatorPass(array('required' => false)),
      'site_name'   => new sfValidatorPass(array('required' => false)),
      'description' => new sfValidatorPass(array('required' => false)),
      'created_at'  => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 00:00:00')), 'to_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 23:59:59')))),
      'updated_at'  => new sfValidatorDateRange(array('required' => false, 'from_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 00:00:00')), 'to_date' => new sfValidatorDateTime(array('required' => false, 'datetime_output' => 'Y-m-d 23:59:59')))),
    ));

    $this->widgetSchema->setNameFormat('link_filters[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'Link';
  }

  public function getFields()
  {
    return array(
      'id'          => 'Number',
      'user_id'     => 'ForeignKey',
      'url'         => 'Text',
      'image'       => 'Text',
      'title'       => 'Text',
      'site_name'   => 'Text',
      'description' => 'Text',
      'created_at'  => 'Date',
      'updated_at'  => 'Date',
    );
  }
}


text:
package org.apache.spark.sql.catalyst.optimizer

import org.apache.spark.sql.catalyst.expressions.{Alias, Expression, GetStructField}
import org.apache.spark.sql.catalyst.planning.SelectedField
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.catalyst.rules.Rule

abstract class FieldExtractionPushdown extends Rule[LogicalPlan] {
  // Gets the top-level GetStructField expressions from the given expression
  // and its children. This does not return children of a GetStructField.
  protected final def getFieldExtractors(expr: Expression): Seq[GetStructField] =
    expr match {
      // Check that getField matches SelectedField(_) to ensure that getField defines a chain of
      // extractors down to an attribute.
      case getField: GetStructField if SelectedField.unapply(getField).isDefined =>
        getField :: Nil
      case _ =>
        expr.children.flatMap(getFieldExtractors)
    }

  // Constructs aliases and a substitution function for the given sequence of
  // GetStructField expressions.
  protected final def constructAliasesAndSubstitutions(fieldExtractors: Seq[GetStructField]) = {
    val aliases =
      fieldExtractors.map(extractor =>
        Alias(extractor, extractor.childSchema(extractor.ordinal).name)())

    val attributes = aliases.map(alias => (alias.child, alias.toAttribute)).toMap

    val substituteAttributes: Expression => Expression = _.transformDown {
      case expr: GetStructField => attributes.getOrElse(expr, expr)
    }

    (aliases, substituteAttributes)
  }
}


text:
from os import remove
from tempfile import NamedTemporaryFile

from flask_testing import TestCase

from opwen_email_client.webapp.config import AppConfig
from opwen_email_client.webapp.ioc import create_app

class TestConfig(AppConfig):
    CACHE_TYPE = 'null'
    TESTING = True
    SQLALCHEMY_DATABASE_URI = 'sqlite://'
    SECURITY_PASSWORD_SALT = 'UnSalted'
    SECRET_KEY = 'NoSecret'

    def __init__(self):
        with NamedTemporaryFile(delete=False) as fobj:
            self.LOCAL_EMAIL_STORE = fobj.name

    def close(self):
        remove(self.LOCAL_EMAIL_STORE)

class Base(object):
    class AppTests(TestCase):
        def _pre_setup(self):
            self.app_config = TestConfig()
            super()._pre_setup()

        def _post_teardown(self):
            self.app_config.close()
            super()._post_teardown()

        def create_app(self):
            app = create_app(self.app_config)
            return app


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

title: ConfigurationData
---

# ConfigurationData

> Encapsula un conjunto de parámetros de captura de los medios de comunicación un dispositivo compatible.

## Descripción

Describe los modos de captura de los medios de comunicación soportados por el dispositivo. Los datos de configuración incluyen el tipo MIME y captura de dimensiones para captura de vídeo o imagen.

Los tipos MIME deben adherirse a [RFC2046][1]. Ejemplos:

 [1]: http://www.ietf.org/rfc/rfc2046.txt

*   `video/3gpp`
*   `video/quicktime`
*   `image/jpeg`
*   `audio/amr`
*   `audio/wav`

## Propiedades

*   **tipo**: cadena codificada en el ASCII en minúsculas que representa el tipo de medios de comunicación. (DOMString)

*   **altura**: la altura de la imagen o vídeo en píxeles. El valor es cero para clips de sonido. (Número)

*   **ancho**: el ancho de la imagen o vídeo en píxeles. El valor es cero para clips de sonido. (Número)

## Ejemplo rápido

    // retrieve supported image modes
    var imageModes = navigator.device.capture.supportedImageModes;

    // Select mode that has the highest horizontal resolution
    var width = 0;
    var selectedmode;
    for each (var mode in imageModes) {
        if (mode.width > width) {
            width = mode.width;
            selectedmode = mode;
        }
    }

No compatible con cualquier plataforma. Todas las matrices de datos configuración están vacías.


text:
package io.piotrjastrzebski.dungen;

import com.badlogic.gdx.utils.Array;

/**
 * Created by PiotrJ on 03/09/15.
 */
public class RoomNode {
	public Room room;
	public Array<RoomEdge> edges = new Array<>();

	public void add (Room add) {
		RoomEdge edge = new RoomEdge();
		edge.roomA = room;
		edge.roomB = add;
		edges.add(edge);
	}

	public void add (RoomEdge add) {
		RoomEdge edge = new RoomEdge();
		if (add.roomA == room) {
			edge.roomA = add.roomA;
			edge.roomB = add.roomB;
		} else {
			edge.roomA = add.roomB;
			edge.roomB = add.roomA;
		}
		edges.add(edge);
	}

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

		RoomNode roomNode = (RoomNode)o;

		if (room != null ? !room.equals(roomNode.room) : roomNode.room != null)
			return false;
		return !(edges != null ? !edges.equals(roomNode.edges) : roomNode.edges != null);

	}

	@Override public int hashCode () {
		int result = room != null ? room.hashCode() : 0;
		result = 31 * result + (edges != null ? edges.hashCode() : 0);
		return result;
	}

	@Override public String toString () {
		return "RoomNode{" +
			"room=" + room +
			'}';
	}
}


text:
all:
	cd ..; python wallmapper.py --zoom 8 --basemap mapbox.control-room --output examples/control-room-8.png
	cd ..; python wallmapper.py --zoom 18 --basemap eleanor.mnyzxgvi --output examples/eleanor-woodcut-18.png
	cd ..; python wallmapper.py --zoom 16 --basemap mapbox.dc-nightvision --output examples/dc-nightvision-16.png
	cd ..; python wallmapper.py --zoom 18 --basemap examples.map-vyofok3q --output examples/streets-18.png
	cd ..; python wallmapper.py --zoom 18 --basemap examples.map-9ijuk24y --output examples/terrain-18.png
	cd ..; python wallmapper.py --zoom 18 --basemap examples.map-qfyrx5r8 --output examples/satellite-18.png
	cd ..; python wallmapper.py --zoom 18 --basemap eleanor.ipncow29 --output examples/space-station-18.png


text:
Nodig je
vrienden uit

1) Kies je tegel en foto

2) Persoonlijke spreuk

3) Bedankt


text:
package com.chinabike.plugins;

import android.app.Activity;
import android.content.Context;

/**
 * Created by Administrator on 2016/2/25.
 */
public class FakeR {
    private Context context;
    private String packageName;

    public FakeR(Activity activity) {
        context = activity.getApplicationContext();
        packageName = context.getPackageName();
    }

    public FakeR(Context context) {
        this.context = context;
        packageName = context.getPackageName();
    }

    public int getId(String group, String key) {
        return context.getResources().getIdentifier(key, group, packageName);
    }

    public static int getId(Context context, String group, String key) {
        return context.getResources().getIdentifier(key, group, context.getPackageName());
    }
}


text:
namespace gfx {

// Get default EGL display for GLSurfaceEGL (differs by platform).
EGLNativeDisplayType GetPlatformDefaultEGLNativeDisplay();

// Interface for EGL surface.
class GL_EXPORT GLSurfaceEGL : public GLSurface {
 public:
  explicit GLSurfaceEGL(
    const gfx::SurfaceConfiguration requested_configuration);

  // Implement GLSurface.
  void DestroyAndTerminateDisplay() override;
  EGLDisplay GetDisplay() override;

  static bool InitializeOneOff();
  static EGLDisplay GetHardwareDisplay();
  static EGLNativeDisplayType GetNativeDisplay();

  // These aren't particularly tied to surfaces, but since we already
  // have the static InitializeOneOff here, it's easiest to reuse its
  // initialization guards.
  static const char* GetEGLExtensions();
  static bool HasEGLExtension(const char* name);
  static bool IsCreateContextRobustnessSupported();
  static bool IsEGLSurfacelessContextSupported();

 protected:
  ~GLSurfaceEGL() override;

 private:
  DISALLOW_COPY_AND_ASSIGN(GLSurfaceEGL);
};

// Encapsulates an EGL surface bound to a view.
class GL_EXPORT NativeViewGLSurfaceEGL : public GLSurfaceEGL {
 public:
  NativeViewGLSurfaceEGL(
    EGLNativeWindowType window,
    const gfx::SurfaceConfiguration requested_configuration);

  // Implement GLSurface.
  EGLConfig GetConfig() override;
  bool Initialize() override;
  void Destroy() override;
  bool Resize(const gfx::Size& size) override;
  bool Recreate() override;
  bool IsOffscreen() override;
  bool SwapBuffers() override;
  gfx::Size GetSize() override;
  EGLSurface GetHandle() override;
  bool SupportsPostSubBuffer() override;
  bool PostSubBuffer(int x, int y, int width, int height) override;
  VSyncProvider* GetVSyncProvider() override;

  // Create a NativeViewGLSurfaceEGL with an externally provided VSyncProvider.
  // Takes ownership of the VSyncProvider.
  virtual bool Initialize(scoped_ptr<VSyncProvider> sync_provider);

 protected:
  ~NativeViewGLSurfaceEGL() override;

  EGLNativeWindowType window_;

  void OnSetSwapInterval(int interval) override;

 private:
  EGLSurface surface_;
  bool supports_post_sub_buffer_;
  EGLConfig config_;
  gfx::Size size_;

  scoped_ptr<VSyncProvider> vsync_provider_;

  int swap_interval_;

  DISALLOW_COPY_AND_ASSIGN(NativeViewGLSurfaceEGL);
};

// Encapsulates a pbuffer EGL surface.
class GL_EXPORT PbufferGLSurfaceEGL : public GLSurfaceEGL {
 public:
  PbufferGLSurfaceEGL(const gfx::Size& size,
                      const gfx::SurfaceConfiguration requested_configuration);

  // Implement GLSurface.
  EGLConfig GetConfig() override;
  bool Initialize() override;
  void Destroy() override;
  bool IsOffscreen() override;
  bool SwapBuffers() override;
  gfx::Size GetSize() override;
  bool Resize(const gfx::Size& size) override;
  EGLSurface GetHandle() override;
  void* GetShareHandle() override;

 protected:
  ~PbufferGLSurfaceEGL() override;

 private:
  gfx::Size size_;
  EGLSurface surface_;
  EGLConfig config_;

  DISALLOW_COPY_AND_ASSIGN(PbufferGLSurfaceEGL);
};

// SurfacelessEGL is used as Offscreen surface when platform supports
// KHR_surfaceless_context and GL_OES_surfaceless_context. This would avoid the
// need to create a dummy EGLsurface in case we render to client API targets.
class GL_EXPORT SurfacelessEGL : public GLSurfaceEGL {
 public:
  SurfacelessEGL(const gfx::Size& size,
                 SurfaceConfiguration requested_configuration);

  // Implement GLSurface.
  EGLConfig GetConfig() override;
  bool Initialize() override;
  void Destroy() override;
  bool IsOffscreen() override;
  bool IsSurfaceless() const override;
  bool SwapBuffers() override;
  gfx::Size GetSize() override;
  bool Resize(const gfx::Size& size) override;
  EGLSurface GetHandle() override;
  void* GetShareHandle() override;

 protected:
  ~SurfacelessEGL() override;

 private:
  gfx::Size size_;
  DISALLOW_COPY_AND_ASSIGN(SurfacelessEGL);
};

}  // namespace gfx

#endif  // UI_GL_GL_SURFACE_EGL_H_


text:
package oceania.items;

import java.util.List;

import net.minecraft.block.Block;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.EnumMovingObjectType;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import oceania.Oceania;
import oceania.entity.EntitySubmarine;
import oceania.util.OUtil;

import org.lwjgl.input.Keyboard;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class ItemSubmarine extends Item
{
	public ItemSubmarine(int itemID)
	{
		super(itemID);
		setCreativeTab(Oceania.CREATIVE_TAB);
		this.setUnlocalizedName("itemSubmarine");
	}

    public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player)
    {
        float pitch = player.rotationPitch;
        float yaw = player.rotationYaw;
        double pX = player.posX;
        double pY = player.posY;
        double pZ = player.posZ;
        Vec3 playerPos = world.getWorldVec3Pool().getVecFromPool(pX, pY, pZ);
        float yawOffZ = MathHelper.cos((-yaw * OUtil.PI_OVER_180) - (float) Math.PI);
        float yawOffX = MathHelper.sin((-yaw * OUtil.PI_OVER_180) - (float) Math.PI);
        float pitchOffZ = -MathHelper.cos((-pitch) * OUtil.PI_OVER_180);
        float pitchOffY = MathHelper.sin((-pitch) * OUtil.PI_OVER_180);
        float offsetX = yawOffX * pitchOffZ;
        float offsetZ = yawOffZ * pitchOffZ;
        double radius = 5.0;
        Vec3 offset = playerPos.addVector((double)offsetX * radius, (double)pitchOffY * radius, (double)offsetZ * radius);
        MovingObjectPosition hitPos = world.clip(playerPos, offset, true);

        if (hitPos == null)
        {
            return stack;
        }
        else if (hitPos.typeOfHit == EnumMovingObjectType.TILE)
        {
        	int bX = hitPos.blockX;
        	int bY = hitPos.blockY;
        	int bZ = hitPos.blockZ;
        	int bID = world.getBlockId(bX, bY, bZ);

        	if (bID == Block.waterStill.blockID || bID == Block.waterMoving.blockID)
        	{
        		EntitySubmarine sub = new EntitySubmarine(world, bX + 0.5, bY + 1.0, bZ + 0.5);
                sub.rotationYaw = (float)(((MathHelper.floor_double((double)(player.rotationYaw * 4.0f / 360.0f) + 0.5) & 3) - 1) * 90);
                sub.setOwner(player.getEntityName());

        		if (!world.getCollidingBoundingBoxes(sub, sub.boundingBox.expand(-0.1D, -0.1D, -0.1D)).isEmpty())
                    return stack;
        		if (!world.isRemote)
        			world.spawnEntityInWorld(sub);
        		if (!player.capabilities.isCreativeMode)
        			stack.stackSize--;
        	}
        }

    	return stack;
    }

	@Override
	@SideOnly(Side.CLIENT)
	public void registerIcons(IconRegister registry)
	{
		this.itemIcon = registry.registerIcon(Oceania.MOD_ID + ":submarine");
	}

	@Override
	@SideOnly(Side.CLIENT)
    public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List descriptionList, boolean noClueWhatThisEvenDoe)
	{
		if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT))
		{
			descriptionList.add("A Submarine, the best");
			descriptionList.add("in ocean exploration!");
		}
		else
		{
			descriptionList.add(OUtil.colorString("Hold &&9SHIFT &&7for more information"));
		}
	}

}


text:
require 'spec_helper'

describe Date do

  let(:now){ Date.today }
  let(:micro){ now.to_time.to_i * 1000 }

  before do
    @original_zone = Time.zone
    Time.zone = "UTC"
    Timecop.freeze(Time.zone.parse("Thu Nov 25 15:00:00 2010"))
  end

  after do
    Timecop.return
    Time.zone = @original_zone
  end

  specify '#to_html' do
    html = js_span("MMM D, YYYY", micro, "Nov 25, 2010")
    expect(now.to_html).to eq(html)
  end

  specify '#happy' do
    expect(now.happy).to eq("Nov 25, 2010")
  end

end


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

package goca

import (
	"strconv"
	"testing"

	"github.com/OpenNebula/one/src/oca/go/src/goca/schemas/image"
	imgkeys "github.com/OpenNebula/one/src/oca/go/src/goca/schemas/image/keys"
	"github.com/OpenNebula/one/src/oca/go/src/goca/schemas/marketplace"
	mktkeys "github.com/OpenNebula/one/src/oca/go/src/goca/schemas/marketplace/keys"
	mktapp "github.com/OpenNebula/one/src/oca/go/src/goca/schemas/marketplaceapp"
	"github.com/OpenNebula/one/src/oca/go/src/goca/schemas/marketplaceapp/keys"
)

func TestMarketplaceApp(t *testing.T) {
	var mkt_app_name string = "new_mkt_app"
	var mkt_app *mktapp.MarketPlaceApp
	var mkt_img_id int
	var market_id int
	var err error

	mkt_app_tmpl := mktapp.NewTemplate()
	mkt_app_tmpl.Add(keys.Name, mkt_app_name)
	mkt_app_tmpl.Add(keys.Size, "1")
	mkt_app_tmpl.SetType(mktapp.Image)

	//Create an image

	img_tmpl := image.NewTemplate()

	img_tmpl.Add(imgkeys.Name, "test_img_go")
	img_tmpl.Add(imgkeys.Size, "1")
	img_tmpl.SetType(image.Datablock)

	mkt_img_id, err = testCtrl.Images().Create(img_tmpl.String(), 1)
	if err != nil {
		t.Fatalf("Test failed:\n" + err.Error())
	}

	WaitResource(func() bool {
		id, _ := testCtrl.Images().ByName("test_img_go")
		img, _ := testCtrl.Image(id).Info(false)

		state, _ := img.State()

		return state == image.Ready
	})

	if err != nil {
		t.Errorf("Test failed:\n" + err.Error())
	}

	mkt_app_tmpl.Add(keys.OriginID, strconv.Itoa(int(mkt_img_id)))

	//Create a marketplace

	mkt_tmpl := marketplace.NewTemplate()
	mkt_tmpl.Add(mktkeys.Name, "mkt-app-test")
	mkt_tmpl.Add(mktkeys.MarketMAD, "http")
	mkt_tmpl.Add(mktkeys.BaseUrl, "http://url/")
	mkt_tmpl.Add(mktkeys.PublicDir, "/var/loca/market-http")

	market_id, err = testCtrl.MarketPlaces().Create(mkt_tmpl.String())

	if err != nil {
		t.Errorf("Test failed:\n" + err.Error())
	}

	mkt_app_tmpl.Add(keys.MarketPlaceID, strconv.Itoa(int(market_id)))
	//Create MarketplaceApp
	app_id, err := testCtrl.MarketPlaceApps().Create(mkt_app_tmpl.String(), int(market_id))

	if err != nil {
		t.Errorf("Test failed:\n" + err.Error())
	}

	mkt_app, err = testCtrl.MarketPlaceApp(app_id).Info(false)
	if err != nil {
		t.Errorf("Test failed:\n" + err.Error())
	}

	actual := mkt_app.Name

	if actual != mkt_app_name {
		t.Errorf("Test failed, expected: '%s', got:  '%s'", mkt_app_name, actual)
	}

	//Delete MarketplaceApp
	err = testCtrl.MarketPlaceApp(app_id).Delete()

	if err != nil {
		t.Errorf("Test failed:\n" + err.Error())
	}

	//delete image
	err = testCtrl.Image(mkt_img_id).Delete()

	if err != nil {
		t.Errorf("Test failed:\n" + err.Error())
	}

	//delete marketplace
	err = testCtrl.MarketPlace(market_id).Delete()

	if err != nil {
		t.Errorf("Test failed:\n" + err.Error())
	}
}


text:
require 'evopop'

def drive(population)
  (0...population.max_generations).each do |i|
    population.train
    population.crossover
    population.mutate if i != population.max_generations - 1
  end

  population
end

population = Evopop::Population.new

drive population

# Sort and print out candidate with highest fitness in the last generation.
population.train
puts <<~DEBUG
  Finished #{population.max_generations} generations with the fittest
  candidate with a dna of #{population.candidates[0].dna} and a fitness
  of #{population.candidates[0].fitness}.
DEBUG


text:
export LR_SYNTH_IP_NAME=aes
export LR_SYNTH_TOP_MODULE=aes

# Setup module parameters.
export LR_SYNTH_AES_192_ENABLE=1
export LR_SYNTH_SEC_MASKING=1
export LR_SYNTH_SEC_S_BOX_IMPL=4

# Setup cell library path.
# Uncomment the lines below and set the path to an appropriate .lib file
# export LR_SYNTH_CELL_LIBRARY_PATH=/path/to/NangateOpenCellLibrary_typical.lib
# export LR_SYNTH_CELL_LIBRARY_NAME=nangate
if [ -z "$LR_SYNTH_CELL_LIBRARY_PATH" ]; then
    echo >&2 "You forgot to set LR_SYNTH_CELL_LIBRARY_PATH!";
    exit 1;
fi
if [ -z "$LR_SYNTH_CELL_LIBRARY_NAME" ]; then
    echo >&2 "You forgot to set LR_SYNTH_CELL_LIBRARY_NAME!";
    exit 1;
fi

# Control synthesis flow.
export LR_SYNTH_TIMING_RUN=0
export LR_SYNTH_FLATTEN=1

# For timing runs, hierarchy flattening is needed.
if [[ $LR_SYNTH_TIMING_RUN == 1 ]] && [[ $LR_SYNTH_FLATTEN == 0 ]]; then
    echo >&2 "LR_SYNTH_TIMING_RUN requires LR_SYNTH_FLATTEN!";
    exit 1;
fi

# Output directory
if [ $# -eq 1 ]; then
    export LR_SYNTH_OUT_DIR=$1
elif [ $# -eq 0 ]; then
    export LR_SYNTH_OUT_DIR_PREFIX="syn_out/${LR_SYNTH_TOP_MODULE}"
    LR_SYNTH_OUT_DIR=$(date +"${LR_SYNTH_OUT_DIR_PREFIX}_%Y_%m_%d_%H_%M_%S")
    export LR_SYNTH_OUT_DIR
else
    echo "Usage $0 [synth_out_dir]"
    exit 1
fi


text:
package es.tmg.cordovaplugin.httpsrequest;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import es.tmg.cordovaplugin.httpsrequest.utils.PluginDefs;

/**
 * HTTPS requests Cordova Plugin
 * @author Jose Antonio Nogales Rincón
 *
 */
public class RequestQueuePlugin extends CordovaPlugin {
	//static progress dialog
	private static ProgressDialog progress;

	@Override
	public boolean execute(final String action, final JSONArray args,
			final CallbackContext callbackContext) throws JSONException {

		/**
		 * Function arguments at index:
		 * - 0: REST service URL
		 * - 1: params of the URL. It will be concatenated as ?param1=value1&param2=value2...
		 * - 2: Type of the request. Values: POST, GET, PUT, DELETE
		 * - 3: Header params in JSON format. {"param1": "value1", "param2", "value2"}
		 * - 4: Body params in JSON format. {"param1": "value1", "param2": "value2"}
		 * - 5 & 6: if show and hide are true, a progress dialog opens at the beginning and closes at the end of request.
		 * 			if show and hide are false, anything happens
		 * 			if show and not hide, a progress dialog opens at the beginning but not close at the end (useful if you need to make several requests and this is not the last request)
		 *    		if not show and hide, a progress dialog closes at the end but not opens at the beginning (useful if you need to make several requests and this is the last request)
		 */
		final String href = args.getString(0);
		final String params = args.getString(1);
		final String type = args.getString(2);
		final JSONObject headerJson = getJSONObject(args, 3);
		final JSONObject bodyJson = getJSONObject(args, 4);
		final boolean showLoading = args.getBoolean(5);
		final boolean hideLoading = args.getBoolean(6);

		if (showLoading) {
			progress = ProgressDialog.show(cordova.getActivity(),
				PluginDefs.EMPTY_STRING, cordova.getActivity().getResources().getString(R.string.loading), true, false);
		}

		//Makes the operation in a background thread to not block the main thread
		cordova.getThreadPool().execute(new Runnable() {
			public void run() {
				new  RequestQueueTask(href, type, params, headerJson, bodyJson, callbackContext, cordova.getActivity(), progress, hideLoading).execute();
			};
		});

		return true;
	}

	/**
	 * Method that recovers a value in a specific position
	 * @param args JSON Array with values
	 * @param index Index of the value to be recovered
	 * @return JSONObject with the recovered value
	 */
	private JSONObject getJSONObject(JSONArray args, int index) {
		JSONObject json = null;
		try {
			if (args.length() > index) {
				json = args.getJSONObject(index);
			}
		} catch(Exception e) { }

		return json;
	}

}


text:
from django.contrib import admin
from models import User, Topic, Room, Message

class UserAdmin(admin.ModelAdmin):
    pass

class TopicAdmin(admin.ModelAdmin):
    pass

class RoomAdmin(admin.ModelAdmin):
    pass

class MessageAdmin(admin.ModelAdmin):
    pass

admin.site.register(User, UserAdmin)
admin.site.register(Topic, TopicAdmin)
admin.site.register(Room, RoomAdmin)
admin.site.register(Message, MessageAdmin)


text:
package edu.mit.ll.nics.common.email;

import java.io.IOException;
import javax.xml.bind.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.StringWriter;

import org.apache.camel.ProducerTemplate;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;

/**
 *BUILD AN EMAIL MESSAGE
 */
public class XmlEmail {

    /**
     *
Member: CNAME

     *
Description:
     * Class name for logging.
     *

     */
    private static final String CNAME = XmlEmail.class.getName();
    /**
     *
Member: log

     *
Description:
     * The logger.
     *

     */
    private static final Logger log = Logger.getLogger(CNAME);
    /**
     * Default destination url
     * rabbitmq topic on the
     * amqp bus on local machine
     *
     * OLD: "rabbitmq://localhost:5672?amqExchange=amq.topic&amqExchangeType=topic&requestedHeartbeat=0&routingKey=LDDRS.alert.email&noAck=false&user=guest&password=guest&msgPersistent=false&msgContentType=text"
     */
    private String defDstUrl =  "rabbitmq://localhost:5672/iweb.amq.topic?exchangeType=topic&requestedHeartbeat=0&routingKey=iweb.alert.email&autoAck=false&user=guest&password=guest";
    private ObjectFactory of = null;
    private EmailType et = null;
    private Marshaller marsh = null;
    private HeaderType head = null;
    private ContentType content = null;
    private BodyType body = null;
    private ImageType image = null;
    private String dstUrl = null;
    private StringWriter sw = null;
    private File imgFile = null;
    private ProducerTemplate pt = null;

    /**
     * Constructor takes in required email header values and populates a jaxb
     * object that will later be marshalled into an xml string
     * @param from = from email address
     * @param to = to email address(es) Comma separate multiple addresses
     * @param subj = subject of email
     */
    protected XmlEmail(final String from, final String to, final String subj, ProducerTemplate pt) {
        of = new ObjectFactory();
        et = new EmailType();
        head = of.createHeaderType();
        content = of.createContentType();
        body = of.createBodyType();
        image = of.createImageType();
        this.pt = pt;

        //Add header
        head.setFrom(from);
        head.setTo(to);
        head.setSubject(subj);
        et.setHeader(head);

        //Initialize content
        content.setBody(body);
        content.setImage(image);
        et.setContent(content);
    }

    /**
     * Makes the string body_text  the body of the e-mail
     * @param body_text
     */
    public void setBody(final String body_text) {
        setBody(body_text, "text");
    }

    /**
     * Makes the string body_test the body of the e-mail with a tag of the body
     * text format (default = text, i.e. HTML,JSON) to assist later message processing
     * @param body_text
     * @param format
     */
    public void setBody(final String body_text, final String format) {
        body.setText(body_text);
        body.setFormat(format);
        content.setBody(body);
        et.setContent(content);
    }

    /**
     * Puts the addresses in string cc on the cc address list
     * @param cc
     */
    public void setCC(final String cc) {
        head.setCc(cc);
    }

    /**
     * Puts the addresses in string bcc on the bcc address list
     * @param bcc
     */
    public void setBCC(final String bcc) {
        head.setBcc(bcc);
    }

    /**
     * Adds an embedded jpeg image located at image_filename
     * @param image_filename
     */
    public void setEmbeddedJpeg(String image_filename) {
        setImage(image_filename, "embed");
    }

    /**
     * Attaches a jpeg image located at image_filename
     * @param image_filename
     * @throws IOException
     */
    public void setAttachedJpeg(String image_filename) {
        setImage(image_filename, "attach");
    }

    /**
     * Reads the image file image_filename into a buffered image that can be
     * marshalled into XML
     * @param image_filename
     * @param location
     */
    private void setImage(String image_filename, String location) {
        imgFile = new File(image_filename);
        BufferedImage bimg;
        try {
            bimg = ImageIO.read(imgFile);
            //Image img = bimg.getScaledInstance(512, -1, Image.SCALE_DEFAULT);
            image.setJPEGPicture(bimg);
            image.setLocation(location);
            content.setImage(image);
            et.setContent(content);
        } catch (IOException ex) {
            log.logp(Level.SEVERE, CNAME, "addImage", ex.toString());
        }
    }
    /**
     * Sends message to the default url
     */
    public void send(){
        send(defDstUrl);
    }
    /**
     * send method marshalls the jaxb object into an xml message and sends it to
     * the dstUrl (topic/room with e-mail consumer)
     * @param url
     */
    public void send(String url) {
        dstUrl = url;
        //Build XML string of Email
        JAXBElement<EmailType> email = of.createEmailMessage(et);

        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(EmailType.class.getPackage().getName());
            marsh = jc.createMarshaller();
            sw = new StringWriter();
            marsh.marshal(email, sw);
            //System.out.println(sw.toString());
        } catch (JAXBException ex) {
            log.logp(Level.SEVERE, CNAME, "marshall", ex.toString());
        }

        pt.sendBody(dstUrl, sw.toString().getBytes());
    }
}


text:
package edu.utdallas.db.uxg140230.model;

public class Flight {
	private String flightNumber;
	private byte weekdays;

	public String getFlightNumber() {
		return flightNumber;
	}
	public void setFlightNumber(String flightNumber) {
		this.flightNumber = flightNumber;
	}
	public byte getWeekdays() {
		return weekdays;
	}
	public void setWeekdays(byte weekdays) {
		this.weekdays = weekdays;
	}

}


text:
var CursorMaintenanceExamples = (function () {
  'use strict';

  // requires: cursor_maintenance.js

  // The CursorMaintenanceExamples module defines two plain formatters and
  //  uses them as the basis for a collection of cursor-maintaining formatters
  //  using various approaches. A plain formatter is a function that takes raw
  //  text and returns formatted text. A cursor-maintaining formatter takes
  //  raw text and a cursor position in the raw text; it returns formatted
  //  text and a new cursor position.

  var CM = CursorMaintenance,
      plain,          // Plain formatters: no cursor maintenance.
      wrapped,        // Plain formatters posing as cursor maintainers.
      adHoc,          // Reimplementation of formats with cursor maintenance.
      mockCursor,     // Ad hoc approach with the help of a mock cursor.
      meta,           // Reimplementation on a text-with-cursor object.
      retrospective,  // Format-independent statistical cursor maintenance.
      layer;          // A statistical approach configured per format.

  //--- Plain formatters: Text transformations with no cursor. The same
  //  two formats, commatize and trimify, are used throughout this module
  //  as the basis for various approaches to cursor maintenance.

  plain = {};

  // commatize takes a string of digits and commas. It arranges commas so
  //  that they separate the digits into groups of three. For example,
  //  "1,45,,00" gets commatized to "14,500".
  plain.commatize = function (s) {           // s is a string composed of
    var start, groups, i;                    //  digits and commas.
    s = s.replace(/,/g, '');                 // Remove all commas.
    start = s.length % 3 || 3;               // Begin with 1, 2, or 3 digits.
    groups = [ s.substring(0, start) ];      // Make the first group of digits.
    for (i = start; i < s.length; i += 3) {
      groups.push(s.substring(i, i + 3));    // Add three-digit groups.
    }
    s = groups.join(',');                    // Insert commas between groups.
    return s;
  };

  // trimify removes all whitespace from the beginning of the string and
  //  reduces other whitespace sequences to a single space each. For example,
  //  "  Four score  and  seven  " gets trimified to "Four score and seven ".
  plain.trimify = function (s) { // s is an arbitrary string.
    s = s.replace(/^\s+/, '');   // Remove whitespace from the beginning.
    s = s.replace(/\s+/g, ' ');  // Condense remaining whitespace sequences
    return s;                    //  to one space each.
  };

  // creditCard extracts up to 16 digits from the string and renders them
  //  in four-digit groups separated by spaces. This format isn't exercised
  //  to the same extent as commatize and trimify. In particular, the
  //  ad hoc and mock-cursor versions are missing.
  plain.creditCard = function (s) {      // s is an arbitrary string.
    var groups = [],
        i;
    s = s.replace(/\D/g, '');            // Remove all non-digit characters.
    s = s.substring(0, 16);              // Keep no more than 16 digits.
    for (i = 0; i < s.length; i += 4) {  // Make four-digit groups.
      groups.push(s.substring(i, i + 4));
    }
    return groups.join(' ');             // Put spaces between the groups.
  };

  //--- Wrapped versions of the plain formatters. These functions have the
  //  same interface as cursor-maintaining formatters, but they don't
  //  really maintain the cursor. They return the raw cursor position as is.

  wrapped = {};

  wrapped.commatize = function (s, cursor) {
    return { text: plain.commatize(s), cursor: cursor };
  };

  wrapped.trimify = function (s, cursor) {
    return { text: plain.trimify(s), cursor: cursor };
  };

  wrapped.creditCard = function (s, cursor) {
    return { text: plain.creditCard(s), cursor: cursor };
  };

  //--- Ad hoc cursor maintenance: Reimplementing the format in such a way
  //  that we keep track of the cursor position while transforming the text.

  adHoc = {};

  // count returns the number of occurrences (possibly overlapping) of the
  //  string sub in the string s. It is called by adHoc.commatize.
  function count(s, sub) {
    var count = 0,
        searchedTo = -1;
    while ((searchedTo = s.indexOf(sub, searchedTo + 1)) != -1) {
      ++count;
    }
    return count;
  }

  // adHoc.commatize counts digits to the left of the cursor in the
  //  raw state, calls the plain commatizer, then counts off the same
  //  number of digits in the commatized text.
  adHoc.commatize = function (s, cursor) {
    var pos, ch,
        leftDigitCount = cursor - count(s.substring(0, cursor), ',');
    s = wrapped.commatize(s).text;
    if (leftDigitCount == 0) {
      return { text: s, cursor: 0 };
    }
    for (pos = 0; pos < s.length; ++pos) {
      ch = s.charAt(pos);
      if (ch != ',') {
        if (--leftDigitCount == 0) {
          break;
        }
      }
    }
    cursor = pos + 1;
    return { text: s, cursor: cursor };
  };

  // adHoc.trimify appends a non-space character to the left part of the
  //  raw text and trimifies it. This gives us the new cursor position
  //  unless the entire trimified text ends up shorter, which will happen
  //  when the cursor is among space characters at the right end of the text.
  adHoc.trimify = function (s, cursor) {
    var leftTrimmed = wrapped.trimify(s.substring(0, cursor) + '|').text;
    s = wrapped.trimify(s).text;
    cursor = Math.min(s.length, leftTrimmed.length - 1);
    return { text: s, cursor: cursor };
  };

  //--- Mock cursor: A variation on the ad hoc approach in which we insert a
  //  special character into the raw text at the cursor position. We then
  //  reimplement the format in such a way that this special character, the
  //  mock cursor, is preserved while we transform the text around it.
  //  Afterward, the mock cursor is removed from the text and its final
  //  position is returned as the new cursor position.

  mockCursor = {};

  // chooseCursorChar returns a printable ASCII character (numbers 32 through
  //  126) that does not occur in the given text. If all printable characters
  //  occur, the return value is null. chooseCursorChar is called by
  //  mockCursor.augment.
  function chooseCursorChar(s) {
    var usedChars = {},
        seekChars = '|^_#',  // Try these first because we like them best.
        i, ch, code;
    for (i = 0; i < s.length; ++i) {
      usedChars[s.charAt(i)] = true;
    }
    // Try our favorite characters.
    for (i = 0; i < seekChars.length; ++i) {
      ch = seekChars.charAt(i);
      if (!(ch in usedChars)) {
        return ch;
      }
    }
    // Try all printable ASCII characters.
    for (code = 32; code <= 126; ++code) {
      ch = String.fromCharCode(code);
      if (!(ch in usedChars)) {
        return ch;
      }
    }
    return null;
  }

  // mockCursor.augment takes a formatter that works on text with a mock
  //  cursor, and returns a cursor-maintaining formatter that uses the
  //  mock-cursor approach. In other words, mockCursor.augment handles the
  //  routine work of inserting the mock cursor prior to formatting and
  //  removing it afterward. The real work of formatting text with a mock
  //  cursor is done by the input function, which takes two arguments:
  //  the first is the raw text, the second is the character representing
  //  the mock cursor; the return value is the formatted text.
  mockCursor.augment = function (format) {
    return function (s, cursor) {
      var cursorChar = chooseCursorChar(s),
          t = s.substring(0, cursor) + cursorChar + s.substring(cursor),
          formatted = format(t, cursorChar),
          cursor = formatted.indexOf(cursorChar),
          text = formatted.replace(cursorChar, '');
      return { text: text, cursor: cursor };
    };
  }

  // mockCursor.commatize scans the raw text from right to left, skipping
  //  commas and counting digits. Groups of non-comma characters that include
  //  three digits are joined with commas. The leftmost character in such a
  //  group is always a digit, so the cursor can never be the right-hand
  //  neighbor of a comma. If the cursor is between digit groups, it must be
  //  to the left of the comma.
  mockCursor.commatize = mockCursor.augment(function (s, cursorChar) {
    var groups = [],
        groupChars = [],
        digitCount = 0,
        i, ch;
    for (i = s.length - 1; i >= 0; --i) {
      ch = s.charAt(i);
      if (ch != ',') {
        groupChars.push(ch);
        if (ch != cursorChar) {
          if (++digitCount == 3) {
            // Reverse the group to put the digits in left-to-right order.
            groups.push(groupChars.reverse().join(''));
            groupChars = [];
            digitCount = 0;
          }
        }
      }
    }
    // There may be one or two digits left over in the final group.
    if (groupChars.length > 0) {
      groups.push(groupChars.reverse().join(''));
    }
    s = groups.reverse().join(',');
    // If the mock cursor ended up on its own in the final group, we
    //  have a spurious comma. Check for this case and delete the comma.
    if (s.charAt(0) == cursorChar && s.charAt(1) == ',') {
      s = cursorChar + s.substring(2);
    }
    return s;
  });

  // mockCursor.trimify calls the plain trimifier on the raw text, then
  //  fixes the formatting around the mock cursor. There are two cases
  //  to check for: either the mock cursor is the leftmost character and has
  //  a space to its right, or it is between exactly two spaces.
  mockCursor.trimify = mockCursor.augment(function (s, cursorChar) {
    s = wrapped.trimify(s).text;
    if (s.charAt(0) == cursorChar) {
      s = s.replace(cursorChar + ' ', cursorChar);
    } else {
      s = s.replace(' ' + cursorChar + ' ', ' ' + cursorChar);
    }
    return s;
  });

  //--- Meta approach: We reimplement the format with elementary operations
  //  (length, read, insert, delete) on a text-with-cursor object. The
  //  CursorMaintenance module defines TextWithCursor for this purpose. Each
  //  elementary operation has a predictable effect on the cursor. We want
  //  to keep these effects in mind as we implement the formatter so that
  //  we control the overall movement of the cursor and make it predictable
  //  to the end user, too.

  meta = {};

  // meta.commatize scans the raw text from right to left, deleting commas
  //  and counting digits. If we come upon a digit when we have already
  //  counted three digits, we insert a comma to the right of this digit
  //  and set the digit count to one.
  meta.commatize = function (s, cursor) {
    var t = new CM.TextWithCursor(s, cursor),
        digitCount = 0,
        pos;
    for (pos = t.length() - 1; pos >= 0; --pos) {
      if (t.read(pos) == ',') {
        t.delete(pos);
      } else if (digitCount == 3) {
        t.insert(pos + 1, ',');
        digitCount = 1;
      } else {
        ++digitCount;
      }
    }
    return t;
  };

  // meta.trimify scans the raw text from right to left, deleting every
  //  space except the leftmost space in each contiguous space sequence.
  //  Finally, if the leftmost character is a space, it is deleted.
  meta.trimify = function (s, cursor) {
    var t = new CM.TextWithCursor(s, cursor),
        spaceCount = 0,
        pos;
    for (pos = t.length() - 1; pos >= 0; --pos) {
      if (t.read(pos) != ' ') {
        spaceCount = 0;     // We are not in a space sequence.
      } else if (spaceCount == 0) {
        spaceCount = 1;     // We are at the rightmost space in a sequence.
      } else {
        t.delete(pos + 1);  // There is a space to the right; delete it.
      }
    }
    if (t.read(0) == ' ') {
      t.delete(0);  // Check for a single space remaining at the left end.
    }
    return t;
  };

  meta.creditCard = function (s, cursor) {
    var t = new CM.TextWithCursor(s, cursor),
        pos, start;
    for (pos = t.length() - 1; pos >= 0; --pos) {
      if (!/\d/.test(t.read(pos))) {  // Remove all non-digit characters.
        t.delete(pos);
      }
    }
    if (t.length() > 16) {            // Keep no more than 16 digits.
      t.delete(16, t.length() - 16);
    }
    start = Math.min(12, t.length() - t.length()%4);
    for (pos = start; pos > 0; pos -= 4) {
      t.insert(pos, ' ');             // Put spaces between four-digit groups.
    }
    return t;
  };

  //--- Retrospective approach: An open-ended statistical approach that
  //  relies on a cost function. The CursorMaintenance module defines a
  //  retrospective format augmenter and two cost functions, which we use
  //  here to instantiate cursor-maintaining formatters for commatize and
  //  trimify.

  retrospective = {};

  [ 'splitLevenshtein', 'frequencyRatios' ].forEach(function (name) {
    var costFunction = CM.retrospective.costFunctions[name],
        augment = function (plainFormatter) {
          return CM.retrospective.augmentFormat(plainFormatter, costFunction);
        };
    retrospective[name] = {
      commatize: augment(plain.commatize),
      trimify: augment(plain.trimify),
      creditCard: augment(plain.creditCard)
    };
  });

  //  The retrospective.splitLevenshtein and retrospective.frequencyRatios
  //  objects each contain cursor-maintaining formatters for commatize and
  //  trimify. Thus, they have the same interface as format, adHoc,
  //  mockCursor, meta, and layer.

  //--- Layer approach: A statistical approach that scans text layers induced
  //  by character sets. To configure this approach for a format, we define
  //  a sequence of character sets and optionally specify whether ties should
  //  should be broken by choosing the leftmost or rightmost candidate (the
  //  default is leftmost). Here we build cursor-maintaining formatters for
  //  commatize and trimify using the layer facilities of CursorMaintenance.

  layer = {};

  layer.commatize = CM.layer.augmentFormat(plain.commatize, [ /\d/ ]);

  layer.trimify = CM.layer.augmentFormat(plain.trimify, [ /\S/ ], true);

  layer.creditCard = CM.layer.augmentFormat(plain.creditCard, [ /\d/ ]);

  return {
    plain: plain,
    wrapped: wrapped,
    adHoc: adHoc,
    mockCursor: mockCursor,
    meta: meta,
    splitLevenshtein: retrospective.splitLevenshtein,
    frequencyRatios: retrospective.frequencyRatios,
    layer: layer
  };
})();