text:
package scalax.collection
package rdf

import scalax.collection.OuterImplicits._, scalax.collection.generic._._

/** Custom edge type representing RDF triples as directed hyperedges.
  *
  * This representation stores not only subjects and objects but also
  * predicates as nodes. Predicates are checked for equality.
  * RDF statements with a given predicate can be directly accessed
  * by the edges connecting to the predicate node.
  */
class TripleDiHyperEdge[N] private (nodes: Product) extends DiHyperEdge[N](nodes) {

  private def node(i: Int): N = iterator.drop(i).next match {
    case inner: Graph[N, _]#NodeT @unchecked => inner.value
    case outer                               => outer
  }
  def subject   = node(0).asInstanceOf[Subject]
  def predicate = node(1).asInstanceOf[Predicate]
  def `object`  = node(2).asInstanceOf[Object]

  override def toString = s"($subject, $predicate, ${`object`})"
}

object TripleDiHyperEdge {
  def apply(subject: Subject, predicate: Predicate, `object`: Object) =
    new TripleDiHyperEdge[RdfNode]((subject, predicate, `object`))

  def unapply(edge: TripleDiHyperEdge[RdfNode]): Option[(Subject, Predicate, Object)] =
    Some((edge.subject, edge.predicate, edge.`object`))
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ForkCMS\Modules\Frontend\Domain\Meta;

use Doctrine\ORM\QueryBuilder;
use ForkCMS\Modules\Internationalisation\Domain\Locale\Locale;
use Symfony\Component\String\Slugger\AsciiSlugger;

/**
 * @template T
 */
trait RepositoryWithMetaTrait
{
    private static string $metaSubjectIdField = 'id';

    /** @param T $subject */
    public function slugify(string $string, object $subject, Locale|null $locale = null): string
    {
        $slugger = new AsciiSlugger(Locale::current()->value);
        $slug = $slugger->slug(mb_strtolower($string))->toString();
        $entityAlias = 's';
        $query = $this->createQueryBuilder($entityAlias)
            ->select('COUNT(s)')
            ->innerJoin('s.meta', 'm')
            ->andWhere('m.slug = :slug')
            ->setParameter('locale', $locale)
            ->setParameter('slug', $slug);
        $this->slugifyIdQueryBuilder($query, $subject, $entityAlias);

        if ((int) $query->getQuery()->getSingleScalarResult() == 0) {
            return $slug;
        }

        return $this->slugify($this->addOrIncreaseNumberAtEndOfString($slug), $subject, $locale);
    }

    /** @param T $subject */
    abstract protected function slugifyIdQueryBuilder(QueryBuilder $queryBuilder, object $subject, string $entityAlias): void;

    final protected function addOrIncreaseNumberAtEndOfString(string $string): string
    {
        $chunks = explode('-', $string);
        $last = $chunks[count($chunks) - 1];

        if (ctype_digit($last)) {
            array_pop($chunks);

            // return incremented string
            return implode('-', $chunks) . '-' . ((int) $last + 1);
        }

        return $string . '-1';
    }
}


text:
<?php

namespace Drupal\Tests\migrate_drupal_ui\Functional;

use Drupal\Core\Database\Database;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate_drupal\MigrationConfigurationTrait;
use Drupal\Tests\BrowserTestBase;

/**
 * Provides a base class for testing migration upgrades in the UI.
 */
abstract class MigrateUpgradeTestBase extends BrowserTestBase {
  use MigrationConfigurationTrait;

  /**
   * Use the Standard profile to test help implementations of many core modules.
   */
  protected $profile = 'standard';

  /**
   * The source database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $sourceDatabase;

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = [
    'language',
    'content_translation',
    'migrate_drupal_ui',
    'telephone',
    'aggregator',
    'book',
    'forum',
    'statistics',
    'migration_provider_test',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->createMigrationConnection();
    $this->sourceDatabase = Database::getConnection('default', 'migrate_drupal_ui');

    // Log in as user 1. Migrations in the UI can only be performed as user 1.
    $this->drupalLogin($this->rootUser);
  }

  /**
   * Loads a database fixture into the source database connection.
   *
   * @param string $path
   *   Path to the dump file.
   */
  protected function loadFixture($path) {
    $default_db = Database::getConnection()->getKey();
    Database::setActiveConnection($this->sourceDatabase->getKey());

    if (substr($path, -3) == '.gz') {
      $path = 'compress.zlib://' . $path;
    }
    require $path;

    Database::setActiveConnection($default_db);
  }

  /**
   * Changes the database connection to the prefixed one.
   *
   * @todo Remove when we don't use global. https://www.drupal.org/node/2552791
   */
  protected function createMigrationConnection() {
    $connection_info = Database::getConnectionInfo('default')['default'];
    if ($connection_info['driver'] === 'sqlite') {
      // Create database file in the test site's public file directory so that
      // \Drupal\simpletest\TestBase::restoreEnvironment() will delete this once
      // the test is complete.
      $file = $this->publicFilesDirectory . '/' . $this->testId . '-migrate.db.sqlite';
      touch($file);
      $connection_info['database'] = $file;
      $connection_info['prefix'] = '';
    }
    else {
      $prefix = is_array($connection_info['prefix']) ? $connection_info['prefix']['default'] : $connection_info['prefix'];
      // Simpletest uses fixed length prefixes. Create a new prefix for the
      // source database. Adding to the end of the prefix ensures that
      // \Drupal\simpletest\TestBase::restoreEnvironment() will remove the
      // additional tables.
      $connection_info['prefix'] = $prefix . '0';
    }

    Database::addConnectionInfo('migrate_drupal_ui', 'default', $connection_info);
  }

  /**
   * {@inheritdoc}
   */
  protected function tearDown() {
    Database::removeConnection('migrate_drupal_ui');
    parent::tearDown();
  }

  /**
   * Executes all steps of migrations upgrade.
   */
  public function testMigrateUpgrade() {
    $connection_options = $this->sourceDatabase->getConnectionOptions();
    $this->drupalGet('/upgrade');
    $this->assertSession()->responseContains('Upgrade a site by importing its database and files into a clean and empty new install of Drupal 8.');

    $this->drupalPostForm(NULL, [], t('Continue'));
    $this->assertText('Provide credentials for the database of the Drupal site you want to upgrade.');
    $this->assertFieldByName('mysql[host]');

    $driver = $connection_options['driver'];
    $connection_options['prefix'] = $connection_options['prefix']['default'];

    // Use the driver connection form to get the correct options out of the
    // database settings. This supports all of the databases we test against.
    $drivers = drupal_get_database_types();
    $form = $drivers[$driver]->getFormOptions($connection_options);
    $connection_options = array_intersect_key($connection_options, $form + $form['advanced_options']);
    $version = $this->getLegacyDrupalVersion($this->sourceDatabase);
    $edit = [
      $driver => $connection_options,
      'source_private_file_path' => $this->getSourceBasePath(),
      'version' => $version,
    ];
    if ($version == 6) {
      $edit['d6_source_base_path'] = $this->getSourceBasePath();
    }
    else {
      $edit['source_base_path'] = $this->getSourceBasePath();
    }
    if (count($drivers) !== 1) {
      $edit['driver'] = $driver;
    }
    $edits = $this->translatePostValues($edit);

    // Ensure submitting the form with invalid database credentials gives us a
    // nice warning.
    $this->drupalPostForm(NULL, [$driver . '[database]' => 'wrong'] + $edits, t('Review upgrade'));
    $this->assertText('Resolve the issue below to continue the upgrade.');

    $this->drupalPostForm(NULL, $edits, t('Review upgrade'));
    $this->assertResponse(200);
    $this->assertText('Are you sure?');
    // Ensure we get errors about missing modules.
    $this->assertSession()->pageTextContains(t('Source module not found for migration_provider_no_annotation.'));
    $this->assertSession()->pageTextContains(t('Source module not found for migration_provider_test.'));
    $this->assertSession()->pageTextContains(t('Destination module not found for migration_provider_test'));

    // Uninstall the module causing the missing module error messages.
    $this->container->get('module_installer')->uninstall(['migration_provider_test'], TRUE);

    // Restart the upgrade process.
    $this->drupalGet('/upgrade');
    $this->assertSession()->responseContains('Upgrade a site by importing its database and files into a clean and empty new install of Drupal 8.');

    $this->drupalPostForm(NULL, [], t('Continue'));
    $this->assertSession()->pageTextContains('Provide credentials for the database of the Drupal site you want to upgrade.');
    $this->assertSession()->fieldExists('mysql[host]');

    $this->drupalPostForm(NULL, $edits, t('Review upgrade'));
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains('Are you sure?');
    // Ensure there are no errors about the missing modules from the test module.
    $this->assertSession()->pageTextNotContains(t('Source module not found for migration_provider_no_annotation.'));
    $this->assertSession()->pageTextNotContains(t('Source module not found for migration_provider_test.'));
    $this->assertSession()->pageTextNotContains(t('Destination module not found for migration_provider_test'));
    // Ensure there are no errors about any other missing migration providers.
    $this->assertSession()->pageTextNotContains(t('module not found'));
    $this->drupalPostForm(NULL, [], t('Perform upgrade'));
    $this->assertText(t('Congratulations, you upgraded Drupal!'));

    // Have to reset all the statics after migration to ensure entities are
    // loadable.
    $this->resetAll();

    $expected_counts = $this->getEntityCounts();
    foreach (array_keys(\Drupal::entityTypeManager()
      ->getDefinitions()) as $entity_type) {
      $real_count = \Drupal::entityQuery($entity_type)->count()->execute();
      $expected_count = isset($expected_counts[$entity_type]) ? $expected_counts[$entity_type] : 0;
      $this->assertEqual($expected_count, $real_count, "Found $real_count $entity_type entities, expected $expected_count.");
    }

    $plugin_manager = \Drupal::service('plugin.manager.migration');
    /** @var \Drupal\migrate\Plugin\Migration[] $all_migrations */
    $all_migrations = $plugin_manager->createInstancesByTag('Drupal ' . $version);
    foreach ($all_migrations as $migration) {
      $id_map = $migration->getIdMap();
      foreach ($id_map as $source_id => $map) {
        // Convert $source_id into a keyless array so that
        // \Drupal\migrate\Plugin\migrate\id_map\Sql::getSourceHash() works as
        // expected.
        $source_id_values = array_values(unserialize($source_id));
        $row = $id_map->getRowBySource($source_id_values);
        $destination = serialize($id_map->currentDestination());
        $message = "Migration of $source_id to $destination as part of the {$migration->id()} migration. The source row status is " . $row['source_row_status'];
        // A completed migration should have maps with
        // MigrateIdMapInterface::STATUS_IGNORED or
        // MigrateIdMapInterface::STATUS_IMPORTED.
        if ($row['source_row_status'] == MigrateIdMapInterface::STATUS_FAILED || $row['source_row_status'] == MigrateIdMapInterface::STATUS_NEEDS_UPDATE) {
          $this->fail($message);
        }
        else {
          $this->pass($message);
        }
      }
    }
    \Drupal::service('module_installer')->install(['forum']);
    \Drupal::service('module_installer')->install(['book']);
  }

  /**
   * Transforms a nested array into a flat array suitable for BrowserTestBase::drupalPostForm().
   *
   * @param array $values
   *   A multi-dimensional form values array to convert.
   *
   * @return array
   *   The flattened $edit array suitable for BrowserTestBase::drupalPostForm().
   */
  protected function translatePostValues(array $values) {
    $edit = [];
    // The easiest and most straightforward way to translate values suitable for
    // BrowserTestBase::drupalPostForm() is to actually build the POST data string
    // and convert the resulting key/value pairs back into a flat array.
    $query = http_build_query($values);
    foreach (explode('&', $query) as $item) {
      list($key, $value) = explode('=', $item);
      $edit[urldecode($key)] = urldecode($value);
    }
    return $edit;
  }

  /**
   * Gets the source base path for the concrete test.
   *
   * @return string
   *   The source base path.
   */
  abstract protected function getSourceBasePath();

  /**
   * Gets the expected number of entities per entity type after migration.
   *
   * @return int[]
   *   An array of expected counts keyed by entity type ID.
   */
  abstract protected function getEntityCounts();

}


text:
package hbase.tableDesign;

import static org.apache.hadoop.hbase.util.Bytes.toBytes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.QualifierFilter;
import org.apache.hadoop.hbase.util.Bytes;

public class FlatAndWideTableDataFacade implements DataFacade {

	private final HTable table;
	private final static byte [] ENTRY_FAMILY = toBytes("entry");
	public FlatAndWideTableDataFacade(Configuration conf) throws IOException{
		table = new HTable(conf, "Blog_FlatAndWide");
	}
	@Override
	public void close() throws IOException{
		table.close();
	}

	@Override
	public void save(Blog blog) throws IOException {
		Put put = new Put(toBytes(blog.getUsername()));
		put.add(ENTRY_FAMILY, toBytes(dateToColumn(blog.getCreated())),
				toBytes(blog.getBlogEntry()));
		table.put(put);
	}

	private String dateToColumn(Date date ){
		String reversedDateAsStr=
				Long.toString(Long.MAX_VALUE-date.getTime());
		StringBuilder builder = new StringBuilder();
		for ( int i = reversedDateAsStr.length(); i < 19; i++){
			builder.append('0');
		}
		builder.append(reversedDateAsStr);
		return builder.toString();
	}
	public Date columnToDate(String column){
		long reverseStamp = Long.parseLong(column);
		return new Date(Long.MAX_VALUE-reverseStamp);
	}

	@Override
	public List<Blog> getBlogs(String userId,Date startDate, Date endDate) throws IOException {
		List<Blog> blogs = new ArrayList<Blog>();

		Get get = new Get(toBytes(userId));

		FilterList filters = new FilterList();
		filters.addFilter(new QualifierFilter(CompareOp.LESS_OR_EQUAL,
				new BinaryComparator(toBytes(dateToColumn(startDate)))));
		filters.addFilter(new QualifierFilter(CompareOp.GREATER_OR_EQUAL,
				new BinaryComparator(toBytes(dateToColumn(endDate)))));

		get.setFilter(filters);
		Result result = table.get(get);
		Map<byte[], byte[]> columnValueMap = result.getFamilyMap(ENTRY_FAMILY);
		for (Map.Entry<byte[], byte[]> entry : columnValueMap.entrySet()){
			Date createdOn = columnToDate(Bytes.toString(entry.getKey()));
			String blogEntry = Bytes.toString(entry.getValue());
			blogs.add(new Blog(userId, blogEntry, createdOn));
		}

		return blogs;
	}

}


text:
<?php

/**
 * This file is part of the Stippers project (available here: https://github.com/Stannieman/stippers/).
 * The license and all terms en conditions that apply to Stippers also apply to this file.
 *
 * @author Stan Wijckmans
 *
 * The settings in this file are used to validate user input.
 */

abstract class DataValidationConfig {
    const PASSWORD_MIN_LENGTH = 8;
    const PASSWORD_MAX_LENGTH = 1000;
    const EMAIL_MAX_LENGTH = 50;

    const STRING_MAX_LENGTH = 30;
    const HOUSE_NUMBER_MAX_LENGTH = 4;
    const POSTAL_CODE_MIN_LENGTH = 4;
    const POSTAL_CODE_MAX_LENGTH = 6;
    const PHONE_MIN_LENGTH = 9;
    const PHONE_MAX_LENGTH = 14;
    const DATE_MAX_LENGTH = 10;
    const MONEY_MAX_LENGTH = 6;
    const YEAR_MAX_LENGTH = 4;
    const CARD_NUMBER_MAX_LENGTH = 8;
    const CHECK_IN_MESSAGE_MAX_LENGTH = 50;

    const EMAIL_SUBJECT_MAX_LENGTH = 50;
    const EMAIL_FILE_NAME_MAX_LENGTH = 255;
    const EMAIL_FILE_MAX_SIZE = 1048576;

    const ADMIN_PERMISSION_MIN = 0;
    const ADMIN_PERMISSION_MAX = 1;
    const USER_MANAGER_PERMISSION_MIN = 0;
    const USER_MANAGER_PERMISSION_MAX = 1;
    const BROWSER_MANAGER_PERMISSION_MIN = 0;
    const BROWSER_MANAGER_PERMISSION_MAX = 1;
    const MONEY_MANAGER_PERMISSION_MIN = 0;
    const MONEY_MANAGER_PERMISSION_MAX = 1;

    const CHAT_MESSAGE_MAX_LENGTH = 150;
}


text:
using System;
using System.Globalization;
using Xunit;

namespace System.Globalization.Tests
{
    public class DateTimeFormatInfoGetFormat
    {
        // PosTest1: Call GetFormat to to get an valid DateTimeFormatInfo instance
        [Fact]
        public void PosTest1()
        {
            DateTimeFormatInfo expected = new DateTimeFormatInfo();
            object obj = expected.GetFormat(typeof(DateTimeFormatInfo));

            Assert.True(obj is DateTimeFormatInfo);

            DateTimeFormatInfo actual = obj as DateTimeFormatInfo;
            Assert.Equal(expected, actual);
        }

        // PosTest2: If the format type is not supported, null reference should be return
        [Fact]
        public void TestUnsupportedFormatType()
        {
            DateTimeFormatInfo info = new DateTimeFormatInfo();

            Assert.Null(info.GetFormat(typeof(Object)));
        }
    }
}


text:
package org.apache.myfaces.trinidadinternal.share.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * MultipartFormItem - Represent an item from a form file-post.
 * An item can be either a parameter or a file.  If it is a parameter,
 * use getName() and getValue() to get the name and value of the
 * parameter.  If it is a file, then use getFilename and writeFile
 * to find the filename and then write the contents to an OutputStream.
 *
 * @version $Name:  $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/share/util/MultipartFormItem.java#0 $) $Date: 10-nov-2005.18:59:24 $
 */
public interface MultipartFormItem
{

  /**
   * Returns the value of the parameter, or null if this is a file and not
   * a parameter.
   */
  public String getValue();

  /**
   * Returns the input-field name of this item in the form.
   */
  public String getName();

  /**
   * Returns the filename of this item, or null if this is a parameter
   * and not a file
   */
  public String getFilename();

  /**
   * Returns the MIME content type of the file.
   */
  public String getContentType();

  /**
   * Writes the file to the given output stream.  Clients
   * can call this method or getInputStream(), but not both.
   * <p>
   * @see #getInputStream
   * @param stream  the output stream to write to.
   * @return     The total number of bytes written
   * @exception java.io.EOFException if the length of this item
   *   exceeds the maximum length set on the MultipartFormHandler
   * @see org.apache.myfaces.trinidadinternal.share.util.MultipartFormHandler#setMaximumAllowedBytes
   */
  public long writeFile(OutputStream stream)
    throws IOException;

  /**
   * Returns an InputStream that can be used to read the file.  Clients
   * may call this method or writeFile(), but not both.
   * @see #writeFile
   */
  public InputStream getInputStream()
    throws IOException;

}


text:
Upgrading or changing package dependencies
==========================================

``setup.py`` specifies acceptable constraints for package versions, which
usually follow Semantic Versioning conventions. The ``requirements`` files
specify exact versions for consistency between development, CI, and deployments.

1. Delete out and recreate your virtualenv environment, or uninstall packages. (E.g. ``pip uninstall -r requirements.txt``, etc.)
2. Edit ``setup.py``, specifying acceptable version constraints. The ``dev`` group of ``extras_require`` is for development and unit testing.
3. ``pip install -e .``
4. ``pip freeze >> requirements.txt`` and edit ``requirements.txt`` to preserve the ``--index-url`` and ``-e .`` lines.
5. ``pip install -e .[dev] >> test_requirements.txt`` and edit the file as above.
6. ``pip install -e .[doc] >> doc_requirements.txt`` and edit the file as above.

Running Tests
=============

Use ``tox``:

.. code-block:: sh

    pip install -r test_requirements.txt
    tox


text:
namespace hx
{

extern bool gEnableJit;
inline void EnableJit(bool inEnable) { gEnableJit = inEnable; }

#define HXCPP_CPPIA_SUPER_ARG(x) , (x)

struct ScriptNamedFunction : public ScriptFunction
{
   ScriptNamedFunction(const ScriptFunction &s) : ScriptFunction(s), name(0), isStatic(false), superExecute(0) { }

   ScriptNamedFunction(const char *inName=0,StackExecute inExe=0,const char *inSig=0, bool inIsStatic=false, StackExecute superExecute=0)
      : ScriptFunction(inExe, inSig), name(inName), isStatic(inIsStatic), superExecute(superExecute)  { }

   const char *name;
   bool isStatic;
   StackExecute superExecute;
};

inline void SetFloatAligned(void *inPtr, const Float &inValue)
{
   #ifdef HXCPP_ALIGN_FLOAT
   int *dest = (int *)inPtr;
   const int *src = (const int *)&inValue;
   dest[1] = src[1];
   #else
   *(Float *)inPtr = inValue;
   #endif
}

inline Float GetFloatAligned(const void *inPtr)
{
   #ifdef HXCPP_ALIGN_FLOAT
   Float result;
   int *dest = (int *)&result;
   const int *src = (const int *)inPtr;
   dest[0] = src[0];
   dest[1] = src[1];
   return result;
   #else
   return *(Float *)inPtr;
   #endif
}

inline void StackContext::pushFloat(Float f)
{
   SetFloatAligned(pointer, f);
   pointer += sizeof(Float);
}
inline void StackContext::pushString(const String &s)
{
   *(String *)pointer = s;
   pointer += sizeof(String);
}

inline void StackContext::pushObject(Dynamic d)
{
   *(hx::Object **)pointer = d.mPtr;
   pointer += sizeof(hx::Object *);
}

inline void StackContext::returnFloat(Float f)
{
   SetFloatAligned(frame, f);
}
inline void StackContext::returnString(const String &s)
{
   *(String *)frame = s;
}
inline void StackContext::returnObject(Dynamic d)
{
   *(hx::Object **)frame = d.mPtr;
}

inline hx::Object *StackContext::getThis(bool inCheckPtr)
{
   #ifdef HXCPP_CHECK_POINTER
      if (inCheckPtr)
      {
         if (!*(hx::Object **)frame) NullReference("This", false);
         #ifdef HXCPP_GC_CHECK_POINTER
         GCCheckPointer(*(hx::Object **)frame);
         #endif
      }
   #endif
   return *(hx::Object **)frame;
}

inline Float StackContext::getFloat(int inPos)
{
   return GetFloatAligned(frame+inPos);
}
inline String StackContext::getString(int inPos)
{
   return *(String *)(frame+inPos);
}
inline Dynamic StackContext::getObject(int inPos)
{
   return *(hx::Object **)(frame+inPos);
}

enum SignatureChar
{
   sigVoid = 'v',
   sigInt = 'i',
   sigFloat = 'f',
   sigString = 's',
   sigObject = 'o',
};

struct AutoStack
{
   CppiaCtx *ctx;
   unsigned char *pointer;
   unsigned char *frame;

   AutoStack(CppiaCtx *inCtx) : ctx(inCtx)
   {
      frame = ctx->frame;
      pointer = ctx->pointer;
      ctx->frame = pointer;
   }
   AutoStack(CppiaCtx *inCtx,unsigned char *inPointer) : ctx(inCtx)
   {
      frame = ctx->frame;
      pointer = inPointer;
      ctx->frame = pointer;
   }

   ~AutoStack()
   {
      ctx->pointer = pointer;
      ctx->frame = frame;
   }
};

typedef hx::Object * (*ScriptableClassFactory)(void **inVTable,int inDataSize);
typedef hx::Object * (*ScriptableInterfaceFactory)(void **inVTable,::hx::Object *);

void ScriptableRegisterClass( String inName, int inBaseSize, ScriptNamedFunction *inFunctions, ScriptableClassFactory inFactory, ScriptFunction inConstruct);

#if (HXCPP_API_LEVEL >= 330)
void ScriptableRegisterInterface( String inName, ScriptNamedFunction *inFunctions, void *inInterfacePointers);
void ScriptableRegisterNameSlots(const char *inNames[], int inLength);

#else
void ScriptableRegisterInterface( String inName, ScriptNamedFunction *inFunctions,const hx::type_info *inType, ScriptableInterfaceFactory inFactory);
#endif

::String ScriptableToString(void *);
hx::Class ScriptableGetClass(void *);
int ScriptableGetType(void *);
void ScriptableMark(void *, hx::Object *, HX_MARK_PARAMS);
void ScriptableVisit(void *, hx::Object *, HX_VISIT_PARAMS);
bool ScriptableField(hx::Object *, const ::String &,hx::PropertyAccess inCallProp,Dynamic &outResult);
bool ScriptableField(hx::Object *, int inName,hx::PropertyAccess inCallProp,Float &outResult);
bool ScriptableField(hx::Object *, int inName,hx::PropertyAccess inCallProp,Dynamic &outResult);
void ScriptableGetFields(hx::Object *inObject, Array< ::String> &outFields);
bool ScriptableSetField(hx::Object *, const ::String &, Dynamic inValue,hx::PropertyAccess inCallProp, Dynamic &outValue);

class CppiaLoadedModule_obj : public ::hx::Object
{
public:
   virtual void run() = 0;
   virtual void boot() = 0;
   virtual ::hx::Class resolveClass( ::String inName) = 0;
};
typedef ::hx::ObjectPtr<CppiaLoadedModule_obj> CppiaLoadedModule;

} // End namespace hx

void __scriptable_load_neko(String inName);
void __scriptable_load_cppia(String inCode);
::hx::CppiaLoadedModule __scriptable_cppia_from_string(String inCode);
void __scriptable_load_neko_bytes(Array<unsigned char> inBytes);
void __scriptable_load_abc(Array<unsigned char> inBytes);

#if (HXCPP_API_LEVEL >= 330)

#define HX_SCRIPTABLE_REGISTER_INTERFACE(name,class) \
    hx::ScriptableRegisterInterface( HX_CSTRING(name), __scriptableFunctions, & class##_scriptable )

#else

#define HX_SCRIPTABLE_REGISTER_INTERFACE(name,class) \
    hx::ScriptableRegisterInterface( HX_CSTRING(name), __scriptableFunctions, &typeid(class), class##__scriptable::__script_create )

#endif

#define HX_SCRIPTABLE_REGISTER_CLASS(name,class) \
   hx::ScriptableRegisterClass( HX_CSTRING(name), (int)offsetof(class##__scriptable,__scriptVTable) + sizeof(void *), __scriptableFunctions, class##__scriptable::__script_create, class##__scriptable::__script_construct )

#ifdef HXCPP_VISIT_ALLOCS
#define SCRIPTABLE_VISIT_FUNCTION \
void __Visit(HX_VISIT_PARAMS) { super::__Visit(HX_VISIT_ARG); hx::ScriptableVisit(__scriptVTable[-1],this,HX_VISIT_ARG); }
#else
#define SCRIPTABLE_VISIT_FUNCTION
#endif

#define HX_DEFINE_SCRIPTABLE(ARG_LIST) \
   inline void *operator new( size_t inSize, int inExtraDataSize ) \
   { \
      return hx::InternalNew(inSize + inExtraDataSize,true); \
   } \
   inline void operator delete(void *,int) {} \
   public: \
   void **__scriptVTable; \
   static hx::Object *__script_create(void **inVTable, int inExtra) { \
    __ME *result = new (inExtra) __ME(); \
    result->__scriptVTable = inVTable; \
   return result; } \
   void ** __GetScriptVTable() { return __scriptVTable; } \
   ::String toString() {  if (__scriptVTable[0] ) \
     { hx::CppiaCtx *ctx = hx::CppiaCtx::getCurrent(); hx::AutoStack a(ctx); ctx->pushObject(this); return ctx->runString(__scriptVTable[0]); } \
      else return __superString::toString(); } \
   ::String __ToString() const { return hx::ScriptableToString(__scriptVTable[-1]); } \
   hx::Class __GetClass() const { return hx::ScriptableGetClass(__scriptVTable[-1]); } \
   int __GetType() const { return hx::ScriptableGetType(__scriptVTable[-1]); } \
   void __Mark(HX_MARK_PARAMS) { super::__Mark(HX_MARK_ARG); hx::ScriptableMark(__scriptVTable[-1],this,HX_MARK_ARG); } \
   SCRIPTABLE_VISIT_FUNCTION

#define HX_DEFINE_SCRIPTABLE_INTERFACE \
   void **__scriptVTable; \
   Dynamic mDelegate; \
   hx::Object *__GetRealObject() { return mDelegate.mPtr; } \
   SCRIPTABLE_VISIT_FUNCTION \
   void ** __GetScriptVTable() { return __scriptVTable; } \
   public: \
   static hx::Object *__script_create(void **inVTable,hx::Object *inDelegate) { \
    __ME *result = new __ME(); \
    result->__scriptVTable = inVTable; \
    result->mDelegate = inDelegate; \
    return result; }

#define HX_DEFINE_SCRIPTABLE_DYNAMIC \
 \
	hx::Val __Field(const ::String &inName,hx::PropertyAccess inCallProp) \
      { Dynamic result; if (hx::ScriptableField(this,inName,inCallProp,result)) return result; return super::__Field(inName,inCallProp); } \
	Float __INumField(int inFieldID) \
		{ Float result; if (hx::ScriptableField(this,inFieldID,hx::paccAlways,result)) return result; return super::__INumField(inFieldID); } \
	Dynamic __IField(int inFieldID) \
		{ Dynamic result; if (hx::ScriptableField(this,inFieldID,hx::paccAlways,result)) return result; return super::__IField(inFieldID); } \
   hx::Val __SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) \
   { \
      Dynamic value; \
      if (hx::ScriptableSetField(this, inName, inValue,inCallProp,value)) \
         return value; \
		return super::__SetField(inName,inValue,inCallProp); \
   } \
	void __GetFields(Array< ::String> &outFields) \
		{ super::__GetFields(outFields); hx::ScriptableGetFields(this,outFields); }

#endif


text:
#ifndef MediaStreamComponent_h
#define MediaStreamComponent_h

#if ENABLE(MEDIA_STREAM)

#include <wtf/PassRefPtr.h>
#include <wtf/RefCounted.h>
#include <wtf/text/WTFString.h>

namespace WebCore {

class MediaStreamDescriptor;
class MediaStreamSource;

class MediaStreamComponent : public RefCounted<MediaStreamComponent> {
public:
    static PassRefPtr<MediaStreamComponent> create(PassRefPtr<MediaStreamSource>);
    static PassRefPtr<MediaStreamComponent> create(MediaStreamDescriptor*, PassRefPtr<MediaStreamSource>);

    MediaStreamDescriptor* stream() const { return m_stream; }
    void setStream(MediaStreamDescriptor* stream) { ASSERT(!m_stream && stream); m_stream = stream; }

    MediaStreamSource* source() const { return m_source.get(); }

    String id() const { return m_id; }
    bool enabled() const { return m_enabled; }
    void setEnabled(bool enabled) { m_enabled = enabled; }

private:
    MediaStreamComponent(const String& id, MediaStreamDescriptor*, PassRefPtr<MediaStreamSource>);

    MediaStreamDescriptor* m_stream;
    RefPtr<MediaStreamSource> m_source;
    String m_id;
    bool m_enabled;
};

typedef Vector<RefPtr<MediaStreamComponent> > MediaStreamComponentVector;

} // namespace WebCore

#endif // ENABLE(MEDIA_STREAM)

#endif // MediaStreamComponent_h


text:
using System;

public static void Run(string myEventHubMessage, TraceWriter log)
#endif
#if (vsTemplates)
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.ServiceBus;

namespace Company.Function
{
    public static class EventHubTriggerCSharp
    {
        [FunctionName("EventHubTriggerCSharp")]
        public static void Run([EventHubTrigger("PathValue", Connection = "ConnectionValue")]string myEventHubMessage, TraceWriter log)
#endif
        {
            log.Info($"C# Event Hub trigger function processed a message: {myEventHubMessage}");
        }
#if (vsTemplates)
    }
}
#endif


text:
"""
BSD 3-Clause License

Copyright (c) 2017, Mairie de Paris
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import pytesseract
import re

from franceocr.config import BASEDIR
from PIL import Image

def ocr(image, lang="fra", config=None):
    image = Image.fromarray(image)

    return pytesseract.image_to_string(image, lang=lang, config=config)

def ocr_read_number(text):
    text = text \
        .replace('O', '0') \
        .replace('I', '1') \
        .replace('S', '5') \
        .replace('B', '8')

    return text

def ocr_read_text(text):
    text = text \
        .replace('0', 'O') \
        .replace('1', 'I') \
        .replace('5', 'S') \
        .replace('8', 'B')

    return text

def ocr_cni(image):
    ocr_result = ocr(
        image,
        "franceocr",
        "--oem 1 --psm 7 " + BASEDIR + "/tessconfig/cni"
    )

    ocr_result = ocr_result \
        .lstrip(":") \
        .replace(",", "") \
        .replace(".", "") \
        .strip()

    return re.sub(r" +", " ", ocr_result)

def ocr_cni_birth_date(image):
    ocr_result = ocr(
        image,
        "franceocr",
        "--oem 1 --psm 7 " + BASEDIR + "/tessconfig/cni-birth_date"
    )

    ocr_result = ocr_read_number(ocr_result)

    return ocr_result \
        .replace(' ', '') \
        .replace(',', '') \
        .replace('.', '')

def ocr_cni_birth_place(image):
    ocr_result = ocr(
        image,
        "franceocr",
        "--oem 1 --psm 7 " + BASEDIR + "/tessconfig/cni-birth_place"
    )

    no_brackets = re.sub(
        r"\(.*\)",
        "",
        ocr_result
    )

    only_alphanum = re.sub(
        r"[^a-zA-Z0-9' \-]",
        "",
        no_brackets
    )

    return only_alphanum \
        .lstrip(":") \
        .lstrip("'") \
        .strip()

def ocr_cni_mrz(image):
    ocr_result = ocr(
        image,
        "OCRB",
        "--oem 0 " + BASEDIR + "/tessconfig/cni-mrz"
    )

    return ocr_result


text:
class SessionsController < ApplicationController

  def new
    if current_user
      redirect_to current_user.get_home_route
    else
      render 'sessions/index'
    end

  end

  def create
    @user = User.find_by_email(params[:email])
    if @user && @user.authenticate(params[:password][0])
      session[:user_id] = @user.id
      PageVisit.last.update_view_count
      redirect_to @user.get_home_route
    else
      redirect_to root_path
    end
  end

  def destroy
    session.clear
    redirect_to '/'
  end

end


text:
<?php

namespace Everon\EvShipping\Block\Adminhtml;

class RatesOverview extends \Magento\Backend\Block\Template
{

}


text:
// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin

// Author: Maxim Kuzmin

using Makc2017.Core.Module.Filters;

namespace Makc2017.Modules.User.Filters
{
    /// <summary>
    /// Модули. Модуль "User". Фильтры. Фильтр списка.
    /// </summary>
    public class ModuleUserFilterList : CoreModuleFilterList
    {
        #region Properties

        /// <summary>
        /// Логин.
        /// </summary>
        public string Login { get; set; }

        /// <summary>
        /// Признак того, что пользователь включен.
        /// </summary>
        public bool? IsEnabled { get; set; }

        /// <summary>
        /// Полное имя.
        /// </summary>
        public string FullName { get; set; }

        #endregion Properties

        #region Public methods

        /// <summary>
        /// Нормализовать.
        /// </summary>
        public sealed override void Normalize()
        {
            base.Normalize();

            if (string.IsNullOrWhiteSpace(SortField))
            {
                SortField = "id";
            }

            if (string.IsNullOrWhiteSpace(SortDirection))
            {
                SortDirection = "desc";
            }
        }

        #endregion Public methods
    }
}


text:
package org.apache.beam.sdk.io;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;

import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;
import org.apache.beam.sdk.coders.ByteArrayCoder;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.VoidCoder;
import org.apache.beam.sdk.io.Read.Bounded;
import org.apache.beam.sdk.io.fs.MatchResult;
import org.apache.beam.sdk.io.fs.MatchResult.Metadata;
import org.apache.beam.sdk.io.fs.ResourceId;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.options.ValueProvider.StaticValueProvider;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.apache.beam.sdk.transforms.display.DisplayData;
import org.apache.beam.sdk.util.MimeTypes;
import org.apache.beam.sdk.values.PBegin;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PDone;

/**
 * {@link PTransform}s for reading and writing TensorFlow TFRecord files.
 */
public class TFRecordIO {
  /** The default coder, which returns each record of the input file as a byte array. */
  public static final Coder<byte[]> DEFAULT_BYTE_ARRAY_CODER = ByteArrayCoder.of();

  /**
   * A {@link PTransform} that reads from a TFRecord file (or multiple TFRecord
   * files matching a pattern) and returns a {@link PCollection} containing
   * the decoding of each of the records of the TFRecord file(s) as a byte array.
   */
  public static Read read() {
    return new AutoValue_TFRecordIO_Read.Builder()
        .setValidate(true)
        .setCompressionType(CompressionType.AUTO)
        .build();
  }

  /**
   * A {@link PTransform} that writes a {@link PCollection} to TFRecord file (or
   * multiple TFRecord files matching a sharding pattern), with each
   * element of the input collection encoded into its own record.
   */
  public static Write write() {
    return new AutoValue_TFRecordIO_Write.Builder()
        .setShardTemplate(null)
        .setFilenameSuffix(null)
        .setNumShards(0)
        .setCompressionType(CompressionType.NONE)
        .build();
  }

  /** Implementation of {@link #read}. */
  @AutoValue
  public abstract static class Read extends PTransform<PBegin, PCollection<byte[]>> {
    @Nullable
    abstract ValueProvider<String> getFilepattern();

    abstract boolean getValidate();

    abstract CompressionType getCompressionType();

    abstract Builder toBuilder();

    @AutoValue.Builder
    abstract static class Builder {
      abstract Builder setFilepattern(ValueProvider<String> filepattern);
      abstract Builder setValidate(boolean validate);
      abstract Builder setCompressionType(CompressionType compressionType);

      abstract Read build();
    }

    /**
     * Returns a transform for reading TFRecord files that reads from the file(s)
     * with the given filename or filename pattern. This can be a local path (if running locally),
     * or a Google Cloud Storage filename or filename pattern of the form
     * {@code "gs://<bucket>/<filepath>"} (if running locally or using remote
     * execution). Standard Java Filesystem glob patterns ("*", "?", "[..]") are supported.
     */
    public Read from(String filepattern) {
      return from(StaticValueProvider.of(filepattern));
    }

    /**
     * Same as {@code from(filepattern)}, but accepting a {@link ValueProvider}.
     */
    public Read from(ValueProvider<String> filepattern) {
      return toBuilder().setFilepattern(filepattern).build();
    }

    /**
     * Returns a transform for reading TFRecord files that has GCS path validation on
     * pipeline creation disabled.
     *
     *
This can be useful in the case where the GCS input does not
     * exist at the pipeline creation time, but is expected to be
     * available at execution time.
     */
    public Read withoutValidation() {
      return toBuilder().setValidate(false).build();
    }

    /**
     * Returns a transform for reading TFRecord files that decompresses all input files
     * using the specified compression type.
     *
     *
If no compression type is specified, the default is
     * {@link TFRecordIO.CompressionType#AUTO}.
     * In this mode, the compression type of the file is determined by its extension
     * (e.g., {@code *.gz} is gzipped, {@code *.zlib} is zlib compressed, and all other
     * extensions are uncompressed).
     */
    public Read withCompressionType(TFRecordIO.CompressionType compressionType) {
      return toBuilder().setCompressionType(compressionType).build();
    }

    @Override
    public PCollection<byte[]> expand(PBegin input) {
      if (getFilepattern() == null) {
        throw new IllegalStateException(
            "Need to set the filepattern of a TFRecordIO.Read transform");
      }

      if (getValidate()) {
        checkState(getFilepattern().isAccessible(), "Cannot validate with a RVP.");
        try {
          MatchResult matches = FileSystems.match(getFilepattern().get());
          checkState(
              !matches.metadata().isEmpty(),
              "Unable to find any files matching %s",
              getFilepattern().get());
        } catch (IOException e) {
          throw new IllegalStateException(
              String.format("Failed to validate %s", getFilepattern().get()), e);
        }
      }

      final Bounded<byte[]> read = org.apache.beam.sdk.io.Read.from(getSource());
      PCollection<byte[]> pcol = input.getPipeline().apply("Read", read);
      // Honor the default output coder that would have been used by this PTransform.
      pcol.setCoder(getDefaultOutputCoder());
      return pcol;
    }

    // Helper to create a source specific to the requested compression type.
    protected FileBasedSource<byte[]> getSource() {
      switch (getCompressionType()) {
        case NONE:
          return new TFRecordSource(getFilepattern());
        case AUTO:
          return CompressedSource.from(new TFRecordSource(getFilepattern()));
        case GZIP:
          return
              CompressedSource.from(new TFRecordSource(getFilepattern()))
                  .withDecompression(CompressedSource.CompressionMode.GZIP);
        case ZLIB:
          return
              CompressedSource.from(new TFRecordSource(getFilepattern()))
                  .withDecompression(CompressedSource.CompressionMode.DEFLATE);
        default:
          throw new IllegalArgumentException("Unknown compression type: " + getCompressionType());
      }
    }

    @Override
    public void populateDisplayData(DisplayData.Builder builder) {
      super.populateDisplayData(builder);

      String filepatternDisplay = getFilepattern().isAccessible()
          ? getFilepattern().get() : getFilepattern().toString();
      builder
          .add(DisplayData.item("compressionType", getCompressionType().toString())
              .withLabel("Compression Type"))
          .addIfNotDefault(DisplayData.item("validation", getValidate())
              .withLabel("Validation Enabled"), true)
          .addIfNotNull(DisplayData.item("filePattern", filepatternDisplay)
              .withLabel("File Pattern"));
    }

    @Override
    protected Coder<byte[]> getDefaultOutputCoder() {
      return ByteArrayCoder.of();
    }
  }

  /////////////////////////////////////////////////////////////////////////////

  /** Implementation of {@link #write}. */
  @AutoValue
  public abstract static class Write extends PTransform<PCollection<byte[]>, PDone> {
    /** The directory to which files will be written. */
    @Nullable abstract ValueProvider<ResourceId> getOutputPrefix();

    /** The suffix of each file written, combined with prefix and shardTemplate. */
    @Nullable abstract String getFilenameSuffix();

    /** Requested number of shards. 0 for automatic. */
    abstract int getNumShards();

    /** The shard template of each file written, combined with prefix and suffix. */
    @Nullable abstract String getShardTemplate();

    /** Option to indicate the output sink's compression type. Default is NONE. */
    abstract CompressionType getCompressionType();

    abstract Builder toBuilder();

    @AutoValue.Builder
    abstract static class Builder {
      abstract Builder setOutputPrefix(ValueProvider<ResourceId> outputPrefix);

      abstract Builder setShardTemplate(String shardTemplate);

      abstract Builder setFilenameSuffix(String filenameSuffix);

      abstract Builder setNumShards(int numShards);

      abstract Builder setCompressionType(CompressionType compressionType);

      abstract Write build();
    }

    /**
     * Writes TFRecord file(s) with the given output prefix. The {@code prefix} will be used as a
     * to generate a {@link ResourceId} using any supported {@link FileSystem}.
     *
     *
In addition to their prefix, created files will have a shard identifier (see
     * {@link #withNumShards(int)}), and end in a common suffix, if given by
     * {@link #withSuffix(String)}.
     *
     *
For more information on filenames, see {@link DefaultFilenamePolicy}.
     */
    public Write to(String outputPrefix) {
      return to(FileBasedSink.convertToFileResourceIfPossible(outputPrefix));
    }

    /**
     * Writes TFRecord file(s) with a prefix given by the specified resource.
     *
     *
In addition to their prefix, created files will have a shard identifier (see
     * {@link #withNumShards(int)}), and end in a common suffix, if given by
     * {@link #withSuffix(String)}.
     *
     *
For more information on filenames, see {@link DefaultFilenamePolicy}.
     */
    @Experimental(Kind.FILESYSTEM)
    public Write to(ResourceId outputResource) {
      return toResource(StaticValueProvider.of(outputResource));
    }

    /**
     * Like {@link #to(ResourceId)}.
     */
    @Experimental(Kind.FILESYSTEM)
    public Write toResource(ValueProvider<ResourceId> outputResource) {
      return toBuilder().setOutputPrefix(outputResource).build();
    }

    /**
     * Writes to the file(s) with the given filename suffix.
     *
     * @see ShardNameTemplate
     */
    public Write withSuffix(String suffix) {
      return toBuilder().setFilenameSuffix(suffix).build();
    }

    /**
     * Writes to the provided number of shards.
     *
     *
Constraining the number of shards is likely to reduce
     * the performance of a pipeline. Setting this value is not recommended
     * unless you require a specific number of output files.
     *
     * @param numShards the number of shards to use, or 0 to let the system
     *                  decide.
     * @see ShardNameTemplate
     */
    public Write withNumShards(int numShards) {
      checkArgument(numShards >= 0, "Number of shards %s must be >= 0", numShards);
      return toBuilder().setNumShards(numShards).build();
    }

    /**
     * Uses the given shard name template.
     *
     * @see ShardNameTemplate
     */
    public Write withShardNameTemplate(String shardTemplate) {
      return toBuilder().setShardTemplate(shardTemplate).build();
    }

    /**
     * Forces a single file as output.
     *
     *
Constraining the number of shards is likely to reduce
     * the performance of a pipeline. Using this setting is not recommended
     * unless you truly require a single output file.
     *
     *
This is a shortcut for
     * {@code .withNumShards(1).withShardNameTemplate("")}
     */
    public Write withoutSharding() {
      return withNumShards(1).withShardNameTemplate("");
    }

    /**
     * Writes to output files using the specified compression type.
     *
     *
If no compression type is specified, the default is
     * {@link TFRecordIO.CompressionType#NONE}.
     * See {@link TFRecordIO.Read#withCompressionType} for more details.
     */
    public Write withCompressionType(CompressionType compressionType) {
      return toBuilder().setCompressionType(compressionType).build();
    }

    @Override
    public PDone expand(PCollection<byte[]> input) {
      checkState(getOutputPrefix() != null,
          "need to set the output prefix of a TFRecordIO.Write transform");
      WriteFiles<byte[]> write = WriteFiles.to(
              new TFRecordSink(
                  getOutputPrefix(),
                  getShardTemplate(),
                  getFilenameSuffix(),
                  getCompressionType()));
      if (getNumShards() > 0) {
        write = write.withNumShards(getNumShards());
      }
      return input.apply("Write", write);
    }

    @Override
    public void populateDisplayData(DisplayData.Builder builder) {
      super.populateDisplayData(builder);

      String outputPrefixString = null;
      if (getOutputPrefix().isAccessible()) {
        ResourceId dir = getOutputPrefix().get();
        outputPrefixString = dir.toString();
      } else {
        outputPrefixString = getOutputPrefix().toString();
      }
      builder
          .add(DisplayData.item("filePrefix", outputPrefixString)
              .withLabel("Output File Prefix"))
          .addIfNotNull(DisplayData.item("fileSuffix", getFilenameSuffix())
              .withLabel("Output File Suffix"))
          .addIfNotNull(DisplayData.item("shardNameTemplate", getShardTemplate())
                  .withLabel("Output Shard Name Template"))
          .addIfNotDefault(DisplayData.item("numShards", getNumShards())
              .withLabel("Maximum Output Shards"), 0)
          .add(DisplayData.item("compressionType", getCompressionType().toString())
              .withLabel("Compression Type"));
    }

    @Override
    protected Coder<Void> getDefaultOutputCoder() {
      return VoidCoder.of();
    }
  }

  /**
   * Possible TFRecord file compression types.
   */
  public enum CompressionType {
    /**
     * Automatically determine the compression type based on filename extension.
     */
    AUTO(""),
    /**
     * Uncompressed.
     */
    NONE(""),
    /**
     * GZipped.
     */
    GZIP(".gz"),
    /**
     * ZLIB compressed.
     */
    ZLIB(".zlib");

    private String filenameSuffix;

    CompressionType(String suffix) {
      this.filenameSuffix = suffix;
    }

    /**
     * Determine if a given filename matches a compression type based on its extension.
     * @param filename the filename to match
     * @return true iff the filename ends with the compression type's known extension.
     */
    public boolean matches(String filename) {
      return filename.toLowerCase().endsWith(filenameSuffix.toLowerCase());
    }
  }

  //////////////////////////////////////////////////////////////////////////////

  /** Disable construction of utility class. */
  private TFRecordIO() {}

  /**
   * A {@link FileBasedSource} which can decode records in TFRecord files.
   */
  @VisibleForTesting
  static class TFRecordSource extends FileBasedSource<byte[]> {
    @VisibleForTesting
    TFRecordSource(String fileSpec) {
      super(StaticValueProvider.of(fileSpec), 1L);
    }

    @VisibleForTesting
    TFRecordSource(ValueProvider<String> fileSpec) {
      super(fileSpec, Long.MAX_VALUE);
    }

    private TFRecordSource(Metadata metadata, long start, long end) {
      super(metadata, Long.MAX_VALUE, start, end);
    }

    @Override
    protected FileBasedSource<byte[]> createForSubrangeOfFile(
        Metadata metadata,
        long start,
        long end) {
      checkArgument(start == 0, "TFRecordSource is not splittable");
      return new TFRecordSource(metadata, start, end);
    }

    @Override
    protected FileBasedReader<byte[]> createSingleFileReader(PipelineOptions options) {
      return new TFRecordReader(this);
    }

    @Override
    public Coder<byte[]> getDefaultOutputCoder() {
      return DEFAULT_BYTE_ARRAY_CODER;
    }

    @Override
    protected boolean isSplittable() throws Exception {
      // TFRecord files are not splittable
      return false;
    }

    /**
     * A {@link org.apache.beam.sdk.io.FileBasedSource.FileBasedReader FileBasedReader}
     * which can decode records in TFRecord files.
     *
     *
See {@link TFRecordIO.TFRecordSource} for further details.
     */
    @VisibleForTesting
    static class TFRecordReader extends FileBasedReader<byte[]> {
      private long startOfRecord;
      private volatile long startOfNextRecord;
      private volatile boolean elementIsPresent;
      private byte[] currentValue;
      private ReadableByteChannel inChannel;
      private TFRecordCodec codec;

      private TFRecordReader(TFRecordSource source) {
        super(source);
      }

      @Override
      public boolean allowsDynamicSplitting() {
        /* TFRecords cannot be dynamically split. */
        return false;
      }

      @Override
      protected long getCurrentOffset() throws NoSuchElementException {
        if (!elementIsPresent) {
          throw new NoSuchElementException();
        }
        return startOfRecord;
      }

      @Override
      public byte[] getCurrent() throws NoSuchElementException {
        if (!elementIsPresent) {
          throw new NoSuchElementException();
        }
        return currentValue;
      }

      @Override
      protected void startReading(ReadableByteChannel channel) throws IOException {
        this.inChannel = channel;
        this.codec = new TFRecordCodec();
      }

      @Override
      protected boolean readNextRecord() throws IOException {
        startOfRecord = startOfNextRecord;
        currentValue = codec.read(inChannel);
        if (currentValue != null) {
          elementIsPresent = true;
          startOfNextRecord = startOfRecord + codec.recordLength(currentValue);
          return true;
        } else {
          elementIsPresent = false;
          return false;
        }
      }
    }
  }

  /**
   * A {@link FileBasedSink} for TFRecord files. Produces TFRecord files.
   */
  @VisibleForTesting
  static class TFRecordSink extends FileBasedSink<byte[]> {
    @VisibleForTesting
    TFRecordSink(ValueProvider<ResourceId> outputPrefix,
        @Nullable String shardTemplate,
        @Nullable String suffix,
        TFRecordIO.CompressionType compressionType) {
      super(
          outputPrefix,
          DefaultFilenamePolicy.constructUsingStandardParameters(
              outputPrefix, shardTemplate, suffix, false),
          writableByteChannelFactory(compressionType));
    }

    private static class ExtractDirectory implements SerializableFunction<ResourceId, ResourceId> {
      @Override
      public ResourceId apply(ResourceId input) {
        return input.getCurrentDirectory();
      }
    }

    @Override
    public WriteOperation<byte[]> createWriteOperation() {
      return new TFRecordWriteOperation(this);
    }

    private static WritableByteChannelFactory writableByteChannelFactory(
        TFRecordIO.CompressionType compressionType) {
      switch (compressionType) {
        case AUTO:
          throw new IllegalArgumentException("Unsupported compression type AUTO");
        case NONE:
          return CompressionType.UNCOMPRESSED;
        case GZIP:
          return CompressionType.GZIP;
        case ZLIB:
          return CompressionType.DEFLATE;
      }
      return CompressionType.UNCOMPRESSED;
    }

    /**
     * A {@link WriteOperation
     * WriteOperation} for TFRecord files.
     */
    private static class TFRecordWriteOperation extends WriteOperation<byte[]> {
      private TFRecordWriteOperation(TFRecordSink sink) {
        super(sink);
      }

      @Override
      public Writer<byte[]> createWriter() throws Exception {
        return new TFRecordWriter(this);
      }
    }

    /**
     * A {@link Writer Writer}
     * for TFRecord files.
     */
    private static class TFRecordWriter extends Writer<byte[]> {
      private WritableByteChannel outChannel;
      private TFRecordCodec codec;

      private TFRecordWriter(WriteOperation<byte[]> writeOperation) {
        super(writeOperation, MimeTypes.BINARY);
      }

      @Override
      protected void prepareWrite(WritableByteChannel channel) throws Exception {
        this.outChannel = channel;
        this.codec = new TFRecordCodec();
      }

      @Override
      public void write(byte[] value) throws Exception {
        codec.write(outChannel, value);
      }
    }
  }

  //////////////////////////////////////////////////////////////////////////////

  /**
   * Codec for TFRecords file format.
   * See https://www.tensorflow.org/api_guides/python/python_io#TFRecords_Format_Details
   */
  private static class TFRecordCodec {
    private static final int HEADER_LEN = (Long.SIZE + Integer.SIZE) / Byte.SIZE;
    private static final int FOOTER_LEN = Integer.SIZE / Byte.SIZE;
    private static HashFunction crc32c = Hashing.crc32c();

    private ByteBuffer header = ByteBuffer.allocate(HEADER_LEN).order(ByteOrder.LITTLE_ENDIAN);
    private ByteBuffer footer = ByteBuffer.allocate(FOOTER_LEN).order(ByteOrder.LITTLE_ENDIAN);

    private int mask(int crc) {
      return ((crc >>> 15) | (crc << 17)) + 0xa282ead8;
    }

    private int hashLong(long x) {
      return mask(crc32c.hashLong(x).asInt());
    }

    private int hashBytes(byte[] x) {
      return mask(crc32c.hashBytes(x).asInt());
    }

    public int recordLength(byte[] data) {
      return HEADER_LEN + data.length + FOOTER_LEN;
    }

    public byte[] read(ReadableByteChannel inChannel) throws IOException {
      header.clear();
      int headerBytes = inChannel.read(header);
      if (headerBytes <= 0) {
        return null;
      }
      checkState(
          headerBytes == HEADER_LEN,
          "Not a valid TFRecord. Fewer than 12 bytes.");
      header.rewind();
      long length = header.getLong();
      int maskedCrc32OfLength = header.getInt();
      checkState(
          hashLong(length) == maskedCrc32OfLength,
          "Mismatch of length mask");

      ByteBuffer data = ByteBuffer.allocate((int) length);
      checkState(inChannel.read(data) == length, "Invalid data");

      footer.clear();
      inChannel.read(footer);
      footer.rewind();
      int maskedCrc32OfData = footer.getInt();

      checkState(
          hashBytes(data.array()) == maskedCrc32OfData,
          "Mismatch of data mask");
      return data.array();
    }

    public void write(WritableByteChannel outChannel, byte[] data) throws IOException {
      int maskedCrc32OfLength = hashLong(data.length);
      int maskedCrc32OfData = hashBytes(data);

      header.clear();
      header.putLong(data.length).putInt(maskedCrc32OfLength);
      header.rewind();
      outChannel.write(header);

      outChannel.write(ByteBuffer.wrap(data));

      footer.clear();
      footer.putInt(maskedCrc32OfData);
      footer.rewind();
      outChannel.write(footer);
    }
  }

}


text:
using System.Windows;
using System.Windows.Input;

namespace Jabbr.WPF
{
    public partial class ShellView : Window
    {
        public ShellView()
        {
            InitializeComponent();
        }

        private void TitleBarMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.RightButton != MouseButtonState.Pressed && e.MiddleButton != MouseButtonState.Pressed &&
                e.LeftButton == MouseButtonState.Pressed)
                DragMove();

            if (e.ClickCount == 2 && (ResizeMode == ResizeMode.CanResizeWithGrip || ResizeMode == ResizeMode.CanResize))
            {
                WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
            }
        }

        private void TitleBarMouseMove(object sender, MouseEventArgs e)
        {
            if (e.RightButton != MouseButtonState.Pressed && e.MiddleButton != MouseButtonState.Pressed
                && e.LeftButton == MouseButtonState.Pressed && WindowState == WindowState.Maximized)
            {
                // Calcualting correct left coordinate for multi-screen system.
                Point mouseAbsolute = PointToScreen(Mouse.GetPosition(this));
                double width = RestoreBounds.Width;
                double left = mouseAbsolute.X - width/2;

                // Aligning window's position to fit the screen.
                double virtualScreenWidth = SystemParameters.VirtualScreenWidth;
                left = left + width > virtualScreenWidth ? virtualScreenWidth - width : left;

                Point mousePosition = e.MouseDevice.GetPosition(this);

                // When dragging the window down at the very top of the border,
                // move the window a bit upwards to avoid showing the resize handle as soon as the mouse button is released
                Top = mousePosition.Y < 5 ? -5 : mouseAbsolute.Y - mousePosition.Y;
                Left = left;

                // Restore window to normal state.
                WindowState = WindowState.Normal;

                DragMove();
            }
        }
    }
}


text:
var _ = require('lodash')

/**
 * Creates a new Model or Collection object.
 * @param {Arrow.Model} Model The model class being updated.
 * @param {Object} [values] Attributes to set on the new model(s).
 * @param {Function} callback Callback passed an Error object (or null if successful), and the new model or collection.
 * @throws {Error}
 */
exports.create = function (Model, values, callback) {
  var self = this
  var table = this.getTableName(Model)
  var payload = Model.instance(values, false).toPayload()
  var primaryKeyColumn = this.getPrimaryKeyColumn(Model)
  var columns = this.fetchColumns(table, payload)
  var placeholders = columns.map(this.returnPlaceholder)
  var query

  if (!primaryKeyColumn) {
    query = 'INSERT INTO ' + table + ' (' + this.escapeKeys(columns).join(',') + ') VALUES (' + placeholders.join(',') + ')'
  } else {
    query = 'INSERT INTO ' + table + ' (' + primaryKeyColumn + ',' + this.escapeKeys(columns).join(',') + ') VALUES (NULL, ' + placeholders.join(',') + ')'
  }
  var data = _.values(payload)
  this._query(query, data, callback, function (result) {
    var instance = Model.instance(values)
    var primaryKey = primaryKeyColumn && self.metadata.schema.objects[table][primaryKeyColumn]
    if (primaryKey && primaryKey.EXTRA === 'auto_increment') {
      instance.setPrimaryKey(result.insertId)
    }
    callback(null, instance)
  })
}


text:
/*	$OpenBSD: mainbus.c,v 1.14 1999/02/19 17:32:39 art Exp $	*/
/*	$NetBSD: mainbus.c,v 1.21 1997/06/06 23:14:20 thorpej Exp $	*/

/*
 * Copyright (c) 1996 Christopher G. Demetriou.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Christopher G. Demetriou
 *	for the NetBSD Project.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>

#include <machine/bus.h>

#include <dev/isa/isavar.h>
#include <dev/eisa/eisavar.h>
#include <dev/pci/pcivar.h>

#include <dev/isa/isareg.h>		/* for ISA_HOLE_VADDR */
#include <i386/isa/isa_machdep.h>

#include "pci.h"
#include "eisa.h"
#include "isa.h"
#include "apm.h"
#include "bios.h"

#if NBIOS > 0
#include <machine/biosvar.h>
#endif

int	mainbus_match __P((struct device *, void *, void *));
void	mainbus_attach __P((struct device *, struct device *, void *));

struct cfattach mainbus_ca = {
	sizeof(struct device), mainbus_match, mainbus_attach
};

struct cfdriver mainbus_cd = {
	NULL, "mainbus", DV_DULL
};

int	mainbus_print __P((void *, const char *));

union mainbus_attach_args {
	const char *mba_busname;		/* first elem of all */
	struct pcibus_attach_args mba_pba;
	struct eisabus_attach_args mba_eba;
	struct isabus_attach_args mba_iba;
#if NBIOS > 0
	struct bios_attach_args mba_bios;
#endif
};

/*
 * This is set when the ISA bus is attached.  If it's not set by the
 * time it's checked below, then mainbus attempts to attach an ISA.
 */
int     isa_has_been_seen;

/*
 * Probe for the mainbus; always succeeds.
 */
int
mainbus_match(parent, match, aux)
	struct device *parent;
	void *match, *aux;
{

	return 1;
}

/*
 * Attach the mainbus.
 */
void
mainbus_attach(parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	union mainbus_attach_args mba;

	printf("\n");

#if NBIOS > 0
	{
		mba.mba_bios.bios_dev = "bios";
		mba.mba_bios.bios_iot = I386_BUS_SPACE_IO;
		mba.mba_bios.bios_memt = I386_BUS_SPACE_MEM;
		config_found(self, &mba.mba_bios, mainbus_print);
	}
#endif

	/*
	 * XXX Note also that the presence of a PCI bus should
	 * XXX _always_ be checked, and if present the bus should be
	 * XXX 'found'.  However, because of the structure of the code,
	 * XXX that's not currently possible.
	 */
#if NPCI > 0
	if (pci_mode_detect() != 0) {
		mba.mba_pba.pba_busname = "pci";
		mba.mba_pba.pba_iot = I386_BUS_SPACE_IO;
		mba.mba_pba.pba_memt = I386_BUS_SPACE_MEM;
		mba.mba_pba.pba_dmat = &pci_bus_dma_tag;
		mba.mba_pba.pba_bus = 0;
		config_found(self, &mba.mba_pba, mainbus_print);
	}
#endif

	if (!bcmp(ISA_HOLE_VADDR(EISA_ID_PADDR), EISA_ID, EISA_ID_LEN)) {
		mba.mba_eba.eba_busname = "eisa";
		mba.mba_eba.eba_iot = I386_BUS_SPACE_IO;
		mba.mba_eba.eba_memt = I386_BUS_SPACE_MEM;
#if NEISA > 0
		mba.mba_eba.eba_dmat = &eisa_bus_dma_tag;
#endif
		config_found(self, &mba.mba_eba, mainbus_print);
	}

	if (isa_has_been_seen == 0) {
		mba.mba_iba.iba_busname = "isa";
		mba.mba_iba.iba_iot = I386_BUS_SPACE_IO;
		mba.mba_iba.iba_memt = I386_BUS_SPACE_MEM;
#if NISADMA > 0
		mba.mba_iba.iba_dmat = &isa_bus_dma_tag;
#endif
		config_found(self, &mba.mba_iba, mainbus_print);
	}
}

int
mainbus_print(aux, pnp)
	void *aux;
	const char *pnp;
{
	union mainbus_attach_args *mba = aux;

	if (pnp)
		printf("%s at %s", mba->mba_busname, pnp);
	if (!strcmp(mba->mba_busname, "pci"))
		printf(" bus %d", mba->mba_pba.pba_bus);
	return (UNCONF);
}


text:
// @flow
import getValueAndUnit from '../helpers/getValueAndUnit'
import PolishedError from '../internalHelpers/_errors'

import type { SideKeyword } from '../types/sideKeyword'
import type { Styles } from '../types/style'
import type { TriangleConfiguration } from '../types/triangleConfiguration'

const getBorderWidth = (
  pointingDirection: SideKeyword,
  height: [number, string],
  width: [number, string],
): string => {
  const fullWidth = `${width[0]}${width[1] || ''}`
  const halfWidth = `${width[0] / 2}${width[1] || ''}`
  const fullHeight = `${height[0]}${height[1] || ''}`
  const halfHeight = `${height[0] / 2}${height[1] || ''}`

  switch (pointingDirection) {
    case 'top':
      return `0 ${halfWidth} ${fullHeight} ${halfWidth}`
    case 'topLeft':
      return `${fullWidth} ${fullHeight} 0 0`
    case 'left':
      return `${halfHeight} ${fullWidth} ${halfHeight} 0`
    case 'bottomLeft':
      return `${fullWidth} 0 0 ${fullHeight}`
    case 'bottom':
      return `${fullHeight} ${halfWidth} 0 ${halfWidth}`
    case 'bottomRight':
      return `0 0 ${fullWidth} ${fullHeight}`
    case 'right':
      return `${halfHeight} 0 ${halfHeight} ${fullWidth}`
    case 'topRight':
    default:
      return `0 ${fullWidth} ${fullHeight} 0`
  }
}

const getBorderColor = (pointingDirection: SideKeyword, foregroundColor: string): Object => {
  switch (pointingDirection) {
    case 'top':
    case 'bottomRight':
      return { borderBottomColor: foregroundColor }
    case 'right':
    case 'bottomLeft':
      return { borderLeftColor: foregroundColor }
    case 'bottom':
    case 'topLeft':
      return { borderTopColor: foregroundColor }
    case 'left':
    case 'topRight':
      return { borderRightColor: foregroundColor }

    default:
      throw new PolishedError(59)
  }
}

/**
 * CSS to represent triangle with any pointing direction with an optional background color.
 *
 * @example
 * // Styles as object usage
 *
 * const styles = {
 *   ...triangle({ pointingDirection: 'right', width: '100px', height: '100px', foregroundColor: 'red' })
 * }
 *
 *
 * // styled-components usage
 * const div = styled.div`
 *   ${triangle({ pointingDirection: 'right', width: '100px', height: '100px', foregroundColor: 'red' })}
 *
 *
 * // CSS as JS Output
 *
 * div: {
 *  'borderColor': 'transparent transparent transparent red',
 *  'borderStyle': 'solid',
 *  'borderWidth': '50px 0 50px 100px',
 *  'height': '0',
 *  'width': '0',
 * }
 */
export default function triangle({
  pointingDirection,
  height,
  width,
  foregroundColor,
  backgroundColor = 'transparent',
}: TriangleConfiguration): Styles {
  const widthAndUnit = getValueAndUnit(width)
  const heightAndUnit = getValueAndUnit(height)

  if (isNaN(heightAndUnit[0]) || isNaN(widthAndUnit[0])) {
    throw new PolishedError(60)
  }

  return {
    width: '0',
    height: '0',
    borderColor: backgroundColor,
    ...getBorderColor(pointingDirection, foregroundColor),
    borderStyle: 'solid',
    borderWidth: getBorderWidth(pointingDirection, heightAndUnit, widthAndUnit),
  }
}


text:
@interface DDAddressPicker () {
	BOOL selectMeOnLoad;
}

- (IBAction)cancel:(id)sender;
- (IBAction)ok:(id)sender;
- (IBAction)selectMe:(id)sender;

@end

@implementation DDAddressPicker

- (id)init {
    return [super initWithWindowNibName:@"AddressPicker"];
}

- (void)windowDidLoad {
	if (selectMeOnLoad) {
		[self selectMe:nil];
		selectMeOnLoad = NO;
	}
}

#pragma mark actions

- (IBAction)cancel:(id)sender {
    [_peoplePickerView deselectAll:nil];

    BOOL br = YES;
    if ([_delegate respondsToSelector:@selector(addressPicker:canEndWithReturnCode:)]) {
        br = [_delegate addressPicker:self canEndWithReturnCode:NSCancelButton];
    }
    if (br)
        [NSApp stopModalWithCode:NSCancelButton];
}

- (IBAction)ok:(id)sender {
    if (self.needsSelection && !self.persons.count) {
        return ;
    }

    BOOL br = YES;
    if ([_delegate respondsToSelector:@selector(addressPicker:canEndWithReturnCode:)]) {
        br = [_delegate addressPicker:self canEndWithReturnCode:NSOKButton];
    }
    if (br)
        [NSApp stopModalWithCode:NSOKButton];
}

- (IBAction)selectMe:(id)sender {
    if (_peoplePickerView) {
        ABPerson *person = [[ABAddressBook sharedAddressBook] me];
        if (person) {
            [_peoplePickerView selectIdentifier:kABEmailProperty forPerson:person byExtendingSelection:NO];
            //=-> bug: tableView isnt scrolled!

#if APPSTORE_CONFORM
            NSLog(@"due to a bug in the view, focusing (making visible) the new selection isnt possible");
#else
            //
            //working hack
            //

            //get table
            id view = [_peoplePickerView firstSubviewOfKind:NSClassFromString(@"ABPeoplePickerTableView")];

            //scroll
            if ([view respondsToSelector:@selector(scrollRowToVisible:)]
               && [view respondsToSelector:@selector(selectedRow)]) {

                [view scrollRowToVisible:[view selectedRow]];
            }

            //focus
            [[view window] makeFirstResponder:view];
#endif
        }
    }
}

#pragma mark -

- (NSArray  *)persons {
    return _peoplePickerView.selectedValues.count ? _peoplePickerView.selectedValues : nil;
}

- (NSInteger)runModal {
    return [NSApp runModalForWindow:self.window];
}

- (void)selectMe {
	if (_peoplePickerView) {
		[self selectMe:nil];
	} else {
		selectMeOnLoad = YES;
    }
}

@end


text:
/**
 * @interface IExample
 */
interface IExample {
  /**
   * Returns a value!
   *
   * @method foo
   * @param {string} str The input string
   * @return {string}
   */
  foo(str?: string): string;
}

export default IExample;


text:
extern const float kFluidSize;

@class MetalView;
@interface FluidEngine : NSObject
- (instancetype)initWithMetalView:(MetalView *)metalView;

- (void)storeImage320x320:(cpp_helper::cf_shared_ptr<CGImageRef>)image;
- (cpp_helper::cf_shared_ptr<CGImageRef>)loadImage320x320;

- (void)update60fps;

@property (nonatomic, assign) float pen;
@property (nonatomic, assign) glm::vec2 forceSegmentPointA;
@property (nonatomic, assign) glm::vec2 forceSegmentPointB;
@property (nonatomic, assign) glm::vec2 force;
@end


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
 Copyright (c) 2011 Kurt Aaholst <kaaholst@gmail.com>

 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.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/parent_container"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="8dp"
        android:paddingStart="16dp"
        android:paddingEnd="32dp"
        android:paddingTop="8dp"
        android:visibility="gone"
        tools:visibility="visible">

        <ImageView
            android:id="@+id/icon"
            android:layout_width="@dimen/album_art_large_icon_size"
            android:layout_height="@dimen/album_art_large_icon_size"
            android:contentDescription="@string/app_name"
            android:layout_marginEnd="8dp"
            tools:src="@drawable/pending"/>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:minHeight="48dp"
            android:orientation="vertical"
            android:paddingEnd="8dp">

            <TextView
                android:id="@+id/text1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textAppearance="@style/SqueezerTextAppearance.ListItem.Primary"
                tools:text="text1"/>

            <TextView
                android:id="@+id/text2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textAppearance="@style/SqueezerTextAppearance.ListItem.Secondary"
                android:visibility="gone"
                tools:visibility="visible"
                tools:text="text2"/>
        </LinearLayout>

        <include layout="@layout/context_menu_image_button"/>
    </LinearLayout>

    <ScrollView
        android:id="@+id/sub_header_container"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone">
        <TextView
            android:id="@+id/sub_header"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:minHeight="48dp"
            android:paddingBottom="4dp"
            android:paddingStart="16dp"
            android:paddingEnd="16dp"
            android:paddingTop="4dp"
            android:textAppearance="@style/SqueezerTextAppearance.ItemList.SubHeader"/>
    </ScrollView>

    <LinearLayout
        android:id="@+id/input_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:visibility="gone"
        tools:visibility="visible"
        android:orientation="horizontal">

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/plugin_input_til"
            android:layout_height="wrap_content"
            android:layout_width="0dp"
            android:layout_weight="1">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/plugin_input"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text" />
        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.button.MaterialButton
            android:id="@+id/input_button"
            app:icon="@drawable/keyboard_return"
            app:iconSize="24dp"
            android:layout_width="48dp"
            android:layout_height="match_parent"/>
    </LinearLayout>

    <include layout="@layout/item_list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"/>

</LinearLayout>


text: Rails.application.config.session_store :cookie_store, key: '_language-backend_session'


text:
from base import WithDaemonTestCase
from pysource.tests import command

class SourceNamedTest(WithDaemonTestCase):

    def test_source_named(self):
        self.run_pysource_script([
            command.source_def('function1(): return 1'),
        ])
        output = self.run_pysource_script([
            command.source_named('function1'),
            command.run('function1')
        ])
        self.assertEqual(output, '1')

    def test_source_named_piped(self):
        self.run_pysource_script([
            command.source_def('function1(): return 1', piped=True),
        ])
        output = self.run_pysource_script([
            command.source_named('function1', piped=True),
            command.run('function1')
        ])
        self.assertEqual(output, '1')

    def test_source_named_verbose(self):
        output = self.run_pysource_script([
            command.source_named('function1', verbose=True),
        ])
        self.assertIn('run function1', output)
        output = output.split('\n')
        self.assertIn('function1 function sourced.', output)

    def test_source_named_verbose_and_piped(self):
        output = self.run_pysource_script([
            command.source_named('function1',
                                 verbose=True,
                                 piped=True),
        ])
        self.assertIn('run-piped function1', output)


text:
describe Facts::Windows::Networking::Fqdn do
  describe '#call_the_resolver' do
    subject(:fact) { Facts::Windows::Networking::Fqdn.new }

    before do
      allow(Facter::Resolvers::Windows::Networking).to receive(:resolve).with(:domain).and_return(domain_name)
      allow(Facter::Resolvers::Hostname).to receive(:resolve).with(:hostname).and_return(hostname)
    end

    context 'when domain and hostname could be resolved' do
      let(:domain_name) { 'domain' }
      let(:hostname) { 'hostname' }
      let(:value) { "#{hostname}.#{domain_name}" }

      it 'calls Facter::Resolvers::Windows::Networking' do
        fact.call_the_resolver
        expect(Facter::Resolvers::Windows::Networking).to have_received(:resolve).with(:domain)
      end

      it 'calls Facter::Resolvers::Hostname' do
        fact.call_the_resolver
        expect(Facter::Resolvers::Hostname).to have_received(:resolve).with(:hostname)
      end

      it 'returns fqdn fact' do
        expect(fact.call_the_resolver).to be_an_instance_of(Array).and \
          contain_exactly(an_object_having_attributes(name: 'networking.fqdn', value: value),
                          an_object_having_attributes(name: 'fqdn', value: value, type: :legacy))
      end
    end

    context 'when it fails to retrieve hostname' do
      let(:domain_name) { 'domain' }
      let(:hostname) { nil }
      let(:value) { nil }

      it 'returns nil' do
        expect(fact.call_the_resolver).to be_an_instance_of(Facter::ResolvedFact).and \
          have_attributes(name: 'networking.fqdn', value: nil)
      end
    end

    context 'when it fails to retrieve domain' do
      let(:domain_name) { nil }
      let(:hostname) { 'hostname' }
      let(:value) { hostname }

      it 'returns hostname as fqdn' do
        expect(fact.call_the_resolver).to be_an_instance_of(Array).and \
          contain_exactly(an_object_having_attributes(name: 'networking.fqdn', value: value),
                          an_object_having_attributes(name: 'fqdn', value: value, type: :legacy))
      end
    end

    context 'when domain is empty string' do
      let(:domain_name) { '' }
      let(:hostname) { 'hostname' }
      let(:value) { hostname }

      it 'returns hostname as fqdn without a trailing dot' do
        expect(fact.call_the_resolver).to be_an_instance_of(Array).and \
          contain_exactly(an_object_having_attributes(name: 'networking.fqdn', value: value),
                          an_object_having_attributes(name: 'fqdn', value: value, type: :legacy))
      end
    end

    context 'when hostname is empty' do
      let(:domain_name) { 'domain' }
      let(:hostname) { '' }
      let(:value) { nil }

      it 'returns nil' do
        expect(fact.call_the_resolver).to be_an_instance_of(Facter::ResolvedFact).and \
          have_attributes(name: 'networking.fqdn', value: nil)
      end
    end
  end
end


text:
package kafka.javaapi

import kafka.cluster.Broker
import collection.JavaConverters._

private[javaapi] object MetadataListImplicits {
  implicit def toJavaTopicMetadataList(topicMetadataSeq: Seq[kafka.api.TopicMetadata]):
  java.util.List[kafka.javaapi.TopicMetadata] =
    topicMetadataSeq.map(new kafka.javaapi.TopicMetadata(_)).asJava

  implicit def toPartitionMetadataList(partitionMetadataSeq: Seq[kafka.api.PartitionMetadata]):
  java.util.List[kafka.javaapi.PartitionMetadata] =
    partitionMetadataSeq.map(new kafka.javaapi.PartitionMetadata(_)).asJava
}

class TopicMetadata(private val underlying: kafka.api.TopicMetadata) {
  def topic: String = underlying.topic

  def partitionsMetadata: java.util.List[PartitionMetadata] = {
    import kafka.javaapi.MetadataListImplicits._
    underlying.partitionsMetadata
  }

  def errorCode: Short = underlying.errorCode

  def sizeInBytes: Int = underlying.sizeInBytes
}

class PartitionMetadata(private val underlying: kafka.api.PartitionMetadata) {
  def partitionId: Int = underlying.partitionId

  def leader: Broker = {
    import kafka.javaapi.Implicits._
    underlying.leader
  }

  def replicas: java.util.List[Broker] = underlying.replicas.asJava

  def isr: java.util.List[Broker] = underlying.isr.asJava

  def errorCode: Short = underlying.errorCode

  def sizeInBytes: Int = underlying.sizeInBytes
}


text:
title:  "What is a Breaking Change Anyways?"
date:   2018-01-12 21:49:00
category: til
tags: [api, service, contract, breaking, change, breaking change, signature, method, backwards, compatible, forwards, backwards compatible, forwards compatible, interface]
---

TIL what a breaking change was in the context of a public API or Service.

At work, I am currently working on the public API interface that will be exposed externally to our customers and partners. We are working with teams internally to get their resources ready to be exposed in this interface.

One of the things we have been impressing on our internal partner teams, is that once a resource is exposed on the interface, **breaking changes** will no longer be allowed without rolling the version of the client-facing interface.

We want our clients to be able to integrate with our platform with as little friction as possible. Ensuring our API teams internally are not pushing breaking changes to their APIs will lead to consistent contracts that are easy to integrate with.

But what constitutes a breaking change? And why are breaking changes so disruptive?

## What is a Breaking Change?

As an API or Service owner, **breaking changes are non-backwards compatible changes to the contracts of methods you expose to your consumers through your API interfaces.**

Breaking changes have the potential to literally "break" the applications that consumers of your API have built on top of the endpoints you have exposed. Client apps built on your APIs encode specifics of the `contracts` for each endpoint in their apps, so they can make requests for data they are interested in.

For example, the contract of an endpoint to get a list of dogs from an API might look as follows:

```
Endpoint:
GET /v1/dogs

Required Headers:
- x-api-key
- Authorization

Response:
[
  {
    id: integer,
    name: string,
    age: integer,
    breed: string
  },
  ...
]
```

The above defines the contract for the `dogs` endpoint. Enumerated, the various pieces of the contract are as follows:

  1) The URI to access the resource (/v1/dogs)
  2) The protocol / method used to interact with the endpoint (HTTP / GET)
  3) Request parameters necessary to access the resource (api-key and authorization headers)
  4) The response model for the endpoint (in this case, an array of objects with the specified keys + types)

If non-backwards compatible changes are made to these contracts, clients will break, and you will have unhappy customers.

This doesn't mean that changes can't be made to the APIs and services themselves! **As long as the client-facing contract remains intact, changes can be made without worry of it being a breaking change**. This can often be accomplished with the addition of an [adapter][adapter] that takes APIs with new interfaces and converts them to the publicly exposed one.

## Backwards Compatibility

We've defined that a breaking change is a non-backwards compatible change to a publicly exposed contract, but what constitutes a backwards compatible change?

**Any change that wouldn't cause clients to break would be considered a backwards compatible.**

That's kind of a meta definition... so here are some **examples of backwards compatible changes** to our dog resource above:

1) **Adding new fields to the response model** - If i added a `vaccinations key` to my response model, that wouldn't break my consumers! Even though the new key is sent in requests for the dog resource, the presence of that key won't cause client code to stop working... since clients weren't aware of it until I added it, they will just continue to ignore it in their code until they upgrade.

2) **Adding new methods to the interface** - If I added a `/v1/cats` resource to my interface, that won't cause clients to break! They didn't know about it before, and its presence on the interface shouldn't affect their retrieval of Dogs.

3) **Adding new optional request parameters** - Say I wanted to allow my clients to filter by breed, so I added a query parameter for breed to my dog resource (e.g. `/v1/dogs?=cavalier`). This also shouldn't break clients, since the response from the original request for `/v1/dogs` remains unchanged.

Astute readers will have noticed something about the above three items... they all start with `Adding`. **Adding things to your interface is generally a backwards compatible change.** Non backwards compatible changes all revolve around Updating, or Deleting properties of your interface contracts.

**Non-backwards compatible changes** to the dog resource include:

1) **Changing the names of fields in the response model** - If the `breed` key was renamed to `Breed`, clients looking for the breed of dogs in the response model wouldn't be able to find the value anymore until they refactored to include capitalization of the key name.

2) **Deleting a field from the response model** - If the `name` key was deleted entirely... that is clearly not backwards compatible and would break all consumers looking to read names of dogs out of the response model.

3) **Changing the shape of the response model** - If the response object became nested that would also break consumers.

4) **Changing the URI of the resource** - If the URI changes, clients won't be able to find your resource anymore. Definitely a breaking change, and not backwards compatible.

5) **Changing the method used to access a resource** - If I change access of the `/v1/dogs` resource from a GET to a POST for some reason, that will break my consumers.

6) **Adding new required request parameters** - If I need the users to start passing multiple API keys, or if I need them to start passing the version of the resource they want to access as a header, that's breaking.

So clearly there are many more ways to make changes that break consumers than otherwise. Some breaking changes are so subtle that it is difficult to pick up on them unless you are constantly vigilant.

Requiring API owners to not make breaking changes to their interfaces imposes more rigidity on how services evolve. Some would argue that to make all changes backwards compatible, interfaces become large and clunky.

I think the decoupling provided by an adapter layer that performs conversions to the expected interface contract is ultra- valuable here, and worth the investment up front (even if it is just pass through).

The point here is that we want to make integrating with our public API interface as frictionless as possible for our customers.

We want more customers to build on our platform. If our platform is constantly breaking, the client-rework needed to conform to an ever-changing interface might outweigh the value provided by accessing the underlying resources.

There are certainly other breaking / non-backwards compatible changes to APIs that I didn't mention, so feel free to share in the comments!

[adapter]: /posts/2017-09-09-the-adapter-pattern/


text:
import BaseLayer from 'ember-flexberry-gis/layers/-private/base';

/**
  Class describing tile layer metadata.

  @class TileLayer
*/
export default BaseLayer.extend({
  /**
    Icon class related to layer type.

    @property iconClass
    @type String
    @default 'image icon'
  */
  iconClass: 'image icon',

  /**
    Permitted operations related to layer type.

    @property operations
    @type String[]
    @default ['edit', 'remove']
  */
  operations: ['edit', 'remove'],

  /**
    Creates new settings object (with settings related to layer-type).

    @method createSettings
    @returns {Object} New settings object (with settings related to layer-type).
  */
  createSettings() {
    return {
      url: undefined
    };
  }
});


text:
package org.jephyr.benchmark;

import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;

@State(Scope.Benchmark)
public abstract class AbstractRingBenchmark {

    static final int PARALLELISM = loadParallelism();
    final int workerCount;
    final int ringSize;

    AbstractRingBenchmark() {
        workerCount = Integer.parseInt(System.getProperty("workerCount"));
        ringSize = Integer.parseInt(System.getProperty("ringSize"));
    }

    private static int loadParallelism() {
        String s = System.getProperty("parallelism");
        return s == null ? Runtime.getRuntime().availableProcessors() : Integer.parseInt(s);
    }

    public abstract void benchmark() throws Exception;
}


text:
package test;

import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import viewer.SLogoViewer;
import viewer.Viewer;
import controller.Controller;
import controller.Turtle;
import controller.TurtleCommand;
import controller.TurtleTrace;

public class TestViewer {
//    private static final String[] DEFAULTPARAMETERS=new String[]{"1","0.0","0.0","90.0","true"};
    Controller controller=new Controller();
    Viewer viewer=controller.getViewer();
    List<Turtle> activeTurtle;

    @Before
    public void setUp () throws Exception {
//        controller= new Controller();
//        viewer=controller.getViewer();
    }

    @After
    public void tearDown () throws Exception {

    }

    // Get the latest active turtle from the model
    public void updateActiveTurtle(){
        activeTurtle = controller.getActiveTurtles();
    }

    //Get parameters of the turtle in the model
    public String[] getParamOfModelTurtle(){
        updateActiveTurtle();
        if (activeTurtle==null) {
            return null;
        }
        TurtleTrace turtleTrace = activeTurtle.get(0).getTurtleTrace();
        //get latest command
        TurtleCommand command = turtleTrace.getLatest();
        String turtleID=activeTurtle.get(0).getId();

        return new String[]{turtleID,
                            String.valueOf(command.getX()),
                            String.valueOf(command.getY()),
                            String.valueOf(command.getDirection()),
                            String.valueOf(command.isPenDown())};
    }

    //Get parameters of active turtle in the viewer
    public String[] getTurtleParameters(String[] defaultParams){
        String[] turtleParameters=null;
        // Wait until the turtle has been generated and moved away from the position specified
        // by defaultParams
        while (turtleParameters==null || compareStringArray(turtleParameters,defaultParams)){
           String[] paramReference=((SLogoViewer)viewer).getTurtleParameters();
           if (paramReference!=null) {
               turtleParameters=paramReference.clone();
           }
           System.out.println(turtleParameters);
        }
        return turtleParameters;
    }

    //Compare two String[] arrays to ensure that they are equal
    public boolean compareStringArray(String[] array1, String[] array2){
        if (array1.length!=array2.length) return false;
        for (int i=0;i<array1.length;i++){
            if (!array1[i].equals(array2[i])) return false;
        }
        return true;
    }

    // Reset the screen
    public void reset(){
        String command="clearscreen";
        controller.addCommand(command);
    }

    // Main testing method
    // Gets the latest parameters from the model and viewer and compares
    // them.
    public String[] assertCorrectDisplayTurtle(String[] defaultParams){
        String[] turtleParameters=getTurtleParameters(defaultParams);
        String[] correctParameters=null;
        while (correctParameters==null){
            correctParameters=getParamOfModelTurtle();
        }
        assertTrue(turtleParameters.length==5);
        assertTrue(turtleParameters[0].equals(correctParameters[0]));
        assertTrue(turtleParameters[1].equals(correctParameters[1]));
        assertTrue(turtleParameters[2].equals(correctParameters[2]));
        assertTrue(turtleParameters[3].equals(correctParameters[3]));
        assertTrue(turtleParameters[4].equals(correctParameters[4]));
        return turtleParameters;
    }
    // All tests need to be in one method, as each new test method will create a new
    // instance of jgame, but jgame is static so later tests will not work.
    @Test
    public void testViewer(){
        // Test that the turtle is created correctly
        String[] lastParam=assertCorrectDisplayTurtle(new String[]{});
        String command="fd 100";
        //Test turtle movement
        controller.addCommand(command);
        lastParam=assertCorrectDisplayTurtle(lastParam);
        //Test turtle rotation
        controller.addCommand("rt 90");
        lastParam=assertCorrectDisplayTurtle(lastParam);
        //Test turtle pen
        controller.addCommand("penup");
        lastParam=assertCorrectDisplayTurtle(lastParam);
    }
}


text:
package broker

import "github.com/TheThingsNetwork/ttn/core/types"

func (m *UplinkMessage) GetAppEui() *types.AppEUI {
	if m != nil {
		return m.AppEui
	}
	return nil
}

func (m *UplinkMessage) GetDevEui() *types.DevEUI {
	if m != nil {
		return m.DevEui
	}
	return nil
}

func (m *DownlinkMessage) GetAppEui() *types.AppEUI {
	if m != nil {
		return m.AppEui
	}
	return nil
}

func (m *DownlinkMessage) GetDevEui() *types.DevEUI {
	if m != nil {
		return m.DevEui
	}
	return nil
}

func (m *DeviceActivationRequest) GetAppEui() *types.AppEUI {
	if m != nil {
		return m.AppEui
	}
	return nil
}

func (m *DeviceActivationRequest) GetDevEui() *types.DevEUI {
	if m != nil {
		return m.DevEui
	}
	return nil
}

func (m *DeduplicatedUplinkMessage) GetAppEui() *types.AppEUI {
	if m != nil {
		return m.AppEui
	}
	return nil
}

func (m *DeduplicatedUplinkMessage) GetDevEui() *types.DevEUI {
	if m != nil {
		return m.DevEui
	}
	return nil
}

func (m *DeduplicatedDeviceActivationRequest) GetAppEui() *types.AppEUI {
	if m != nil {
		return m.AppEui
	}
	return nil
}

func (m *DeduplicatedDeviceActivationRequest) GetDevEui() *types.DevEUI {
	if m != nil {
		return m.DevEui
	}
	return nil
}

func (m *ActivationChallengeRequest) GetAppEui() *types.AppEUI {
	if m != nil {
		return m.AppEui
	}
	return nil
}

func (m *ActivationChallengeRequest) GetDevEui() *types.DevEUI {
	if m != nil {
		return m.DevEui
	}
	return nil
}