text:
require('/apps/calendar/test/integration/calendar_integration.js');
require('/apps/calendar/js/calendar.js');
require('/apps/calendar/js/calc.js');

suite('calendar - launch', function() {

  var device;
  var helper = IntegrationHelper;
  var app;

  suiteTeardown(function() {
    yield app.close();
  });

  MarionetteHelper.start(function(client) {
    app = new CalendarIntegration(client);
    device = app.device;
  });

  suiteSetup(function() {
    yield app.launch();
  });

  test('starting display', function() {
    var remoteDate = yield app.remoteDate();
    var month = yield app.element('monthView');

    // should start at month view
    yield app.waitUntilElement(month, 'displayed');

    var today = yield month.findElement(app.selector('present'));
    var id = yield today.getAttribute('data-date');
    var date = Calendar.Calc.dateFromId(id);

    // should highlight current date at the 'present'
    assert.deepEqual(
      Calendar.Calc.createDay(remoteDate),
      Calendar.Calc.createDay(date),
      'should display present day'
    );
  });

  test('initial calendars', function() {
    var toggle = yield app.element('showSettingsBtn');

    yield helper.waitFor(
      toggle.displayed.bind(toggle),
      MochaTask.nextNodeStyle
    );

    yield toggle.click();

    var calendars = yield app.element('calendarList');
    var text = yield calendars.text();

    assert.ok(text, 'has calendars');

    assert.match(
      text, /offline/i,
      'starts with offline calendar'
    );
  });

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015-present Open Networking Laboratory
  ~
  ~ 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.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.onosproject</groupId>
        <artifactId>onos</artifactId>
        <version>1.6.1-SNAPSHOT</version>
    </parent>

    <artifactId>onos-protocols</artifactId>
    <packaging>pom</packaging>

    <description>ONOS southbound protocols</description>

    <modules>
        <module>openflow</module>
        <module>netconf</module>
        <module>pcep</module>
        <module>ovsdb</module>
        <module>bgp</module>
        <module>rest</module>
        <module>ospf</module>
        <module>isis</module>
        <module>snmp</module>
        <module>bmv2</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onlab-misc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onlab-junit</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.onosproject</groupId>
                <artifactId>onos-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

redpajama_set_name: RedPajamaGithub


text:
package io.rdbc.pgsql.core.internal.protocol.messages.backend

object EmptyQueryResponse extends PgBackendMessage


text:
package org.apache.cassandra.service;

import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.cassandra.config.Schema;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.concurrent.Stage;
import org.apache.cassandra.concurrent.StageManager;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ReadCommand;
import org.apache.cassandra.db.ReadResponse;
import org.apache.cassandra.db.Table;
import org.apache.cassandra.net.IAsyncCallback;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.SimpleCondition;
import org.apache.cassandra.utils.WrappedRunnable;

public class ReadCallback<T> implements IAsyncCallback
{
    protected static final Logger logger = LoggerFactory.getLogger( ReadCallback.class );

    public final IResponseResolver<T> resolver;
    protected final SimpleCondition condition = new SimpleCondition();
    private final long startTime;
    protected final int blockfor;
    final List<InetAddress> endpoints;
    private final IReadCommand command;
    protected final AtomicInteger received = new AtomicInteger(0);

    /**
     * Constructor when response count has to be calculated and blocked for.
     */
    public ReadCallback(IResponseResolver<T> resolver, ConsistencyLevel consistencyLevel, IReadCommand command, List<InetAddress> endpoints)
    {
        this.command = command;
        this.blockfor = determineBlockFor(consistencyLevel, command.getKeyspace());
        this.resolver = resolver;
        this.startTime = System.currentTimeMillis();
        boolean repair = randomlyReadRepair();
        sortForConsistencyLevel(endpoints);
        this.endpoints = repair || resolver instanceof RowRepairResolver
                       ? endpoints
                       : endpoints.subList(0, Math.min(endpoints.size(), blockfor));

        if (logger.isDebugEnabled())
            logger.debug(String.format("Blockfor/repair is %s/%s; setting up requests to %s",
                                       blockfor, repair, StringUtils.join(this.endpoints, ",")));
    }

    /**
     * Endpoints is already restricted to live replicas, sorted by snitch preference.  This is a hook for
     * DatacenterReadCallback to move local-DC replicas to the front of the list.  We need this both
     * when doing read repair (because the first replica gets the data read) and otherwise (because
     * only the first 1..blockfor replicas will get digest reads).
     */
    protected void sortForConsistencyLevel(List<InetAddress> endpoints)
    {
        // no-op except in DRC
    }

    private boolean randomlyReadRepair()
    {
        if (resolver instanceof RowDigestResolver)
        {
            assert command instanceof ReadCommand : command;
            String table = ((RowDigestResolver) resolver).table;
            String columnFamily = ((ReadCommand) command).getColumnFamilyName();
            CFMetaData cfmd = Schema.instance.getTableMetaData(table).get(columnFamily);
            return cfmd.getReadRepairChance() > FBUtilities.threadLocalRandom().nextDouble();
        }
        // we don't read repair on range scans
        return false;
    }

    public T get() throws TimeoutException, DigestMismatchException, IOException
    {
        long timeout = DatabaseDescriptor.getRpcTimeout() - (System.currentTimeMillis() - startTime);
        boolean success;
        try
        {
            success = condition.await(timeout, TimeUnit.MILLISECONDS);
        }
        catch (InterruptedException ex)
        {
            throw new AssertionError(ex);
        }

        if (!success)
        {
            StringBuilder sb = new StringBuilder("");
            for (Message message : resolver.getMessages())
                sb.append(message.getFrom()).append(", ");
            throw new TimeoutException("Operation timed out - received only " + received.get() + " responses from " + sb.toString() + " .");
        }

        return blockfor == 1 ? resolver.getData() : resolver.resolve();
    }

    public void response(Message message)
    {
        resolver.preprocess(message);
        int n = waitingFor(message)
              ? received.incrementAndGet()
              : received.get();
        if (n >= blockfor && resolver.isDataPresent())
        {
            condition.signal();
            maybeResolveForRepair();
        }
    }

    /**
     * @return true if the message counts towards the blockfor threshold
     * TODO turn the Message into a response so we don't need two versions of this method
     */
    protected boolean waitingFor(Message message)
    {
        return true;
    }

    /**
     * @return true if the response counts towards the blockfor threshold
     */
    protected boolean waitingFor(ReadResponse response)
    {
        return true;
    }

    public void response(ReadResponse result)
    {
        ((RowDigestResolver) resolver).injectPreProcessed(result);
        int n = waitingFor(result)
              ? received.incrementAndGet()
              : received.get();
        if (n >= blockfor && resolver.isDataPresent())
        {
            condition.signal();
            maybeResolveForRepair();
        }
    }

    /**
     * Check digests in the background on the Repair stage if we've received replies
     * too all the requests we sent.
     */
    protected void maybeResolveForRepair()
    {
        if (blockfor < endpoints.size() && received.get() == endpoints.size())
        {
            assert resolver.isDataPresent();
            StageManager.getStage(Stage.READ_REPAIR).execute(new AsyncRepairRunner());
        }
    }

    public int determineBlockFor(ConsistencyLevel consistencyLevel, String table)
    {
        switch (consistencyLevel)
        {
            case ONE:
                return 1;
            case TWO:
                return 2;
            case THREE:
                return 3;
            case QUORUM:
                return (Table.open(table).getReplicationStrategy().getReplicationFactor() / 2) + 1;
            case ALL:
                return Table.open(table).getReplicationStrategy().getReplicationFactor();
            default:
                throw new UnsupportedOperationException("invalid consistency level: " + consistencyLevel);
        }
    }

    public void assureSufficientLiveNodes() throws UnavailableException
    {
        if (endpoints.size() < blockfor)
        {
            logger.debug("Live nodes {} do not satisfy ConsistencyLevel ({} required)",
                         StringUtils.join(endpoints, ", "), blockfor);
            throw new UnavailableException();
        }
    }

    public boolean isLatencyForSnitch()
    {
        return true;
    }

    private class AsyncRepairRunner extends WrappedRunnable
    {
        protected void runMayThrow() throws IOException
        {
            try
            {
                resolver.resolve();
            }
            catch (DigestMismatchException e)
            {
                if (logger.isDebugEnabled())
                    logger.debug("Digest mismatch:", e);

                ReadCommand readCommand = (ReadCommand) command;
                final RowRepairResolver repairResolver = new RowRepairResolver(readCommand.table, readCommand.key);
                IAsyncCallback repairHandler = new AsyncRepairCallback(repairResolver, endpoints.size());

                for (InetAddress endpoint : endpoints)
                    MessagingService.instance().sendRR(readCommand, endpoint, repairHandler);
            }
        }
    }
}


text:
const APP_PREFIX = 'secure-wallet'
const VERSION = '0.0.1.3'
const CACHE_NAME = APP_PREFIX + VERSION
const URLS = [
  '/secure-wallet/',
  '/secure-wallet/index.html',
  '/secure-wallet/main.css',
  '/secure-wallet/main.js',
  '/secure-wallet/manifest.json',
  '/secure-wallet/images/favicon-16x16.png',
  '/secure-wallet/sw.js',
]
self.addEventListener('install', e => e.waitUntil(swInstall()))
self.addEventListener('activate', e => e.waitUntil(swActivate()))
self.addEventListener('fetch', e => e.respondWith(swFetch(e)))

async function swFetch(e) {
  console.log('sw[fetch]')
  let request = await caches.match(e.request);
  return request || fetchAndCache(e.request);
}

async function swInstall() {
  console.log('sw[install]')
  const cache = await caches.open(CACHE_NAME);
  let options = { headers: { 'cache-control': 'no-cache' }};
  let requests = URLS.map(url => new Request(url, options))
  await cache.addAll(requests);
  await self.skipWaiting();
}

async function swActivate() {
  console.log('sw[activate]')
  let keyList = await caches.keys();
  let cacheWhitelist = keyList.filter(key => key.indexOf(APP_PREFIX));
  cacheWhitelist.push(CACHE_NAME)
  return Promise.all(keyList.map(function (key, i) {
    if (cacheWhitelist.indexOf(key) === -1) {
      console.log('deleting cache : ' + keyList[i])
      return caches.delete(keyList[i])
    }
  }))
}

async function fetchAndCache(request){
  const res = await fetch(request);
  const cache = await caches.open(CACHE_NAME);
  cache.put(request, res.clone());
  return res;
}


text:
title: .map
---

# QPromise::map

*Since: 0.4.0*

```cpp
QPromise<Sequence<T>>::map(Mapper mapper) -> QPromise<QVector<R>>

// With:
// - Sequence: STL compatible container (e.g. QVector, etc.)
// - Mapper: Function(T value, int index) -> R | QPromise<R>
```

::: warning IMPORTANT
This method only applies to promise with sequence value.
:::

Iterates over all the promise values (i.e. `Sequence<T>`) and [maps the sequence](https://en.wikipedia.org/wiki/Map_%28higher-order_function%29)
to another using the given `mapper` function. The type returned by `mapper` determines the type of
the `output` promise. If `mapper` throws, `output` is rejected with the new exception.

If `mapper` returns a promise (or `QFuture`), the `output` promise is delayed until all the promises
are resolved. If any of the promises fails, `output` immediately rejects with the error of the
promise that rejected, whether or not the other promises are resolved.

```cpp
QPromise<QList<QUrl>> input = {...}

auto output = input.map([](const QUrl& url, int index) {
    return QPromise<QByteArray>{[&](auto resolve, auto reject) {
        // download content at 'url' and resolve
        // {...}
    }};
}).map([](const QByteArray& value, ...) {
    // process the downloaded QByteArray
    // {...}
    return DownloadResult{value};
});

// 'output' resolves as soon as all promises returned by
// 'mapper' are fulfilled or at least one is rejected.

// 'output' type: QPromise<QVector<DownloadResult>>
output.then([](const QVector<DownloadResult>& res) {
    // {...}
});
```

::: tip NOTE
The order of the output sequence values is guarantee to be the same as the original sequence,
regardless of completion order of the promises returned by `mapper`.
:::

This function is provided for convenience and is similar to:

```cpp
promise.then([](const Sequence<T>& values) {
    return QtPromise::map(values, [](const T& value, int index) {
        return // {...}
    });
});
```

See also: [`QtPromise::map`](../helpers/map.md)


text:
title: Lubanga - Thomas Lubanga Dyilo - Confirmation of Charges
published: true
event_date: 2007-01-29T00:00:00.000Z
action: Confirmation of Charges
case: the-prosecutor-v-lubanga
accused: thomas-lubanga-dyilo
youtube_id:
slug: lubanga-events-thomas-lubanga-dyilo-confirmation-of-charges
---

[Decision](http://www.icc-cpi.int/iccdocs/doc/doc266175.PDF) on the confirmation of charges


text:
package com.xnlogic.pacer.pipes;

import java.util.ArrayList;
import java.util.NoSuchElementException;

import org.junit.Test;

public class NeverPipeTest {
    @Test(expected=NoSuchElementException.class)
    public void ensureExceptionTest() {
        NeverPipe neverPipe = new NeverPipe();
        ArrayList<Object> starts = new ArrayList<Object>();
        starts.add(new Object());
        neverPipe.setStarts(starts.iterator());
        neverPipe.next();
    }
}


text:
require 'ddr/models/engine'
require 'ddr/models/version'
require 'action_view' # https://github.com/haml/haml/issues/695
require 'active_record'
require 'hydra-core'
require 'hydra/validations'

module Ddr
  extend ActiveSupport::Autoload
  extend Deprecation

  autoload :Actions
  autoload :Auth
  autoload :Datastreams
  autoload :Derivatives
  autoload :Events
  autoload :Index
  autoload :Managers
  autoload :Metadata
  autoload :Notifications
  autoload :Utils
  autoload :Vocab

  def self.const_missing(name)
    if name == :IndexFields
      Deprecation.warn(Ddr::Models, "`Ddr::IndexFields` is deprecated and will be removed in ddr-models 3.0." \
                                    " Use `Ddr::Index::Fields` instead.")
      Index::Fields
    else
      super
    end
  end

  module Models
    extend ActiveSupport::Autoload

    autoload :AdminSet
    autoload :Base
    autoload :Cache
    autoload :Captionable
    autoload :ChecksumInvalid, 'ddr/models/error'
    autoload :Contact
    autoload :ContentModelError, 'ddr/models/error'
    autoload :DerivativeGenerationFailure, 'ddr/models/error'
    autoload :Describable
    autoload :Error
    autoload :EventLoggable
    autoload :FileCharacterization
    autoload :FileManagement
    autoload :FindingAid
    autoload :FixityCheckable
    autoload :Governable
    autoload :HasAdminMetadata
    autoload :HasAttachments
    autoload :HasChildren
    autoload :HasContent
    autoload :HasIntermediateFile
    autoload :HasMultiresImage
    autoload :HasStructMetadata
    autoload :HasThumbnail
    autoload :Indexing
    autoload :Language
    autoload :MediaType
    autoload :NotFoundError, 'ddr/models/error'
    autoload :PermanentId
    autoload :RightsStatement
    autoload :SolrDocument
    autoload :Streamable
    autoload :Structure
    autoload :WithContentFile
    autoload :YearFacet

    module Structures
      extend ActiveSupport::Autoload
      autoload :Agent
      autoload :Div
      autoload :File
      autoload :FileGrp
      autoload :FileSec
      autoload :FLocat
      autoload :Fptr
      autoload :MetsHdr
      autoload :Mptr
      autoload :StructMap
      autoload :ComponentTypeTerm
    end

    # Image server URL
    mattr_accessor :image_server_url

    mattr_accessor :permanent_id_target_url_base do
      "https://repository.duke.edu/id/"
    end

    # Home directory for FITS
    mattr_accessor :fits_home

    # Run file characterization or not?
    mattr_accessor :characterize_files do
      false
    end
    class << self
      alias :characterize_files? :characterize_files
    end

    mattr_accessor :ead_xml_base_url do
      "https://library.duke.edu/rubenstein/findingaids/"
    end

    # Application temp dir - defaults to system temp dir
    mattr_accessor :tempdir do
      Dir.tmpdir
    end

    # Is repository locked?  Default is false.
    # A locked repository behaves as though each object in the repository is locked.
    mattr_accessor :repository_locked do
      false
    end

    mattr_accessor :auto_assign_permanent_id do
      false
    end

    mattr_accessor :auto_update_permanent_id do
      false
    end

    # File path to vips
    mattr_accessor :vips_path

    mattr_accessor :default_mime_type do
      "application/octet-stream"
    end

    # Maps file extensions to preferred media types
    mattr_accessor :preferred_media_types do
      {
        '.aac'  => 'audio/mp4',
        '.f4a'  => 'audio/mp4',
        '.flv'  => 'video/flv',
        '.m4a'  => 'audio/mp4',
        '.mov'  => 'video/quicktime',
        '.mp3'  => 'audio/mpeg',
        '.mp4'  => 'video/mp4',
        '.oga'  => 'audio/ogg',
        '.ogg'  => 'audio/ogg',
        '.srt'  => 'text/plain',
        '.vtt'  => 'text/vtt',
        '.wav'  => 'audio/wav',
        '.webm' => 'video/webm',
        '.zip'  => 'application/zip'
      }
    end

    # Maps media types to preferred file extensions
    mattr_accessor :preferred_file_extensions do
      {
        'application/zip' => 'zip',
        'audio/mp4'       => 'm4a',
        'audio/mpeg'      => 'mp3',
        'audio/ogg'       => 'ogg',
        'audio/wav'       => 'wav',
        'text/vtt'        => 'vtt',
        'video/flv'       => 'flv',
        'video/mp4'       => 'mp4',
        'video/quicktime' => 'mov',
        'video/webm'      => 'webm'
      }
    end

    # Yields an object with module configuration accessors
    def self.configure
      yield self
    end

  end
end

Dir[Ddr::Models::Engine.root.to_s + "/app/models/*.rb"].each { |m| require m }


text:
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/content_essay_detail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.zhx.one.mvp.read.view.EssayDetailActivity"
    tools:showIn="@layout/activity_essay_detail">

        <!--android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"-->
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

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

</LinearLayout>


text:
package com.util.sqlMap;

import java.io.Reader;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class SqlMapConfig {

	private static final SqlMapClient sqlMap;

	static{
		try {
			String resouce = "com/util/sqlMap/sqlMapConfig.xml";
			// 클래스 패스path경로
			// xml에선 .  클래스에선 /
			Reader reader = Resources.getResourceAsReader(resouce);
			sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);

		} catch (Exception e) {
			System.out.println("SqlMapConfig");
			System.out.println(e.toString());
			// 코딩하다난에러는 컴파일에러, 실행하다발생한 에러는 런타임 오류
			throw new RuntimeException("Error : "+ e);
		}
	}

	public static SqlMapClient getSqlMapInstance(){
		return sqlMap;
	}

}


text:
package javax.validation.groups;

public interface Remove {

}


text:
#ifndef __PWG__EMCAL_ALIEMCALFASTORMASKCONTAINER_H__
#define __PWG__EMCAL_ALIEMCALFASTORMASKCONTAINER_H__

#include <vector>
#include <TNamed.h>
#include <TObjArray.h>

class TBrowser;

namespace PWG {

namespace EMCAL {

/**
 * @class AliEmcalFastorMaskContainer
 * @brief Container for offline masked FastORs
 * @ingroup EMCALTRGFW
 * @author Markus Fasel <markus.fasel@cern.ch>, Oak Ridge National Laboratory
 * @since June 1st, 2021
 *
 * # Container for masked FastORs
 *
 * The container structure is designed as OADB object for FastORs which
 * are tagged offline. FastORs can have two different tags:
 * - Dead: FastOR should always be ignored
 * - Bad: Warm FastORs with dedicated noise pattern, up to user analysis
 *
 * The object has dedicated getters and setters for the channel status.
 * In order to display the masked channels, the object is made browsable.
 * As the Browse function internally relies on the trigger mapping in order
 * to convert the FastOR absolute ID into a positon in EMCAL the run version
 * (Run1 or Run2) needs to be specified when constructing the object.
 */
class AliEmcalFastorMaskContainer : public TNamed {
public:

  /**
   * @enum MaskStatus_t
   * @brief Type of FastOR masking
   */
  enum MaskStatus_t {
    kDeadFastOR = 0,            ///< FastOR is set to dead
    kBadFastOR = 1,             ///< FastOR is set to bad
    kStatusUndefined = -1       ///< Mask status not defined
  };

  /**
   * @enum RunType_t
   * @brief Type of the run
   */
  enum RunType_t {
    kRun1 = 0,                  ///< Run1 (2010-2013)
    kRun2 = 1,                  ///< Run2 (2015-2018)
    kRuntypeUndefined = -1      ///< Unknown
  };

  /**
   * @brief Dummy constructor
   */
  AliEmcalFastorMaskContainer();

  /**
   * @brief Constructor, setting also the name
   * @param name Name of the container
   */
  AliEmcalFastorMaskContainer(const char *name);

  /**
   * @brief Browse functionality: Draw map of masked FastORs
   * @param b Browser where to draw the FastORs.
   */
  virtual void Browse(TBrowser *b);

  /**
   * @brief Mark type as not folder
   * @return Always false
   */
  virtual Bool_t IsFolder() const { return false; }

  /**
   * @brief Destructor
   */
  virtual ~AliEmcalFastorMaskContainer() {}

  /**
   * @brief Clear list of masked FastORs (container empty afterwards)
   */
  virtual void Clear(Option_t * /*option*/ ="") { fMaskedFastors.Clear(); }

  /**
   * @brief Get list of all masked FastORs (bad and dead)
   * @return List of all masked FastORs
   */
  std::vector<int> GetMaskAll() const;

  /**
   * @brief Get list of dead FastORs
   * @return List of dead FastORs
   */
  std::vector<int> GetMaskDead() const;

  /**
   * @brief Get list of bad FastORs
   * @return List of bad FastORs
   */
  std::vector<int> GetMaskBad() const;

  /**
   * @brief Get the the mask status of a dedicated FastOR
   * @param absID Absolute ID of the FastOR
   * @return Mask status of the FastOR (kUndefined if not found)
   */
  MaskStatus_t GetFastorMaskStatus(int absID) const;

  /**
   * @brief Check whether a FastOR with a given absolute ID is dead
   * @param absID Absolute ID of the FastOR
   * @return True if the FastOR is dead, false otherwise
   */
  bool IsDeadFastor(int absID) const { return GetFastorMaskStatus(absID) == MaskStatus_t::kDeadFastOR; }

  /**
   * @brief Check whether a FastOR with a given absolute ID is bad
   * @param absID Absolute ID of the FastOR
   * @return True if the FastOR is bad, false otherwise
   */
  bool IsBadFastor(int absID) const { return GetFastorMaskStatus(absID) == MaskStatus_t::kBadFastOR; }

  /**
   * @brief Check whether a FastOR with a given absolute ID is bad
   * @param absID Absolute ID of the FastOR
   * @return True if the FastOR is bad, false otherwise
   */
  bool IsGoodFastor(int absID) const { return GetFastorMaskStatus(absID) == MaskStatus_t::kStatusUndefined; }

  /**
   * @brief Add new dead FastOR to the mask container
   * @param absID Absolute ID of the FastOR
   */
  void AddDeadFastor(int absID) { SetFastorStatus(absID, MaskStatus_t::kDeadFastOR); }

  /**
   * @brief Add new bad FastOR to the mask container
   * @param absID Absolute ID of the FastOR
   */
  void AddBadFastor(int absID) { SetFastorStatus(absID, MaskStatus_t::kBadFastOR); }

  /**
   * @brief Mask FastOR as good (remove from container if present)
   * @param absID Absolute ID of the FastOR
   */
  void SetGoodFastor(int absID) { SetFastorStatus(absID, MaskStatus_t::kStatusUndefined); }

  /**
   * @brief Add list of dead FastORs
   * @param absIDs List of absolute FastOR IDs to be masked dead
   *
   * In case the FastORs are already present in the container only
   * the status is updated, otherwise they are added as new entry.
   */
  void AddDeadFastors(std::vector<int> absIDs);

  /**
   * @brief Add list of bad FastORs
   * @param absIDs List of absolute FastOR IDs to be masked bad
   *
   * In case the FastORs are already present in the container only
   * the status is updated, otherwise they are added as new entry.
   */
  void AddBadFastors(std::vector<int> absIDs);

  /**
   * @brief Get the number of masked FastORs in the container
   * @return Number of FastORs
   */
  int Size() const { return fMaskedFastors.GetEntries(); }

  /**
   * @brief Set the mask status for a given FastOR status
   * @param absID Absolute ID of the FastOR
   * @param status Status (bad/dead/undefined)
   *
   * In case the FastOR is not yet listed, add it in case it
   * is bad or dead, otherwise just update the status. In case
   * the status in good (undefined), remove it from the list
   */
  void SetFastorStatus(int absID, MaskStatus_t status);

  /**
   * @brief Set the run type (run1 or run2)
   * @param runtype Run type
   */
  void SetRunType(RunType_t runtype) { fRunType = runtype; }

  /**
   * @brief Set the runtype by run number
   * @param runnumber Run number of the current run
   */
  void SetRunTypeByRunNumber(int runnumber) { if(runnumber <= 197388) fRunType = RunType_t::kRun1; else fRunType = RunType_t::kRun2; }

  /**
   * @class MaskedFastor
   * @brief Helper class storing FastOR information within the AliEmcalFastorMaskContainer
   *
   * The object is ROOT and C++ sortable, according to the FastOR absolute ID. As information
   * it stores the FastOR absolute ID and the mask status.
   */
  class MaskedFastor : public TObject {
  public:

    /**
     * @brief Dummy constructor
     */
    MaskedFastor() : TObject(), fFastORAbsID(-1), fMaskStatus(MaskStatus_t::kStatusUndefined) {}

    /**
     * @brief Constructor, also initializing the FastOR object
     * @param absID  Absolute ID of the FastOR
     * @param status Mask status (bad/dead)
     */
    MaskedFastor(int absID, MaskStatus_t status): TObject(), fFastORAbsID(absID), fMaskStatus(status) {}

    /**
     * @brief Destructor
     */
    virtual ~MaskedFastor() {}

    /**
     * @brief Comparison operator for equalness
     * @param other FastOR to compare to
     * @return True in case the FastORs have the same absolute ID, false otherwise
     */
    bool operator==(const MaskedFastor &other) const { return fFastORAbsID == other.fFastORAbsID; }

    /**
     * @brief Comparison operator for smaller
     * @param other FastOR to compare to
     * @return True if the FastOR abs ID is smaller than the other, false otherwise
     */
    bool operator<(const MaskedFastor &other) const { return fFastORAbsID < other.fFastORAbsID; }

    /**
     * @brief Mark object as ROOT-sortable
     * @return Always true
     */
    virtual Bool_t IsSortable() const { return true; }

    /**
     * @brief ROOT check for equalness
     * @param obj Object to compare to
     * @return True if the other object is a MaskedFastor and the FastOR abs IDs are equal, false otherwise
     */
    virtual Bool_t IsEqual(const TObject *obj) const {
      const MaskedFastor *otherfastor = dynamic_cast<const MaskedFastor *>(obj);
      if(!otherfastor) return false;
      return *this == *otherfastor;
    }

    /**
     * @brief ROOT comparison function
     * @param obj Object to compare to
     * @return -1 in case this object is smaller or other is not a MaskedFastor, 0 if the FastORs are equal, 1 if this FastOR is larger than the other
     */
    virtual Int_t Compare(const TObject *obj) const {
      const MaskedFastor *otherfastor = dynamic_cast<const MaskedFastor *>(obj);
      if(!otherfastor) return -1;
      if(*this == *otherfastor) return 0;
      else if (*this < *otherfastor) return -1;
      else return 1;
    }

    /**
     * @brief Get absolute ID of the FastOR
     * @return Absolute ID of the FastOR
     */
    int GetAbsID() const { return fFastORAbsID; }

    /**
     * @brief Get the mask status of the FastOR (dead/bad)
     * @return Mask status of the FastOR
     */
    MaskStatus_t GetMaskStatus() const { return fMaskStatus; }

    /**
     * @brief Check whether the FastOR was masked as bad
     * @return True if the FastOR is bad, false otherwise
     */
    bool IsBad() const { return fMaskStatus == MaskStatus_t::kBadFastOR; }

    /**
     * @brief Check if the FastOR was masked as dead
     * @return True  if the FastOR is dead, false otherwise
     */
    bool IsDead() const { return fMaskStatus == MaskStatus_t::kDeadFastOR; }

    /**
     * @brief Set the absolute ID of the FastOR
     * @param absID Absolute ID of the FastOR
     */
    void SetAbsID(int absID) { fFastORAbsID = absID; }

    /**
     * @brief Set the mask status (bad/dead) of the FastOR
     * @param status Mask status
     */
    void SetMaskStatus(MaskStatus_t status) { fMaskStatus = status; }

    /**
     * @brief Mask FastOR as bad
     */
    void SetBad() { SetMaskStatus(MaskStatus_t::kBadFastOR); }

    /**
     * @brief Mask FastOR as dead
     */
    void SetDead() { SetMaskStatus(MaskStatus_t::kDeadFastOR); }

  private:
    int             fFastORAbsID;     ///< Absolute ID of the FastOR
    MaskStatus_t    fMaskStatus;      ///< Mask Status (dead / bad)

    ClassDef(MaskedFastor, 1);
  };

private:

  /**
   * @brief Helper function finding masked FastOR object within the container
   * @param absID
   * @return MaskedFastor*
   */
  MaskedFastor *FindInContainer(int absID) const;

  TObjArray fMaskedFastors;           ///< Container with masked FastORs
  RunType_t fRunType;                 ///< Period in which run was taken, needed for Browse functionality

  ClassDef(AliEmcalFastorMaskContainer, 1);
};

/**
 * @class TestAliEmcalFastorMaskContainer
 * @brief Unit test for the EMCAL Fastor mask container
 * @ingroup EMCALTESTS
 */
class TestAliEmcalFastorMaskContainer : public TObject {
public:

  /**
   * @brief Constructor
   */
  TestAliEmcalFastorMaskContainer() : TObject() {}

  /**
   * @brief Destructor
   */
  virtual ~TestAliEmcalFastorMaskContainer() {}

  /**
   * @brief Test runner for all tests
   * @return true All tests passed
   * @return false At least one test did not pass
   */
  bool RunAllTests() const;

  /**
   * @brief Run in-memory test
   * @return true Test passed
   * @return false Test failed
   *
   * Preparing a container with example bad and dead channel list,
   * and check whether the list of bad/dead channels matches the
   * list inserted. Container is not written to file.
   */
  bool TestInMemory() const;

  /**
   * @brief Test file IO
   * @return true Test passed
   * @return false Test failed
   *
   * Preparing a container with example bad and dead channel list and
   * write it to file. Then the container is read again from file and
   * compared to the input list to check wether the bad/dead channels
   * match.
   */
  bool TestIO() const;

  /**
   * @brief Test changing the status of certain FastORs
   * @return true Test passed
   * @return false Test failed
   *
   * Preparing a container with bad and dead channel list. Randomly
   * 5 channels are selected for which the status is changed from which
   * the status is changed from dead to bad and vice versa. Lists of
   * dead and bad channels after the test must match with the input lists
   * including the change of the channel status
   */
  bool TestChangeStatus() const;

  /**
   * @brief Test of the Clean method
   * @return true Test passed
   * @return false Test failed
   *
   * Preparing a container with bad and dead channel list. The clean method
   * is called then. After clean the list of bad and dead channels obtained
   * from the container must be empty.
   */
  bool TestClean() const;

private:

  /**
   * @brief Get example list with bad channels for unit tests
   * @return Example lists with bad channels
   */
  std::vector<int> GetTestBadChannels() const;

  /**
   * @brief Get example list with dead channels for unit test
   * @return Example list with dead channels
   */
  std::vector<int> GetTestDeadChannels() const;

  /**
   * @brief Check where two vectors have the same content
   * @param list1 First list in teh check for equalness
   * @param list2 Second list in the check for equalness
   * @return true Vectors are equal
   * @return false
   */
  bool CheckEqual(const std::vector<int> &list1, const std::vector<int> &list2) const;

  /**
   * @brief Select randomly elements from a given inputlist
   * @param inputlist Input list
   * @param length Number of entries to select
   * @return List with entries obtained from the inputlist
   */
  std::vector<int> GetRandomSubsample(std::vector<int> inputlist, int length) const;

  /**
   * @brief Helper function printing the content of the vector
   * @param data Vector to monitor
   * @param header Header printed above the vector content
   */
  void printVector(std::vector<int> data, const char *header) const;

  ClassDef(TestAliEmcalFastorMaskContainer, 1);
};

}

}

#endif // __PWG__EMCAL_ALIEMCALFASTORMASKCONTAINER_H__


text:
#ifndef LOVE_MOUSE_WRAP_MOUSE_H
#define LOVE_MOUSE_WRAP_MOUSE_H

// LOVE
#include "common/runtime.h"
#include "common/config.h"

namespace love
{
namespace mouse
{

int w_newCursor(lua_State *L);
int w_getSystemCursor(lua_State *L);
int w_setCursor(lua_State *L);
int w_getCursor(lua_State *L);
int w_getX(lua_State *L);
int w_getY(lua_State *L);
int w_getPosition(lua_State *L);
int w_setX(lua_State *L);
int w_setY(lua_State *L);
int w_setPosition(lua_State *L);
int w_isDown(lua_State *L);
int w_setVisible(lua_State *L);
int w_isVisible(lua_State *L);
int w_setGrabbed(lua_State *L);
int w_isGrabbed(lua_State *L);
int w_setRelativeMode(lua_State *L);
int w_getRelativeMode(lua_State *L);
extern "C" LOVE_EXPORT int luaopen_love_mouse(lua_State *L);

} // mouse
} // love

#endif // LOVE_MOUSE_WRAP_MOUSE_H


text:
![meta.php](http://i.hizliresim.com/Wgym6P.png)
# Meta.php

Meta.php ile meta etiketlerini çok basit bir şekilde yönetebilirsiniz.
Bu classı genellikle "header.php", "footer.php", "sidebar.php" vb gibi proje dosyalarınız var ise kullanabilirsiniz.
# Kurulum
Kurulum için 2 farklı yol deneyebilirsinz. Tavsiyemiz: Github üzerinden indirmenizdir.
#### Composer ile kurulum;
```sh
$ composer require hamzaemre/meta.php
```
#### Direk projeyi indirmek;
https://github.com/hamzaemre/meta.php/archive/master.zip

# Kullanım
PHP bilenler için çok basit kullanımı mevcuttur. Aşağıdaki kod ile her sayfanın kendine özgü içeriklerini barındıran tek dosyayı okutup yazdırabilirsiniz. Dinamik sayfalarınız için olan kullanım şekli için "Dinamik kullanım" kısmına bakın.
```php
<?php
    // Classımızı dahil ediyoruz.
    require_once 'Meta.php';
    // $meta değişkenine yeni bir sınıf oluşturup atama yapıyoruz.
    $meta = new Meta;
    // Daha sonra $meta->Start(); fonksiyonu ile json dosyamızı okutup içindeki gerekli değerleri alıp işliyoruz. Mesela "title", "meta", "facebook meta", "twitter meta"
    $meta->Start();
```
# Dinamik kullanım:
```php
require_once 'Meta.php';
require_once 'database.php';

$baslik = $data_row['title']; // Blog yazısı için veritabanından gelen başlık...
$meta = new Meta;
$meta->setTitle("Blog yazısı 1"); // 1. örnek
$meta->setTitle($baslik); // 2. örnek

$meta->setMetaTags(array(
    "keywords" => "kelime, meta, php, bla bla",
    "description" => "Açıklama kısmı..."
));
```
# metatags.json
```json
{
  "main_path": "/local_folder/",
  "pages": {
    "index.php": {
      "title": "Anasayfa",
      "meta": {
        "keywords": "ana sayfa, web sitesi, bla bla",
        "description": "Ana sayfasının description kısmı..."
      },
      "facebook_meta": {
        "url": "http://www.site.com/index.php",
        "type": "article",
        "title": "Facebook Title",
        "description": "Facebook description...",
        "image": "http://www.site.com/image.jpg"
      },
      "twitter_meta": {
        "card": "summary_large_image",
        "site": "@username",
        "creator": "@username",
        "title": "Twitter Title",
        "description": "Twitter description...",
        "image:src": "http://www.site.com/image.jpg"
      }
    }
  }
}
```
Burada en önemli kısım "main_path" kısmıdır. Eğer script'iniz, local sunucuda yada server'da bir dizin altında çalışıyor ise bunu belirtmelisiniz.

----
# Bana ulaşın:
##### Gmail: hamzaemre0@gmail.com
##### Twitter: https://twitter.com/HamzaEmrel


text:
package com.adobe.epubcheck.util;

import java.util.HashSet;
import java.util.Set;

import com.adobe.epubcheck.api.Report;

public class MetaUtils {

	public static Set<String> validateProperties(String propertyValue,
			Set<String> recognizedUnprefixedValues,
			Set<String> recognizedPrefixes, String path, int line, int column,
			Report report, boolean singleValue) {

		if (propertyValue == null)
			return null;

		Set<String> unprefixedValues = new HashSet<String>();

		propertyValue = propertyValue.trim();
		propertyValue = propertyValue.replaceAll("[\\s]+", " ");
		String propertyArray[] = propertyValue.split(" ");

		if (singleValue && propertyArray.length > 1)
			report.error(path, line, column, "Property can take only one value");

		for (int i = 0; i < propertyArray.length; i++)
			if (propertyArray[i].endsWith(":"))
				report.error(
						path,
						line,
						column,
						propertyArray[i]
								+ " value is not allowed to be composed only by a prefix");
			else if (propertyArray[i].contains(":"))
				checkPrefix(
						recognizedPrefixes,
						propertyArray[i].substring(0,
								propertyArray[i].indexOf(':')), path, line,
						column, report);
			else if (recognizedUnprefixedValues != null
					&& recognizedUnprefixedValues.contains(propertyArray[i]))
				unprefixedValues.add(propertyArray[i]);
			else
				report.error(path, line, column, "Undefined property: "
						+ propertyArray[i] + (propertyArray[i].equals("acknowledgements") ? " (use notation 'acknowledgments' instead)" : "") );

		return unprefixedValues;
	}

	static boolean checkPrefix(Set<String> prefixSet, String prefix,
			String path, int line, int column, Report report) {

		if (!prefixSet.contains(prefix)) {
			report.error(path, line, column, "Undecleared prefix: " + prefix);
			return false;
		}
		return true;
	}
}


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<link rel="import" href="../../bower_components/app-route/app-route.html">

<link rel="import" href="../../bower_components/iron-flex-layout/iron-flex-layout.html">
<link rel="import" href="../../bower_components/iron-image/iron-image.html">

<link rel="import" href="../../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../../bower_components/paper-material/paper-material.html">
<link rel="import" href="../../bower_components/paper-tooltip/paper-tooltip.html">

<link rel="import" href="../../bower_components/neon-animation/neon-shared-element-animatable-behavior.html">

<link rel="import" href="../styles/shared-styles.html">
<link rel="import" href="../elements/truncate-marked-text.html">
<link rel="import" href="../elements/speaker-details.html">
<link rel="import" href="../elements/footer-block.html">
<link rel="import" href="../behaviors/utils-behavior.html">
<link rel="import" href="../behaviors/page-behavior.html">
<link rel="import" href="../behaviors/localize-behavior.html">

<dom-module id="speakers-page">

  <template>

    <app-route route="{{route}}"
               pattern="/:speakerId"
               data="{{routeData}}"></app-route>

      <template is="dom-repeat" items="[[_toArray(speakers)]]" as="speaker" on-dom-change="_updateCascadedNodes">

          <paper-material class="card">

              <iron-image src="[[speaker.photoUrl]]" class="photo placeholder-color" preload fade
                          sizing="cover"></iron-image>

                <template is="dom-repeat" items="[[speaker.badges]]" as="badge">

                    [[badge.name]]
                    <paper-tooltip>[[badge.description]]</paper-tooltip>

                </template>

                [[speaker.name]]
                [[speaker.country]]

              <iron-image class="company-logo" src="{{speaker.companyLogo}}" sizing="contain"></iron-image>

{{localize('skills')}}:
                <template is="dom-repeat" items="[[speaker.tags]]" as="tag">
                  [[tag]]
                </template>

              <marked-element class="details-text" markdown="[[speaker.shortBio]]">

              </marked-element>

              <template is="dom-repeat" items="[[speaker.socials]]" as="social">

                  <paper-icon-button class="social-icon"
                                     icon$="icons:{{social.icon}}"></paper-icon-button>

              </template>

          </paper-material>

      </template>

    <speaker-details id="speakerDetails"
                     app="{{app}}"
                     speaker="{{_selectedSpeaker}}"
                     entry-animation="scale-up-animation"
                     exit-animation="fade-out-animation"
                     with-backdrop>
    </speaker-details>

  </template>

</dom-module>


text:
FakeIt
======

[![Join the chat at https://gitter.im/eranpeer/FakeIt](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/eranpeer/FakeIt?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

GCC: [![Build Status GCC](https://travis-ci.org/eranpeer/FakeIt.svg?branch=master)](https://travis-ci.org/eranpeer/FakeIt)
[![Coverage Status](https://coveralls.io/repos/eranpeer/FakeIt/badge.svg?branch=master&service=github)](https://coveralls.io/github/eranpeer/FakeIt?branch=master)

MSC: [![Build status MSC](https://ci.appveyor.com/api/projects/status/sy2dk8se2yoxaqve)](https://ci.appveyor.com/project/eranpeer/fakeit)

FakeIt is a simple mocking framework for C++. It supports GCC, Clang and MS Visual C++.

FakeIt is written in C++11 and can be used for testing both C++11 and C++ projects.

```cpp
struct SomeInterface {
	virtual int foo(int) = 0;
	virtual int bar(string) = 0;
};
```
```cpp
// Instantiate a mock object.
Mock<SomeInterface> mock;

// Setup mock behavior.
When(Method(mock,foo)).Return(1); // Method mock.foo will return 1 once.

// Fetch the mock instance.
SomeInterface &i = mock.get();

// Will print "1".
cout << i.foo(0);

```
Verify method invocation
```cpp
Mock<SomeInterface> mock;

When(Method(mock,foo)).Return(0);

SomeInterface &i = mock.get();

// Production code
i.foo(1);

// Verify method mock.foo was invoked.
Verify(Method(mock,foo));

// Verify method mock.foo was invoked with specific arguments.
Verify(Method(mock,foo).Using(1));
```

Checkout the [Quickstart](https://github.com/eranpeer/FakeIt/wiki/Quickstart) for many more examples!

Download the [Latest Release](https://github.com/eranpeer/FakeIt/releases/latest) and start using FakeIt now!

## Features
* Packaged as a **single header file**.
* Very simple API based on the expressiveness of C++11.
* Supports all major compilers: GCC, Clang and MSC++.
* Easily integrated with [**GTest**](https://code.google.com/p/googletest/), [**MS Test**](http://en.wikipedia.org/wiki/Visual_Studio_Unit_Testing_Framework) and [**Boost Test**](http://www.boost.org/doc/libs/1_56_0/libs/test/doc/html/index.html).
* Expressive [Arrange-Act-Assert](http://xp123.com/articles/3a-arrange-act-assert/) syntax.
* Create mock classes or **spy existing objects** instantly in one simple line.
* No limitation on number of method arguments.
* Supports dynamic casting.

## Installation
FakeIt is a header only framework. It does not require any installation. For extra simplicity fakeit is packaged as a single header file.

FakeIt is pre-configured to work with some of the major unit testing frameworks. A pre-configured version will use the assertions mechanism of the unit testing framework to integrate the generated error messages into the unit testing framework output.

If you don't find your unit testing framework on the list, simply use the *standalone* configuration.

### Using a pre-packaged single header file
Pre-packaged single header versions of FakeIt are located under the *single_header* folder.
Depending on the unit testing framework you use, simply add one of the pre-packaged versions to the include path of your test project:
* <fakeit_folder>/single_header/[gtest](https://github.com/google/googletest)
* <fakeit_folder>/single_header/mstest
* <fakeit_folder>/single_header/boost
* <fakeit_folder>/single_header/[catch](https://github.com/philsquared/Catch)
* <fakeit_folder>/single_header/[tpunit](https://github.com/tpounds/tpunitpp)
* <fakeit_folder>/single_header/[mettle](https://github.com/jimporter/mettle)
* <fakeit_folder>/single_header/standalone

For example, to use fakeit with **Google Test** simply add the *single_header/gtest* folder to the include path of your test project:
```
-I"<fakeit_folder>/single_header/gtest"
```
### Using the source header files
Fakeit source code header files are located under the *include* foler. To use FakeIt directly from the source code all you need to do is to download the source files and add the *include* folder and the configuration folder of your choice to the include path of your project.
For example:
* To use fakeit with **Google Test** add the *include* folder and the *config/gtest* folder to the include path of your test project:
```
-I"<fakeit_folder>/include" -I"<fakeit_folder>/config/gtest"
```
* To use fakeit with **MS Test** add the *include* folder and the *config/mstest* folder to the include path of your test project:
```
-I"<fakeit_folder>/include" -I"<fakeit_folder>/config/mstest"
```
* To use fakeit with **Boost Test** add the *include* folder and the *config/boost* folder to the include path of your test project:
```
-I"<fakeit_folder>/include" -I"<fakeit_folder>/config/boost"
```
* To use fakeit with **Catch** add the *include* folder and the *config/catch* folder to the include path of your test project:
```
-I"<fakeit_folder>/include" -I"<fakeit_folder>/config/catch"
```
* To use fakeit with **tpunit** add the *include* folder and the *config/tpunit* folder to the include path of your test project:
```
-I"<fakeit_folder>/include" -I"<fakeit_folder>/config/tpunit"
```
* To use fakeit with **Mettle** add the *include* folder and the *config/mettle* folder to the include path of your test project:
```
-I"<fakeit_folder>/include" -I"<fakeit_folder>/config/mettle"
```
* To use fakeit without any testing framework integration (**standalone**) add the *include* folder and the *config/standalone* folder to the include path of your test project:
```
-I"<fakeit_folder>/include" -I"<fakeit_folder>/config/standalone"
```
It is recommended to build and run the unit tests to make sure FakeIt fits your environment.
#### Building and Running the Unit Tests with GCC
```
cd build
make all
```
run the tests by typing
```
./fakeit_tests.exe
```
#### Building and Running the Unit Tests with Clang
```
cd build
make -f clang_makefile all
```
run the tests by typing
```
./fakeit_tests.exe
```
#### Building and Running the Unit Tests with Visual Studio
Open the tests/all_tests.vcxproj project file with Visual Studio 2013. Build and run the project and check the test results.
## Limitations
* Currently only GCC, Clang and MSC++ are supported.
* Can't mock classes with multiple inheritance.
* Can't mock classes with virtual inheritance.
* Currently mocks are not thread safe.


text:
	Home > Shopping List

Shopping List with no cookies in it!

	<shopping-list items="list.items"></shopping-list>


text:
Get the best price

Home

Get the best price

        <form role="form" method="post" action="/bestprice" id="bestpriceForm">

                Email address
                <input type="email" class="form-control" name="userEmail" id="userEmail" placeholder="Enter email" required data-validation="email">

            <?php echo $_token('bestprice'); ?>
            <button id="form-submit" type="submit" class="btn btn-primary ladda-button" data-style="expand-right">Submit</button>
        </form>


text:
package de.mhu.os.fr.nr1;

import javax.swing.JFrame;

import de.mhu.os.fr.gui.SurfaceFrame;
import de.mhu.os.fr.model.Creature;
import de.mhu.os.fr.model.SerializedSurface;
import de.mhu.os.fr.model.Surface;
import de.mhu.os.fr.model.SurfaceGenerator;
import de.mhu.os.fr.util.ValueSource;
import de.mhus.lib.MSwing;

public class Number1 {

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		Surface s = new Surface( 100, 100 );
		SurfaceGenerator.generateSimple( s, 0.1 );
		SerializedSurface save = s.serialize();

		//s.addSource( 10, 10, new ValueSource( (byte)5 ) );
		SurfaceGenerator.generateSources( s, 3 );

		SurfaceFrame frame = new SurfaceFrame( s );
		frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
		frame.setTitle( "Number 1" );
		//ASwing.tribleFrame( frame );
		frame.pack();
		MSwing.centerFrame( frame );
		frame.setVisible( true );

		int round = 0;
		while ( true ) {
			round++;
			s.restore( save );
			for ( int i = 0; i < 10; i++ ) {
				Creature1 c = new Creature1( i % 2 == 0);
				s.addCreature( c, (int)(Math.random()*s.getWidth()), (int)(Math.random()*s.getHeight()) );
			}

			s.loop( round );
			s.clearCreatures();
			//System.out.println( "Exited" );
		}
	}

}


text:
namespace util {
namespace stream {

class ChainPosition;

class ReadSizeException : public util::Exception {
  public:
    ReadSizeException() throw();
    ~ReadSizeException() throw();
};

class Read {
  public:
    explicit Read(int fd) : file_(fd) {}
    void Run(const ChainPosition &position);
  private:
    int file_;
};

// Like read but uses pread so that the file can be accessed from multiple threads.
class PRead {
  public:
    explicit PRead(int fd, bool take_own = false) : file_(fd), own_(take_own) {}
    void Run(const ChainPosition &position);
  private:
    int file_;
    bool own_;
};

class Write {
  public:
    explicit Write(int fd) : file_(fd) {}
    void Run(const ChainPosition &position);
  private:
    int file_;
};

// It's a common case that stuff is written and then recycled.  So rather than
// spawn another thread to Recycle, this combines the two roles.
class WriteAndRecycle {
  public:
    explicit WriteAndRecycle(int fd) : file_(fd) {}
    void Run(const ChainPosition &position);
  private:
    int file_;
};

class PWrite {
  public:
    explicit PWrite(int fd) : file_(fd) {}
    void Run(const ChainPosition &position);
  private:
    int file_;
};

// Reuse the same file over and over again to buffer output.
class FileBuffer {
  public:
    explicit FileBuffer(int fd) : file_(fd) {}

    PWrite Sink() const {
      util::SeekOrThrow(file_.get(), 0);
      return PWrite(file_.get());
    }

    PRead Source(bool discard = false) {
      return PRead(discard ? file_.release() : file_.get(), discard);
    }

    uint64_t Size() const {
      return SizeOrThrow(file_.get());
    }

  private:
    scoped_fd file_;
};

} // namespace stream
} // namespace util
#endif // UTIL_STREAM_IO_H


text:
package io.swagger.api.factories;

import io.swagger.api.JobsApiService;
import io.swagger.api.impl.JobsApiServiceImpl;

public class JobsApiServiceFactory {

   private final static JobsApiService service = new JobsApiServiceImpl();

   public static JobsApiService getJobsApi()
   {
      return service;
   }
}


text:
class TestUtils(object):

    @staticmethod
    def lists_are_equal(list1, list2):
        return sorted(list1) == sorted(list2)

    @staticmethod
    def lists_are_not_equal(list1, list2):
        return sorted(list1) != sorted(list2)


text:
package org.cloudfoundry.logcache.v1;

import org.immutables.value.Value;

/**
 * The request payload for the Info operation
 */
@Value.Immutable
abstract class _InfoRequest {

}


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

package org.chromium.webengine;

import android.net.Uri;

import androidx.annotation.NonNull;

import org.chromium.webengine.interfaces.INavigationParams;

/**
 * {@link Navigation} contains information about the current Tab Navigation.
 */
public class Navigation {
    private INavigationParams mNavigationParams;

    Navigation(@NonNull INavigationParams navigationParams) {
        mNavigationParams = navigationParams;
    }

    /**
     * The uri the main frame is navigating to. This may change during the navigation when
     * encountering a server redirect.
     */
    @NonNull
    public Uri getUri() {
        return mNavigationParams.uri;
    }

    /**
     * Returns the status code of the navigation. Returns 0 if the navigation hasn't completed yet
     * or if a response wasn't received.
     */
    public int getStatusCode() {
        return mNavigationParams.statusCode;
    }

    /**
     * Whether the navigation happened without changing document. Examples of same document
     * navigations are:
     *  - reference fragment navigations
     *  - pushState/replaceState
     *  - same page history navigation
     */
    public boolean isSameDocument() {
        return mNavigationParams.isSameDocument;
    }
}


text:
Mocha-like tests in phantomjs script

This attempt is abandoned.

The newest mocha version really struggles inside phantom 2.0.

Using [node-phantom-simple](https://www.npmjs.com/package/node-phantom-simple) bridge inside mocha tests that run in node produces good results and a low performance cost (less than 20% including spawning phantomjs for a single test that runs for approx 2 sec.)


text:
"""Constants for the Jellyfin integration."""
import logging
from typing import Final

from homeassistant.const import Platform, __version__ as hass_version

DOMAIN: Final = "jellyfin"

CLIENT_VERSION: Final = hass_version

COLLECTION_TYPE_MOVIES: Final = "movies"
COLLECTION_TYPE_MUSIC: Final = "music"

CONF_CLIENT_DEVICE_ID: Final = "client_device_id"

DEFAULT_NAME: Final = "Jellyfin"

ITEM_KEY_COLLECTION_TYPE: Final = "CollectionType"
ITEM_KEY_ID: Final = "Id"
ITEM_KEY_IMAGE_TAGS: Final = "ImageTags"
ITEM_KEY_INDEX_NUMBER: Final = "IndexNumber"
ITEM_KEY_MEDIA_SOURCES: Final = "MediaSources"
ITEM_KEY_MEDIA_TYPE: Final = "MediaType"
ITEM_KEY_NAME: Final = "Name"

ITEM_TYPE_ALBUM: Final = "MusicAlbum"
ITEM_TYPE_ARTIST: Final = "MusicArtist"
ITEM_TYPE_AUDIO: Final = "Audio"
ITEM_TYPE_LIBRARY: Final = "CollectionFolder"
ITEM_TYPE_MOVIE: Final = "Movie"

MAX_IMAGE_WIDTH: Final = 500
MAX_STREAMING_BITRATE: Final = "140000000"

MEDIA_SOURCE_KEY_PATH: Final = "Path"

MEDIA_TYPE_AUDIO: Final = "Audio"
MEDIA_TYPE_NONE: Final = ""
MEDIA_TYPE_VIDEO: Final = "Video"

SUPPORTED_COLLECTION_TYPES: Final = [COLLECTION_TYPE_MUSIC, COLLECTION_TYPE_MOVIES]

USER_APP_NAME: Final = "Home Assistant"
USER_AGENT: Final = f"Home-Assistant/{CLIENT_VERSION}"

PLATFORMS = [Platform.SENSOR]
LOGGER = logging.getLogger(__package__)


text:
Rest Sample was created to show basic REST operations using Spring MVC and MongoDB.

# Technologies used

Java 1.8

Maven 3.3.9

Spring boot 1.4.1

MongoDB 3.2

Swagger 2.6.1

# Installing and testing

Type `mvn spring-boot:run` from the root project directory to start the application;

Check the Swagger API: http://localhost:8080/swagger-ui.html

The MongoDB used was pulled on the docker official repository: https://hub.docker.com/_/mongo/

The command used to pull and run the docker image was:

``docker run --name mongo-users -d -p 27017:27017 mongo``

# URLs

To see all the endpoints created, please check it trough Swagger documentation:

Swagger: http://localhost:8080/swagger-ui.html

# Contact

Lucas Montanari (lucas_montanari@hotmail.com)


text:
var users = [];

function submit() {
    var input = document.getElementById('name');
    if(isValid(input)) {
        addUser(input);
        loadPage();
    } else {
        alert('You must inform an username');
    }
}

function addUser(input) {
    users.push(input.value.trim());
    input.value = '';
    sortUsersByName();
}

function isValid(input) {
    if(input.value) return true;
    return false;
}

function sortUsersByName() {
    users = users.sort(function(a, b) {
        return a.toLowerCase().localeCompare(b.toLowerCase());
    });
}

function loadPage() {
    clearPage();
    var list = document.getElementById('list');
    var ul = document.createElement('ul');
    list.appendChild(ul);
    for(var i=0; i<users.length; i++) {
        var item = document.createElement('li');
        item.appendChild(document.createTextNode(users[i]));
        item.setAttribute('id', 'item' + i);
        item.onclick = deleteUser;
        ul.appendChild(item);
    }
}

function deleteUser(event) {
    var item = event.target;
    if(confirm('Do you want to delete ' + item.textContent + '?')) {
        var id = item.id.slice(4);
        users.splice(id, 1);
        loadPage();
    }
}

function clearPage() {
    var list = document.getElementById('list');
    list.innerHTML = '';
}

function reset() {
    clearPage();
    users = [];
}

function init() {
    document.getElementById('submit').onclick = submit;
    document.getElementById('clear').onclick = reset;
}

window.onload = init;


text:
var dest = './dist';
var src = './src';

module.exports = {
  dest: dest,
  browserSync: {
    server: {
      // Serve up our build folder
      baseDir: dest,
    },
  },
  markup: {
    src : src + '/htdocs/**',
    dest: dest,
  },
  browserify: {
    // A separate bundle will be generated for each bundle config below
    bundleConfigs: [
      {
        entries      : 'index.js',
        dest         : dest,
        debug        : true,
        outputName   : 'interact.js',
        outputNameMin: 'interact.min.js',
        headerFile   : 'src/header.js',

        standalone   : 'interact',
        transform    : [[ 'babelify', {} ]],
        // Additional file extentions to make optional
        extensions   : [],
      },
    ],
  },
};


text:
import fs from 'fs';
import path from 'path';
import os from 'os';
import globby from 'globby';
import { list } from '@keystone-6/core';
import { text } from '@keystone-6/core/fields';
import { setupTestRunner } from '@keystone-6/api-tests/test-runner';
import { allowAll } from '@keystone-6/core/access';
import { humanize } from '../../../packages/core/src/lib/utils';
import { apiTestConfig, expectValidationError } from '../utils';

const testModules = globby.sync(`packages/**/src/**/test-fixtures.{js,ts}`, {
  absolute: true,
});
testModules
  .map(require)
  .filter(
    ({ skipRequiredTest, unSupportedAdapterList = [] }) =>
      !skipRequiredTest && !unSupportedAdapterList.includes(process.env.TEST_ADAPTER)
  )
  .forEach(mod => {
    (mod.testMatrix || ['default']).forEach((matrixValue: string) => {
      describe(`${mod.name} - ${matrixValue} - isRequired`, () => {
        beforeEach(() => {
          if (mod.beforeEach) {
            mod.beforeEach(matrixValue);
          }
        });
        afterEach(async () => {
          if (mod.afterEach) {
            await mod.afterEach(matrixValue);
          }
        });
        beforeAll(() => {
          if (mod.beforeAll) {
            mod.beforeAll(matrixValue);
          }
        });
        afterAll(async () => {
          if (mod.afterAll) {
            await mod.afterAll(matrixValue);
          }
        });

        const fieldConfig = mod.fieldConfig ? mod.fieldConfig(matrixValue) : {};

        const runner = setupTestRunner({
          config: apiTestConfig({
            lists: {
              Test: list({
                access: allowAll,
                fields: {
                  name: text(),
                  testField: mod.typeFunction({
                    ...fieldConfig,
                    validation: {
                      ...fieldConfig.validation,
                      isRequired: true,
                    },
                  }),
                },
              }),
            },
            storage: {
              test_image: {
                kind: 'local',
                type: 'image',
                storagePath: fs.mkdtempSync(path.join(os.tmpdir(), 'tmp_test_images')),
                generateUrl: path => `http://localhost:3000/images${path}`,
                serverRoute: {
                  path: '/images',
                },
              },
              test_file: {
                kind: 'local',
                type: 'file',
                storagePath: fs.mkdtempSync(path.join(os.tmpdir(), 'tmp_test_files')),
                generateUrl: path => `http://localhost:3000/files${path}`,
                serverRoute: {
                  path: '/files',
                },
              },
            },
          }),
        });

        const messages = [`Test.testField: ${humanize('testField')} is required`];

        test(
          'Create an object without the required field',
          runner(async ({ context }) => {
            const { data, errors } = await context.graphql.raw({
              query: `
                  mutation {
                    createTest(data: { name: "test entry" } ) { id }
                  }`,
            });
            expect(data).toEqual({ createTest: null });
            expectValidationError(errors, [
              {
                path: ['createTest'],
                messages:
                  mod.name === 'Text' ? ['Test.testField: Test Field must not be empty'] : messages,
              },
            ]);
          })
        );

        test(
          'Create an object with an explicit null value',
          runner(async ({ context }) => {
            const { data, errors } = await context.graphql.raw({
              query: `
                  mutation {
                    createTest(data: { name: "test entry", testField: null } ) { id }
                  }`,
            });
            expect(data).toEqual({ createTest: null });
            expectValidationError(errors, [
              {
                path: ['createTest'],
                messages,
              },
            ]);
          })
        );

        test(
          'Update an object with the required field having a null value',
          runner(async ({ context }) => {
            const data0 = await context.query.Test.createOne({
              data: {
                name: 'test entry',
                testField: mod.exampleValue(matrixValue),
              },
            });
            const { data, errors } = await context.graphql.raw({
              query: `
                  mutation {
                    updateTest(where: { id: "${data0.id}" }, data: { name: "updated test entry", testField: null } ) { id }
                  }`,
            });
            expect(data).toEqual({ updateTest: null });
            expectValidationError(errors, [
              {
                path: ['updateTest'],
                messages,
              },
            ]);
          })
        );

        test(
          'Update an object without the required field',
          runner(async ({ context }) => {
            const data0 = await context.query.Test.createOne({
              data: {
                name: 'test entry',
                testField: mod.exampleValue(matrixValue),
              },
            });
            const data = await context.query.Test.updateOne({
              where: { id: data0.id },
              data: { name: 'updated test entry' },
              query: 'id name',
            });
            expect(data).not.toBe(null);
            expect(data.name).toEqual('updated test entry');
          })
        );
      });
    });
  });


text:
__precompile__()

module FullRankModels

import LowRankModels: ConvergenceHistory, update_ch!, fit!

include("regularizers.jl")
include("gfrm.jl")
include("evaluate_fit.jl")

include("algorithms/prisma.jl")
# include("algorithms/fw_sketch.jl")
include("algorithms/fw.jl")
include("algorithms/fw_sketch_multithread.jl")
include("algorithms/fw_thin.jl")

include("utilities.jl")
include("cross_validate.jl")

end # module


text:
from django.conf import settings
from django.db.models import Q
import re
from cms.exceptions import NoHomeFound

APPEND_TO_SLUG = "-copy"
COPY_SLUG_REGEX = re.compile(r'^.*-copy(?:-(\d+)*)?$')

def is_valid_page_slug(page, parent, lang, slug, site, path=None):
    """Validates given slug depending on settings.
    """
    from cms.models import Page, Title
    # Since 3.0 this must take into account unpublished pages as it's necessary
    # to be able to open every page to edit content.
    # If page is newly created (i.e. page.pk is None) we skip filtering out
    # titles attached to the same page
    if page.pk:
        qs = Title.objects.filter(page__site=site).exclude(page=page)
    else:
        qs = Title.objects.filter(page__site=site)

    if settings.USE_I18N:
        qs = qs.filter(language=lang)

    if parent:
        if parent.is_home:
            # siblings on hoe and parentless
            qs = qs.filter(Q(page__parent=parent) |
                           Q(page__parent__isnull=True))
        else:
            # siblings on the same parent page
            qs = qs.filter(page__parent=parent)
    else:
        try:
            # siblings on home and parentless
            home = Page.objects.get_home(site)
            qs = qs.filter(Q(page__parent=home) |
                           Q(page__parent__isnull=True))
        except NoHomeFound:
            # if no home is published, check among parentless siblings only
            qs = qs.filter(page__parent__isnull=True)

    if page.pk:
        qs = qs.exclude(Q(language=lang) & Q(page=page))
        qs = qs.exclude(page__publisher_public=page)
    # Check for slugs
    if qs.filter(slug=slug).exists():
        return False
    # Check for path
    if path and qs.filter(path=path).exists():
        return False
    return True

def get_available_slug(title, new_slug=None):
    """Smart function generates slug for title if current title slug cannot be
    used. Appends APPEND_TO_SLUG to slug and checks it again.

    (Used in page copy function)

    Returns: slug
    """
    slug = new_slug or title.slug
    # We need the full path for the title to check for conflicting urls
    title.slug = slug
    title.update_path()
    path = title.path
    # This checks for conflicting slugs/overwrite_url, for both published and unpublished pages
    # This is a simpler check than in page_resolver.is_valid_url which
    # takes into account actually page URL
    if not is_valid_page_slug(title.page, title.page.parent, title.language, slug, title.page.site, path):
        # add nice copy attribute, first is -copy, then -copy-2, -copy-3, ....
        match = COPY_SLUG_REGEX.match(slug)
        if match:
            try:
                next_id = int(match.groups()[0]) + 1
                slug = "-".join(slug.split('-')[:-1]) + "-%d" % next_id
            except TypeError:
                slug += "-2"
        else:
            slug += APPEND_TO_SLUG
        return get_available_slug(title, slug)
    else:
        return slug

def check_title_slugs(page):
    """Checks page title slugs for duplicity if required, used after page move/
    cut/paste.
    """
    for title in page.title_set.all():
        old_slug, old_path = title.slug, title.path
        title.slug = get_available_slug(title)
        if title.slug != old_slug or title.path != old_path:
            title.save()


text:
module Docks
  module Tags
    class Author < Base
      def initialize
        @name = :author
        @synonyms = [:contributor]
        @multiple_allowed = true
        @multiline = false
      end

      def process(symbol)
        symbol.update(@name) do |authors|
          authors = Array(authors).map { |author| split_on_top_level_parens_commas_and_pipes(author) }.flatten
          authors.map { |author| OpenStruct.new name_and_parenthetical(author, :name, :email) }
        end
      end
    end
  end
end


text:
module Lottery
  module Europe
    include Lottery::LotteryHelper
    extend self

    def euro_millions
      make_hash(draw(50, 5), draw(11, 2))
    end

    def lotto
      make_hash(draw(49, 6))
    end

    def thunderball
      make_hash(draw(39, 5), draw(14, 1))
    end

  end
end


text:
package com.sedmelluq.discord.lavaplayer.container.mp3;

import com.sedmelluq.discord.lavaplayer.natives.mp3.Mp3Decoder;
import com.sedmelluq.discord.lavaplayer.tools.DataFormatTools;
import com.sedmelluq.discord.lavaplayer.tools.io.SeekableInputStream;
import java.io.IOException;

import static com.sedmelluq.discord.lavaplayer.natives.mp3.Mp3Decoder.MPEG1_SAMPLES_PER_FRAME;

/**
 * MP3 seeking support for constant bitrate files or in cases where the variable bitrate format used by the file is not
 * supported. In case the file is not actually CBR, this being used as a fallback may cause inaccurate seeking.
 */
public class Mp3ConstantRateSeeker implements Mp3Seeker {
  private static final int META_TAG_OFFSET = 36;
  private static final byte[][] META_TAGS = new byte[][] {
      new byte[] {'I', 'n', 'f', 'o'},
      new byte[] { 'L', 'A', 'M', 'E' }
  };

  private final double averageFrameSize;
  private final int sampleRate;
  private final long firstFramePosition;
  private final long contentLength;

  private Mp3ConstantRateSeeker(double averageFrameSize, int sampleRate, long firstFramePosition, long contentLength) {
    this.averageFrameSize = averageFrameSize;
    this.sampleRate = sampleRate;
    this.firstFramePosition = firstFramePosition;
    this.contentLength = contentLength;
  }

  /**
   * @param firstFramePosition Position of the first frame in the file
   * @param contentLength Total length of the file
   * @param frameBuffer Buffer of the first frame
   * @return Constant rate seeker, will always succeed, never null.
   */
  public static Mp3ConstantRateSeeker createFromFrame(long firstFramePosition, long contentLength, byte[] frameBuffer) {
    int sampleRate = Mp3Decoder.getFrameSampleRate(frameBuffer, 0);
    double averageFrameSize = Mp3Decoder.getAverageFrameSize(frameBuffer, 0);

    return new Mp3ConstantRateSeeker(averageFrameSize, sampleRate, firstFramePosition, contentLength);
  }

  public static boolean isMetaFrame(byte[] frameBuffer) {
    for (byte[] metaTag : META_TAGS) {
      if (DataFormatTools.arrayRangeEquals(frameBuffer, META_TAG_OFFSET, metaTag)) {
        return true;
      }
    }

    return false;
  }

  @Override
  public long getDuration() {
    return getMaximumFrameCount() * MPEG1_SAMPLES_PER_FRAME * 1000 / sampleRate;
  }

  @Override
  public boolean isSeekable() {
    return true;
  }

  @Override
  public long seekAndGetFrameIndex(long timecode, SeekableInputStream inputStream) throws IOException {
    long maximumFrameCount = getMaximumFrameCount();

    long sampleIndex = timecode * sampleRate / 1000;
    long frameIndex = Math.min(sampleIndex / MPEG1_SAMPLES_PER_FRAME, maximumFrameCount);

    long seekPosition = (long) (frameIndex * averageFrameSize) - 8;
    inputStream.seek(firstFramePosition + seekPosition);

    return frameIndex;
  }

  private long getMaximumFrameCount() {
    return (long) ((contentLength - firstFramePosition + 8) / averageFrameSize);
  }
}


text:
from django.shortcuts import render, render_to_response

def index(req):
    if req.method == 'GET':
        return render_to_response('swallow/index.html')

def article(req):
    if req.method == 'GET':
        pass


text:
#include "TwiMaster.h"

void ASFService::TwiMaster::init(const twi_options_t* opt /*= nullptr*/) {

	if(opt != nullptr) {
		config(opt);
	}

	twi_master_setup(twi->getPeripherialInstance(), &twiOptions);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://arturwin.office.itmill.com:9999/" />
<title>New Test</title>

New Test

	open
	/run/com.vaadin.tests.components.ui.InitialFragmentEvent?restartApplication#initial

	assertText
	vaadin=runcomvaadintestscomponentsuiInitialFragmentEvent::PID_SLog_row_0

	open
	/run/com.vaadin.tests.components.ui.InitialFragmentEvent#initial

	assertText
	vaadin=runcomvaadintestscomponentsuiInitialFragmentEvent::PID_SLog_row_0

	runScript
	window.location.hash='second'

	pause
	500

	waitForVaadin

	assertText
	vaadin=runcomvaadintestscomponentsuiInitialFragmentEvent::PID_SLog_row_0
	1. Fragment changed from "no event received" to second

	runScript
	window.location.hash=''

	pause
	500

	waitForVaadin

	assertText
	vaadin=runcomvaadintestscomponentsuiInitialFragmentEvent::PID_SLog_row_0
	2. Fragment changed from second to


text:
var movement = require("./movement.js")
var cam = require("./cam.js");

function presenceStart(){
  camera.start();
}
function presenceStop(){
  camera.stop();
}

var camera = new cam();
var presence = new movement(presenceStart, presenceStop);

var jsonServer = require('json-server');
// Returns an Express server
var server = jsonServer.create();
// Set default middlewares (logger, static, cors and no-cache)
server.use(jsonServer.defaults());
// Add custom routes
// server.get('/custom', function (req, res) { res.json({ msg: 'hello' }) })
// Returns an Express router
var router = jsonServer.router('db.json');
server.use(router);
server.listen(3000);

var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname+"/public/")).listen(8080);


text:
import os

class BaseSync(object):
    """
    Base class for all classes that implement the sync functionality. Sets up
    the swift client with the default configuration, which points to the local
    Swift configuration. Supplies the skeleton methods that must be overwritten
    by all child classes.
    """

    def __init__(self, status_dir, settings, per_account=False):
        """Base class that all users of the ContainerCrawler should derive from

        Arguments:
        status_dir -- directory that contains the sync status files
        settings -- sync settings; contains at least the following keys:
            account -- the Swift account that is synced
            container -- the specific container within the account
            Any other keys are provider specific.

        Keyword arguments:
        per_account -- whether the operation is happening on every container in
                       the account.
        """
        self._status_dir = status_dir
        self._account = settings['account']
        self._container = settings['container']
        if 'internal_account' in settings and 'internal_container' in settings:
            # sharded containers maybe in a hidden account that we use for
            # status file tracking
            self._status_file = os.path.join(
                self._status_dir,
                settings['internal_account'],
                settings['internal_container']).encode('utf-8')
            self._status_account_dir = os.path.join(
                self._status_dir, settings['internal_account']).encode('utf-8')
        else:
            self._status_file = os.path.join(self._status_dir, self._account,
                                             self._container).encode('utf-8')
            self._status_account_dir = os.path.join(
                self._status_dir, self._account).encode('utf-8')
        self._per_account = per_account

    def handle(self, rows, swift_client):
        raise NotImplementedError

    def get_last_processed_row(self, db_id):
        raise NotImplementedError

    def save_last_processed_row(self, row_id, db_id):
        raise NotImplementedError

    def get_last_verified_row(self, db_id):
        raise NotImplementedError

    def save_last_verified_row(self, row_id, db_id):
        raise NotImplementedError

    def handle_container_info(self, broker_info, metadata):
        # Optional to implement
        pass


text:
define(function(require) {
	var registerSuite = require('intern!object');
	var w3cTest = require('../support/w3cTest');
	var name = 'pointerevent_pointerenter_does_not_bubble-manual';

	registerSuite({
		name: name,

		main: function() {
			return w3cTest(this.remote, name + '.html')
				.findById('target0')
					.moveMouseTo(50, 25)
					.end()
				.findById('parent0')
					.moveMouseTo(0, 25)
					.end()
				.checkResults();
		}
	});
});


text:
001
017    package org.apache.commons.math3.genetics;
018
019    import java.util.ArrayList;
020    import java.util.Collection;
021    import java.util.Collections;
022    import java.util.Iterator;
023    import java.util.List;
024
025    import org.apache.commons.math3.exception.util.LocalizedFormats;
026    import org.apache.commons.math3.exception.NotPositiveException;
027    import org.apache.commons.math3.exception.NullArgumentException;
028    import org.apache.commons.math3.exception.NumberIsTooLargeException;
029    import org.apache.commons.math3.exception.NumberIsTooSmallException;
030
031    /**
032     * Population of chromosomes represented by a {@link List}.
033     *
034     * @since 2.0
035     * @version $Id: ListPopulation.java 1422195 2012-12-15 06:45:18Z psteitz $
036     */
037    public abstract class ListPopulation implements Population {
038
039        /** List of chromosomes */
040        private List<Chromosome> chromosomes;
041
042        /** maximal size of the population */
043        private int populationLimit;
044
045        /**
046         * Creates a new ListPopulation instance and initializes its inner chromosome list.
047         *
048         * @param populationLimit maximal size of the population
049         * @throws NotPositiveException if the population limit is not a positive number (&lt; 1)
050         */
051        public ListPopulation(final int populationLimit) throws NotPositiveException {
052            this(Collections.<Chromosome> emptyList(), populationLimit);
053        }
054
055        /**
056         * Creates a new ListPopulation instance.
057         * <p>
058         * Note: the chromosomes of the specified list are added to the population.
059         *
060         * @param chromosomes list of chromosomes to be added to the population
061         * @param populationLimit maximal size of the population
062         * @throws NullArgumentException if the list of chromosomes is {@code null}
063         * @throws NotPositiveException if the population limit is not a positive number (&lt; 1)
064         * @throws NumberIsTooLargeException if the list of chromosomes exceeds the population limit
065         */
066        public ListPopulation(final List<Chromosome> chromosomes, final int populationLimit)
067            throws NullArgumentException, NotPositiveException, NumberIsTooLargeException {
068
069            if (chromosomes == null) {
070                throw new NullArgumentException();
071            }
072            if (populationLimit <= 0) {
073                throw new NotPositiveException(LocalizedFormats.POPULATION_LIMIT_NOT_POSITIVE, populationLimit);
074            }
075            if (chromosomes.size() > populationLimit) {
076                throw new NumberIsTooLargeException(LocalizedFormats.LIST_OF_CHROMOSOMES_BIGGER_THAN_POPULATION_SIZE,
077                                                    chromosomes.size(), populationLimit, false);
078            }
079            this.populationLimit = populationLimit;
080            this.chromosomes = new ArrayList<Chromosome>(populationLimit);
081            this.chromosomes.addAll(chromosomes);
082        }
083
084        /**
085         * Sets the list of chromosomes.
086         * <p>
087         * Note: this method removed all existing chromosomes in the population and adds all chromosomes
088         * of the specified list to the population.
089         *
090         * @param chromosomes the list of chromosomes
091         * @throws NullArgumentException if the list of chromosomes is {@code null}
092         * @throws NumberIsTooLargeException if the list of chromosomes exceeds the population limit
093         * @deprecated use {@link #addChromosomes(Collection)} instead
094         */
095        @Deprecated
096        public void setChromosomes(final List<Chromosome> chromosomes)
097            throws NullArgumentException, NumberIsTooLargeException {
098
099            if (chromosomes == null) {
100                throw new NullArgumentException();
101            }
102            if (chromosomes.size() > populationLimit) {
103                throw new NumberIsTooLargeException(LocalizedFormats.LIST_OF_CHROMOSOMES_BIGGER_THAN_POPULATION_SIZE,
104                                                    chromosomes.size(), populationLimit, false);
105            }
106            this.chromosomes.clear();
107            this.chromosomes.addAll(chromosomes);
108        }
109
110        /**
111         * Add a {@link Collection} of chromosomes to this {@link Population}.
112         * @param chromosomeColl a {@link Collection} of chromosomes
113         * @throws NumberIsTooLargeException if the population would exceed the population limit when
114         * adding this chromosome
115         * @since 3.1
116         */
117        public void addChromosomes(final Collection<Chromosome> chromosomeColl) throws NumberIsTooLargeException {
118            if (chromosomes.size() + chromosomeColl.size() > populationLimit) {
119                throw new NumberIsTooLargeException(LocalizedFormats.LIST_OF_CHROMOSOMES_BIGGER_THAN_POPULATION_SIZE,
120                                                    chromosomes.size(), populationLimit, false);
121            }
122            this.chromosomes.addAll(chromosomeColl);
123        }
124
125        /**
126         * Returns an unmodifiable list of the chromosomes in this population.
127         * @return the unmodifiable list of chromosomes
128         */
129        public List<Chromosome> getChromosomes() {
130            return Collections.unmodifiableList(chromosomes);
131        }
132
133        /**
134         * Access the list of chromosomes.
135         * @return the list of chromosomes
136         * @since 3.1
137         */
138        protected List<Chromosome> getChromosomeList() {
139            return chromosomes;
140        }
141
142        /**
143         * Add the given chromosome to the population.
144         *
145         * @param chromosome the chromosome to add.
146         * @throws NumberIsTooLargeException if the population would exceed the {@code populationLimit} after
147         *   adding this chromosome
148         */
149        public void addChromosome(final Chromosome chromosome) throws NumberIsTooLargeException {
150            if (chromosomes.size() >= populationLimit) {
151                throw new NumberIsTooLargeException(LocalizedFormats.LIST_OF_CHROMOSOMES_BIGGER_THAN_POPULATION_SIZE,
152                                                    chromosomes.size(), populationLimit, false);
153            }
154            this.chromosomes.add(chromosome);
155        }
156
157        /**
158         * Access the fittest chromosome in this population.
159         * @return the fittest chromosome.
160         */
161        public Chromosome getFittestChromosome() {
162            // best so far
163            Chromosome bestChromosome = this.chromosomes.get(0);
164            for (Chromosome chromosome : this.chromosomes) {
165                if (chromosome.compareTo(bestChromosome) > 0) {
166                    // better chromosome found
167                    bestChromosome = chromosome;
168                }
169            }
170            return bestChromosome;
171        }
172
173        /**
174         * Access the maximum population size.
175         * @return the maximum population size.
176         */
177        public int getPopulationLimit() {
178            return this.populationLimit;
179        }
180
181        /**
182         * Sets the maximal population size.
183         * @param populationLimit maximal population size.
184         * @throws NotPositiveException if the population limit is not a positive number (&lt; 1)
185         * @throws NumberIsTooSmallException if the new population size is smaller than the current number
186         *   of chromosomes in the population
187         */
188        public void setPopulationLimit(final int populationLimit) throws NotPositiveException, NumberIsTooSmallException {
189            if (populationLimit <= 0) {
190                throw new NotPositiveException(LocalizedFormats.POPULATION_LIMIT_NOT_POSITIVE, populationLimit);
191            }
192            if (populationLimit < chromosomes.size()) {
193                throw new NumberIsTooSmallException(populationLimit, chromosomes.size(), true);
194            }
195            this.populationLimit = populationLimit;
196        }
197
198        /**
199         * Access the current population size.
200         * @return the current population size.
201         */
202        public int getPopulationSize() {
203            return this.chromosomes.size();
204        }
205
206        /**
207         * {@inheritDoc}
208         */
209        @Override
210        public String toString() {
211            return this.chromosomes.toString();
212        }
213
214        /**
215         * Returns an iterator over the unmodifiable list of chromosomes.
216         * <p>Any call to {@link Iterator#remove()} will result in a {@link UnsupportedOperationException}.</p>
217         *
218         * @return chromosome iterator
219         */
220        public Iterator<Chromosome> iterator() {
221            return getChromosomes().iterator();
222        }
223    }


text: do things with version names that look like semver


text:
package org.jiucai.appframework.base.mapper;

import org.jiucai.appframework.base.util.JsonUtil;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component("jacksonObjectMapper")
public class JacksonObjectMapper {

	private static ObjectMapper mapper;

	static {

		mapper = JsonUtil.getObjectMapper();
	}

	public ObjectMapper getMapper() {
		return mapper;
	}

}


text:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "jerryscript-port-default.h"
#include "jerryscript-port.h"
#include "jerryscript.h"

#include "jerryscript-ext/debugger.h"
#include "jerryscript-ext/handler.h"
#include "main-options.h"
#include "main-utils.h"

/**
 * Temporal buffer size.
 */
#define JERRY_BUFFER_SIZE 256u

#if defined(JERRY_EXTERNAL_CONTEXT) && (JERRY_EXTERNAL_CONTEXT == 1)
/**
 * The alloc function passed to jerry_context_create
 */
static void *
context_alloc (size_t size, void *cb_data_p)
{
  (void) cb_data_p; /* unused */
  return malloc (size);
} /* context_alloc */
#endif /* defined (JERRY_EXTERNAL_CONTEXT) && (JERRY_EXTERNAL_CONTEXT == 1) */

int
main (int argc, char **argv)
{
  union
  {
    double d;
    unsigned u;
  } now = { .d = jerry_port_get_current_time () };
  srand (now.u);

  JERRY_VLA (main_source_t, sources_p, argc);

  main_args_t arguments;
  arguments.sources_p = sources_p;

  main_parse_args (argc, argv, &arguments);

#if defined(JERRY_EXTERNAL_CONTEXT) && (JERRY_EXTERNAL_CONTEXT == 1)
  jerry_context_t *context_p = jerry_context_alloc (JERRY_GLOBAL_HEAP_SIZE * 1024, context_alloc, NULL);
  jerry_port_default_set_current_context (context_p);
#endif /* defined (JERRY_EXTERNAL_CONTEXT) && (JERRY_EXTERNAL_CONTEXT == 1) */

restart:
  main_init_engine (&arguments);
  int return_code = JERRY_STANDALONE_EXIT_CODE_FAIL;
  jerry_value_t ret_value;

  for (uint32_t source_index = 0; source_index < arguments.source_count; source_index++)
  {
    main_source_t *source_file_p = sources_p + source_index;
    const char *file_path_p = argv[source_file_p->path_index];

    if (source_file_p->type == SOURCE_MODULE)
    {
      jerry_value_t specifier =
        jerry_string ((const jerry_char_t *) file_path_p, (jerry_size_t) strlen (file_path_p), JERRY_ENCODING_UTF8);
      jerry_value_t referrer = jerry_undefined ();
      ret_value = jerry_port_module_resolve (specifier, referrer, NULL);
      jerry_value_free (referrer);
      jerry_value_free (specifier);

      if (!jerry_value_is_exception (ret_value))
      {
        if (jerry_module_state (ret_value) != JERRY_MODULE_STATE_UNLINKED)
        {
          /* A module can be evaluated only once. */
          jerry_value_free (ret_value);
          continue;
        }

        jerry_value_t link_val = jerry_module_link (ret_value, NULL, NULL);

        if (jerry_value_is_exception (link_val))
        {
          jerry_value_free (ret_value);
          ret_value = link_val;
        }
        else
        {
          jerry_value_free (link_val);

          jerry_value_t module_val = ret_value;
          ret_value = jerry_module_evaluate (module_val);
          jerry_value_free (module_val);
        }
      }

      if (jerry_value_is_exception (ret_value))
      {
        main_print_unhandled_exception (ret_value);
        goto exit;
      }

      jerry_value_free (ret_value);
      continue;
    }

    size_t source_size;
    uint8_t *source_p = jerry_port_read_source (file_path_p, &source_size);

    if (source_p == NULL)
    {
      goto exit;
    }

    switch (source_file_p->type)
    {
      case SOURCE_SNAPSHOT:
      {
        ret_value = jerry_exec_snapshot ((uint32_t *) source_p,
                                         source_size,
                                         source_file_p->snapshot_index,
                                         JERRY_SNAPSHOT_EXEC_COPY_DATA,
                                         NULL);

        jerry_port_release_source (source_p);
        break;
      }
      default:
      {
        assert (source_file_p->type == SOURCE_SCRIPT || source_file_p->type == SOURCE_MODULE);

        if (!jerry_validate_string ((jerry_char_t *) source_p, (jerry_size_t) source_size, JERRY_ENCODING_UTF8))
        {
          jerry_port_release_source (source_p);
          jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: Input must be a valid UTF-8 string.");
          goto exit;
        }

        jerry_parse_options_t parse_options;
        parse_options.options = JERRY_PARSE_HAS_SOURCE_NAME;
        parse_options.source_name =
          jerry_string ((const jerry_char_t *) file_path_p, (jerry_size_t) strlen (file_path_p), JERRY_ENCODING_UTF8);

        ret_value = jerry_parse (source_p, source_size, &parse_options);

        jerry_value_free (parse_options.source_name);
        jerry_port_release_source (source_p);

        if (!jerry_value_is_exception (ret_value) && !(arguments.option_flags & OPT_FLAG_PARSE_ONLY))
        {
          jerry_value_t func_val = ret_value;
          ret_value = jerry_run (func_val);
          jerry_value_free (func_val);
        }

        break;
      }
    }

    if (jerry_value_is_exception (ret_value))
    {
      if (main_is_value_reset (ret_value))
      {
        jerry_cleanup ();

        goto restart;
      }

      main_print_unhandled_exception (ret_value);
      goto exit;
    }

    jerry_value_free (ret_value);
  }

  if (arguments.option_flags & OPT_FLAG_WAIT_SOURCE)
  {
    while (true)
    {
      jerry_debugger_wait_for_source_status_t receive_status;
      receive_status = jerry_debugger_wait_for_client_source (main_wait_for_source_callback, NULL, &ret_value);

      if (receive_status == JERRY_DEBUGGER_SOURCE_RECEIVE_FAILED)
      {
        jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Connection aborted before source arrived.");
        goto exit;
      }

      if (receive_status == JERRY_DEBUGGER_SOURCE_END)
      {
        jerry_port_log (JERRY_LOG_LEVEL_DEBUG, "No more client source.\n");
        break;
      }

      assert (receive_status == JERRY_DEBUGGER_CONTEXT_RESET_RECEIVED
              || receive_status == JERRY_DEBUGGER_SOURCE_RECEIVED);

      if (receive_status == JERRY_DEBUGGER_CONTEXT_RESET_RECEIVED || main_is_value_reset (ret_value))
      {
        jerry_cleanup ();
        goto restart;
      }

      assert (receive_status == JERRY_DEBUGGER_SOURCE_RECEIVED);
      jerry_value_free (ret_value);
    }
  }
  else if (arguments.option_flags & OPT_FLAG_USE_STDIN)
  {
    char buffer[JERRY_BUFFER_SIZE];
    char *source_p = NULL;
    size_t source_size = 0;

    while (!feof (stdin))
    {
      size_t read_bytes = fread (buffer, 1u, JERRY_BUFFER_SIZE, stdin);

      size_t new_size = source_size + read_bytes;
      source_p = realloc (source_p, new_size);

      memcpy (source_p + source_size, buffer, read_bytes);
      source_size = new_size;
    }

    ret_value = jerry_parse ((jerry_char_t *) source_p, source_size, NULL);
    free (source_p);

    if (jerry_value_is_exception (ret_value))
    {
      main_print_unhandled_exception (ret_value);
      goto exit;
    }

    jerry_value_t func_val = ret_value;
    ret_value = jerry_run (func_val);
    jerry_value_free (func_val);

    if (jerry_value_is_exception (ret_value))
    {
      main_print_unhandled_exception (ret_value);
      goto exit;
    }

    jerry_value_free (ret_value);
  }
  else if (arguments.source_count == 0)
  {
    const char *prompt = (arguments.option_flags & OPT_FLAG_NO_PROMPT) ? "" : "jerry> ";
    char buffer[JERRY_BUFFER_SIZE];

    while (true)
    {
      printf ("%s", prompt);
      char *str_p = fgets (buffer, JERRY_BUFFER_SIZE, stdin);

      if (str_p == NULL)
      {
        printf ("\n");
        break;
      }

      size_t len = strlen (str_p);

      if (len == 0)
      {
        continue;
      }

      if (!jerry_validate_string ((jerry_char_t *) str_p, (jerry_size_t) len, JERRY_ENCODING_UTF8))
      {
        jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: Input must be a valid UTF-8 string.\n");
        continue;
      }

      ret_value = jerry_parse ((jerry_char_t *) str_p, len, NULL);

      if (jerry_value_is_exception (ret_value))
      {
        main_print_unhandled_exception (ret_value);
        continue;
      }

      jerry_value_t func_val = ret_value;
      ret_value = jerry_run (func_val);
      jerry_value_free (func_val);

      if (jerry_value_is_exception (ret_value))
      {
        main_print_unhandled_exception (ret_value);
        continue;
      }

      const jerry_value_t args[] = { ret_value };
      jerry_value_t ret_val_print = jerryx_handler_print (NULL, args, 1);
      jerry_value_free (ret_val_print);
      jerry_value_free (ret_value);
      ret_value = jerry_run_jobs ();

      if (jerry_value_is_exception (ret_value))
      {
        main_print_unhandled_exception (ret_value);
        continue;
      }

      jerry_value_free (ret_value);
    }
  }

  ret_value = jerry_run_jobs ();

  if (jerry_value_is_exception (ret_value))
  {
    main_print_unhandled_exception (ret_value);
    goto exit;
  }

  jerry_value_free (ret_value);

  if (arguments.exit_cb_name_p != NULL)
  {
    jerry_value_t global = jerry_current_realm ();
    jerry_value_t name_str = jerry_string_sz (arguments.exit_cb_name_p);
    jerry_value_t callback_fn = jerry_object_get (global, name_str);

    jerry_value_free (global);
    jerry_value_free (name_str);

    if (jerry_value_is_function (callback_fn))
    {
      ret_value = jerry_call (callback_fn, jerry_undefined (), NULL, 0);

      if (jerry_value_is_exception (ret_value))
      {
        main_print_unhandled_exception (ret_value);
        goto exit;
      }

      jerry_value_free (ret_value);
    }

    jerry_value_free (callback_fn);
  }

  return_code = JERRY_STANDALONE_EXIT_CODE_OK;

exit:
  jerry_cleanup ();

#if defined(JERRY_EXTERNAL_CONTEXT) && (JERRY_EXTERNAL_CONTEXT == 1)
  free (context_p);
#endif /* defined (JERRY_EXTERNAL_CONTEXT) && (JERRY_EXTERNAL_CONTEXT == 1) */

  return return_code;
} /* main */