text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>sparknlp_jsl.annotator.chunker.chunk_key_phrase_extraction — Spark NLP 4.0.0 documentation</title>

  <link href="../../../../static/styles/theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">
<link href="../../../../static/styles/pydata-sphinx-theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">

  <link rel="stylesheet"
    href="../../../../static/vendor/fontawesome/6.1.2/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-brands-400.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-regular-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../../../static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../../../static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../../../../static/css/custom.css" />

  <link rel="preload" as="script" href="../../../../static/scripts/pydata-sphinx-theme.js?digest=1e1de1a1873e13ef5536">

    <link rel="shortcut icon" href="../../../../static/fav.ico"/>
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="docsearch:language" content="en">

  <input type="checkbox" class="sidebar-toggle" name="__primary" id="__primary">

  <input type="checkbox" class="sidebar-toggle" name="__secondary" id="__secondary">

<form class="bd-search d-flex align-items-center" action="../../../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
  Ctrl+K
</form>

        Site Navigation

                        Getting Started

                        API Reference

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

        Site Navigation

                        Getting Started

                        API Reference

Source code for sparknlp_jsl.annotator.chunker.chunk_key_phrase_extraction

from sparknlp.common import *
from sparknlp.annotator.embeddings.bert_sentence_embeddings import BertSentenceEmbeddings

[docs]class ChunkKeyPhraseExtraction(BertSentenceEmbeddings, HasEngine):
    """
    Chunk KeyPhrase Extraction uses Bert Sentence Embeddings to determine the most relevant key phrases describing a
    text. The input to the model consists of chunk annotations and sentence or document annotation. The model compares
    the chunks against the corresponding sentences/documents and selects the chunks which are most representative of
    the broader text context (i.e. the document or the sentence they belong to). The key phrases candidates (i.e. the
    input chunks) can be generated in various ways, e.g. by NGramGenerator, TextMatcher or NerConverter. The model
    operates either at sentence (selecting the most descriptive chunks from the sentence they belong to) or at document
    level. In the latter case, the key phrases are selected to represent all the input document annotations.

    ====================== ======================
    Input Annotation types Output Annotation type
    ====================== ======================
    ``DOCUMENT, CHUNK``    ``CHUNK``
    ====================== ======================

    Parameters
    ----------

    topN
        The number of key phrases to select.
    selectMostDifferent
        Finds the topN * 2 key phrases and then selects topN of them, such as that they are the most different from
        each other
    divergence
        The divergence value determines how different from each the extracted key phrases are. Uses Maximal Marginal
        Relevance (MMR). MMR should not be used in conjunction with selectMostDifferent as they aim to achieve the same
        goal, but in different ways.
    documentLevelProcessing
        Extract key phrases from the whole document  from particular sentences which the chunks refer to.
    concatenateSentences
        Concatenate the input sentence/documentation annotations before computing their embeddings.

    Examples
    --------

    >>> documenter = sparknlp.DocumentAssembler() \
    ...     .setInputCol("text") \
    ...     .setOutputCol("document")
    ...
    >>> sentencer = sparknlp.annotators.SentenceDetector() \
    ...     .setInputCols(["document"])\
    ...     .setOutputCol("sentences")
    ...
    >>> tokenizer = sparknlp.annotators.Tokenizer() \
    ...     .setInputCols(["document"]) \
    ...     .setOutputCol("tokens") \
    ...
    >>>  embeddings = sparknlp.annotators.WordEmbeddingsModel() \
    ...     .pretrained("embeddings_clinical", "en", "clinical/models") \
    ...     .setInputCols(["document", "tokens"]) \
    ...     .setOutputCol("embeddings")
    ...
    >>> ner_tagger = MedicalNerModel() \
    ...     .pretrained("ner_jsl_slim", "en", "clinical/models") \
    ...     .setInputCols(["sentences", "tokens", "embeddings"]) \
    ...     .setOutputCol("ner_tags")
    ...
    >>> ner_converter = NerConverter()\
    ...     .setInputCols("sentences", "tokens", "ner_tags")\
    ...     .setOutputCol("ner_chunks")
    ...
    >>> key_phrase_extractor = ChunkKeyPhraseExtraction\
    ...     .pretrained()\
    ...     .setTopN(1)\
    ...     .setDocumentLevelProcessing(False)\
    ...     .setDivergence(0.4)\
    ...     .setInputCols(["sentences", "ner_chunks"])\
    ...     .setOutputCol("ner_chunk_key_phrases")
    ...
    >>> pipeline = sparknlp.base.Pipeline() \
    ...     .setStages([documenter, sentencer, tokenizer, embeddings, ner_tagger, ner_converter, key_phrase_extractor])
    ...
    >>> data = spark.createDataFrame([["Her Diabetes has become type 2 in the last year with her Diabetes.He complains of swelling in his right forearm."]]).toDF("text")
    >>> results = pipeline.fit(data).transform(data)
    >>> results\
    ...     .selectExpr("explode(ner_chunk_key_phrases) AS key_phrase")\
    ...     .selectExpr(
    ...         "key_phrase.result",
    ...         "key_phrase.metadata.entity",
    ...         "key_phrase.metadata.DocumentSimilarity",
    ...         "key_phrase.metadata.MMRScore")\
    ...     .show(truncate=False)

    +-----------------------------+------------------+-------------------+
    |result                       |DocumentSimilarity|MMRScore           |
    +-----------------------------+------------------+-------------------+
    |gestational diabetes mellitus|0.7391447825527298|0.44348688715422274|
    |28-year-old                  |0.4366776288430703|0.13577881610104517|
    |type two diabetes mellitus   |0.7323921930094919|0.085800103824974  |
    +-----------------------------+------------------+-------------------+

    """

[docs]    name = "ChunkKeyPhraseExtraction"

[docs]    topN = Param(Params._dummy(),
                 "topN",
                 "Number of key phrases to extract, ordered by their score",
                 typeConverter=TypeConverters.toInt

                 )

[docs]    def setTopN(self, value):
        """Set the number of key phrases to extract. The default value is 3.

        Parameters
        ----------
        value : integer
           Number of key phrases to extract.
        """
        return self._set(topN=value)

[docs]    divergence = Param(Params._dummy(),
                       "divergence",
                       "The divergence value determines how different from each the extracted key phrases are. "
                       "The value must be in the the interval [0, 1]. The higher the value is, "
                       "the more divergence is enforced.  The default value is 0.2.",
                       typeConverter=TypeConverters.toFloat

                       )

[docs]    def setDivergence(self, value):
        """Set the level of divergence of the extracted key phrases. The value should be in the interval [0, 1].
            This parameter should not be used if setSelectMostDifferent is true - the two parameters aim to achieve the
            same goal in different ways. The default is 0, i.e. there is no constraint on the order of key phrases
             extracted.

        Parameters
        ----------
        value : float
           Divergence value
        """
        return self._set(divergence=value)

[docs]    selectMostDifferent = Param(Params._dummy(),
                                "selectMostDifferent",
                                "Find the topN * 2 key phrases and then select topN of them, such as that they are the "
                                "most different from each other",
                                typeConverter=TypeConverters.toBoolean

                                )

[docs]    def setSelectMostDifferent(self, value):
        """Let the model return the top N key phrases which are the most different from each other. Using this paramter
        only makes sense if the divergence parameter is set to 0. The default value is 'false'

        Parameters
        ----------
        value : boolean
           whether to select the most different key phrases or not.
        """
        return self._set(selectMostDifferent=value)

[docs]    documentLevelProcessing = Param(Params._dummy(),
                                    "documentLevelProcessing",
                                    "Let the model extract key phrase at the document or at the sentence level",
                                    typeConverter=TypeConverters.toBoolean

                                    )

[docs]    def setDocumentLevelProcessing(self, value):
        """Extract key phrases from the whole document or from particular sentences which the chunks refer to.
         The default value is 'false'.

        Parameters
        ----------
        value : boolean
           Whether to extract key phrases from the whole document(all sentences).
        """
        return self._set(documentLevelProcessing=value)

[docs]    concatenateSentences = Param(Params._dummy(),
                                 "concatenateSentences",
                                 "Concatenate input sentence annotations before computing their embedding.",
                                 typeConverter=TypeConverters.toBoolean

                                 )

[docs]    def setConcatenateSentences(self, value):
        """Concatenate the input sentence/documentation annotations before computing their embeddings. This parameter
        is only used if documentLevelProcessing is true. If concatenateSentences is set to true, the model will
        concatenate the document/sentence input annotations and compute a single embedding. If it is false, the model
        will compute the embedding of each sentence separately and then average the resulting embedding vectors.
        The default value is 'false'.

        Parameters
        ----------
        value : boolean
           Whether to concatenate the input sentence/document annotations in order to compute the embedding of the
           whole document.
        """
        return self._set(concatenateSentences=value)

[docs]    dropPunctuation = Param(Params._dummy(),
                            "dropPunctuation",
                            "Remove punctuation marks from input chunks.",
                            typeConverter=TypeConverters.toBoolean

                            )

[docs]    def setDropPunctuation(self, value):
        """This parameter determines whether to remove punctuation marks from the input chunks. Chunks coming from NER
        models are not affected.
        The default value is 'true'.

        Parameters
        ----------
        value : boolean
           Whether to remove punctuation marks from input chunks.
        """
        return self._set(dropPunctuation=value)

    @keyword_only
    def __init__(self, classname="com.johnsnowlabs.nlp.embeddings.ChunkKeyPhraseExtraction", java_model=None):
        super(ChunkKeyPhraseExtraction, self).__init__(
            classname=classname,
            java_model=java_model
        )
        self._setDefault(
            dimension=768,
            batchSize=8,
            maxSentenceLength=128,
            caseSensitive=False,
            divergence=0.0,
            documentLevelProcessing=True,
            topN=3,
            selectMostDifferent=False,
            concatenateSentences=True,
            dropPunctuation=True
        )

    @staticmethod

[docs]    def pretrained(name="sbert_jsl_medium_uncased", lang="en", remote_loc="clinical/models"):
        from sparknlp_jsl.pretrained import InternalResourceDownloader
        return InternalResourceDownloader.downloadModel(ChunkKeyPhraseExtraction, name, lang, remote_loc,
                                                        j_dwn='InternalsPythonResourceDownloader')

    © Copyright 2022, John Snow Labs.

Created using Sphinx 5.3.0.


text:
(function () {
  'use strict';

  angular
    .module('meetings')
    .controller('MeetingsListController', MeetingsListController);

  MeetingsListController.$inject = ['MeetingsService'];

  function MeetingsListController(MeetingsService) {
    var vm = this;

    vm.meetings = MeetingsService.query();
  }
}());

redpajama_set_name: RedPajamaGithub


text:
var Schema = require('../model/Schema');

var UUID = require('node-uuid');
var Q = require('q');

var mongojs = require('mongojs');
var db = mongojs('test');
var usersCollection = db.collection('users');

module.exports = {
    create: function( params ){
        var deferred = Q.defer();

        var newUser = Schema.create('user');
        var newUserKeys = Object.keys(newUser);

        // Copy properties to new object if they exist in the schema
        for( var i in newUserKeys ){
            var keyName = newUserKeys[i];
            if( params[ keyName ] ){
                newUser[ keyName ] = params[ keyName ];
            }
        }

        // Check that the user doesn't already exist!
        this.find( 'username', newUser.username ).then(function( userList ){
            if( userList.length != 0 ){
                console.log('Can not create user: user already exists in db');
                deferred.reject( new Error('Username already exists in db'));
            } else {

                usersCollection.save(newUser, function(error, user){
                    if( error ){
                        deferred.reject('could not create user');
                    } else {
                        deferred.resolve(user);
                    }
                });

            }
        });

        return deferred.promise;
    },
    findByUsernameWithPassword: function( username ){
        var deferred = Q.defer();
        var criteria = { username: username };
        var projection = { _id: 0 };

        usersCollection.find( criteria, projection, function (error, usersList) {
            if (error){
                deferred.reject( new Error('error finding users: ' + error));
            } else {
                deferred.resolve(usersList);
            }
        });

        return deferred.promise;
    },
    find: function( property, value ){
        var deferred = Q.defer();

        var criteria = {};
        var projection = { _id: 0, password: 0 };

        if( property && value){
            criteria[property] = value;
        }

        usersCollection.find( criteria, projection, function (error, usersList) {
            if (error || !usersList){
                deferred.reject( new Error('error finding users: ' + error));
            } else {
                deferred.resolve(usersList);
            }
        });

        return deferred.promise;
    }/*,
    createAPIKey: function( userId){
        var deferred = Q.defer();

        console.log('User id=' + userId + ' is requesting an API key');

        this.find('_id', userId).then( function( userList){

            if( !userList || !userList.length ){
                deferred.reject('error finding user in db');
                return;
            }

            var user = userList[0];

            // Prevent the user from re-creating an API key
            if( user && user.APIKey ){
                deferred.reject('API key already created! Cannot recreate.');
                return;
            }

            // Generate new key
            var APIKey = UUID.v4({rng: UUID.nodeRNG});
            var searchQuery = {_id: user._id};
            var updateParameter = { $set: { APIKey: APIKey } };

            // Update user in DB
            usersCollection.update( searchQuery,updateParameter, {}, function(error, updateStatus){
                if( !error && updateStatus.ok && updateStatus.n == 1 ){

                    // Find the updated user and return the API key in the response
                    usersCollection.find( searchQuery, function(error, userList){
                        if(!error && userList && userList.length && userList[0].APIKey){

                            console.log('User id=' + userId + ' had an API key created at ' + (new Date()).toISOString());
                            deferred.resolve(userList[0].APIKey);
                        } else {
                            deferred.reject('Set API key but couldn\'t return it successfully.');
                        }
                    });

                } else {
                    deferred.reject( 'Could not create API key' );
                }
            });
        });

        return deferred.promise;
    }  */
};


text:
module Benchmarks.Postgres.PostgreSQLSimplePlus
(
  -- * Session
  Session,
  runSession,
  -- ** Settings
  Settings,
  Host,
  Port,
  User,
  Password,
  Database,
  PoolSize,
  -- * Action
  Action,
  runAction,
  query,
  query_,
  execute,
  execute_,
  returning,
  -- * Reexports of from "postgresql-simple"
  Pos.ToRow(..),
  Pos.FromRow(..),
  Pos.ToField(..),
  Pos.FromField(..),
  Pos.field,
  Pos.Only(..),
  Pos.fromOnly,
  Pos.sql,
)
where

import Benchmarks.Prelude
import qualified Database.PostgreSQL.Simple as Pos
import qualified Database.PostgreSQL.Simple.SqlQQ as Pos
import qualified Database.PostgreSQL.Simple.FromField as Pos
import qualified Database.PostgreSQL.Simple.ToField as Pos
import qualified Database.PostgreSQL.Simple.FromRow as Pos
import qualified Database.PostgreSQL.Simple.ToRow as Pos
import qualified Data.Pool as Poo

-- * Session
-------------------------

newtype Session m r = Session (ReaderT (Poo.Pool Pos.Connection) m r)
  deriving (Functor, Applicative, Monad, MonadIO, MonadTrans)

-- FIXME: introduce bracketing if to be used anywhere seriously.
runSession :: MonadIO m => Settings -> Session m r -> m r
runSession (host, port, user, pw, db, poolSize) (Session m) = do
  pool <- liftIO $ Poo.createPool connect disconnect stripe timeout poolSize
  r <- runReaderT m pool
  liftIO $ Poo.purgePool pool
  return r
  where
    connect = Pos.connect $ Pos.ConnectInfo host port user pw db
    disconnect c = Pos.close c
    stripe = 1
    timeout = fromIntegral 30

type Settings = (Host, Port, User, Password, Database, PoolSize)
type Host = String
type Port = Word16
type User = String
type Password = String
type Database = String
type PoolSize = Word32

-- * Action
-------------------------

-- |
-- A composition of multiple queries,
-- which will be executed on a single connection and
-- optionally as a single transaction.
--
-- 'MonadIO' instance is not provided intentionally,
-- since transactions must not produce any side effects besides
-- the database updates.
newtype Action r = Action (ReaderT Pos.Connection IO r)
  deriving (Functor, Applicative, Monad)

-- |
-- Whether to treat a composed action as a transaction.
type AsTransaction = Bool

-- FIXME: handle exceptions and rollbacks by retrying,
-- if this code is to be used anywhere seriously.
runAction :: (MonadIO m) => AsTransaction -> Action r -> Session m r
runAction asTransaction (Action m) = do
  pool <- Session ask
  liftIO $ Poo.withResource pool $ \cx ->
    (if asTransaction then Pos.withTransaction cx else id) $
      runReaderT m cx

-- ** Actions
-------------------------

query :: (Pos.ToRow a, Pos.FromRow r) => Pos.Query -> a -> Action [r]
query q a = Action $ ReaderT $ \c -> Pos.query c q a

query_ :: (Pos.FromRow r) => Pos.Query -> Action [r]
query_ q = Action $ ReaderT $ \c -> Pos.query_ c q

execute :: (Pos.ToRow a) => Pos.Query -> a -> Action ()
execute q a = Action $ ReaderT $ \c -> void $ Pos.execute c q a

execute_ :: Pos.Query -> Action ()
execute_ q = Action $ ReaderT $ \c -> void $ Pos.execute_ c q

returning :: (Pos.ToRow a, Pos.FromRow r) => Pos.Query -> [a] -> Action [r]
returning q a = Action $ ReaderT $ \c -> Pos.returning c q a


text:
TOPDIR = ../../..

BOARD	= DISCOVERY_F4

USE_STM_PERIF_LIB = 1
#USE_USB = 1
#RTOS = FreeRTOS
START_FROM_RAM = 1

TARGET		= target
OPTIMIZE	= -O2

#PROJECT_SRC = src
#PROJECT_SRC = src
#PROJECT_INCLUDES = $(TOPDIR)/Libraries/STM32_USB_Device_Library/Class/hid/inc
PROJECT_FLAGS = -ggdb
PROJECT_LDFLAGS = -nostartfiles -nostdlib
#PROJECT_CWARNINGS =
#PROJECT_CXXWARNINGS =

#VPATH += $(TOPDIR)/Libraries/STM32_USB_Device_Library/Class/hid/src
#SRCS += usb_dcd_int.c usb_dcd.c usbd_core.c usbd_req.c usbd_ioreq.c usbd_hid_core.c

include $(TOPDIR)/Makefile.common


text:
layout: post
title: "Bug Reopening on Firefox for Android (Before and After the New Process) [DRAFT]"
date: 2013-09-12 16:16
comments: true
categories: phd
---

In early 2011, the Mozilla Foundation [adopted a faster release process](http://arstechnica.com/information-technology/2011/03/mozilla-outlines-16-week-firefox-development-cycle/), dubbed *train model*, with new releases every 6 weeks. It wasn't until the following year, though, that Firefox for Android jumped on the bandwagon. Due to the need to rebuild the user interface, they decided to hold the switch to the train model until June, 2012. Before that, they only shipped a new version when it met quality and performance criteria -- even if this meant missing the next train/release date.

How the process change affected Firefox for Android's quality? I've computed some quality metrics (specifically metrics related to bug reopening) on its bug reports before and after the switch to the train model to try to answer this question.

We estimated that the process change occured near June 26th, 2012, when [Firefox for Android 14 was released](https://wiki.mozilla.org/Releases/Old/2012). We classified bug reports based on whether they were created before or after the date.

<!-- TODO: recompute metrics -->

Here's the computed metrics:
<!--
 **Metric**                           | **Before** | **After**
                                      |            |
 Number of issues                     | 2449       | 7192
 Days                                 | 1257       | 468
 % verifications by test team         | 79%        | 55%
 % of bugs reopened after FIXED       | 11%        | 5%
 % of bugs reopened after VERIFIED    | 4%         | 1%
 Days btw FIXED and REOPENED (avg)    | 14         | 11
 Days btw VERIFIED and REOPENED (avg) | 28         | 18
 % of time fixing bugs                | 92%        | 94%
 % of time bugs are latent            | 4.5%       | 2.2%
 -->

 **Metric**                           | **Before** | **After**
--------------------------------------|------------|----------
 Number of issues                     | 5005       | 4636
 % verifications by test team         | 56%        | 38%
 % of bugs reopened after FIXED       | 9%         | 4%
 % of bugs reopened after VERIFIED    | 3.5%       | 1.5%
 Days btw FIXED and REOPENED (avg)    | 12         | 14
 Days btw VERIFIED and REOPENED (avg) | 24         | 18
 % of time fixing bugs                | 92%        | 94%
 % of time bugs are latent            | 4.5%       | 2.2%

To interpret the results, it is useful to know a little bit about the [Mozilla release process](http://mozilla.github.io/process-releases/) and [how it is reflected in bug reports](/blog/2013/09/08/mozilla-process/). For instance, keep in mind that when a bug is marked `FIXED`, its patch has undergone peer review and automated testing; when it is marked `VERIFIED`, it has additionally undergone manual integration testing.

From the table, we can see that the number of bugs reports that are reopened after being fixed dropped by more than half in the rapid release process (**TODO: why?**). The same can be said about the proportion of bugs that are reopened after being manually tested. <!-- A more dramatic change can be observed within bugs that were manually tested: now they are reopened 4x less often. -->

After a bug is considered fixed, the time it takes for people to notice that it should be reopened is called latent time. With the new process, the average latent time has increased a little, from 12 to 14 days. If we consider the lifetime of all bug reports over the two periods analyzed, 3.5% of the time used to be spent thinking that a bug was fixed when it was actually latent; now, this time was reduced to 2.5%.

A curious fact from the table regards the test team, automatically identified as the group of people whose work is specialized in manual testing (which appears in bug reports as the `VERIFIED` status). The test team used to be responsible for about 56% of the verifications; now the verification effort seems more evenly distributed, as the test team only performs 38% of the verifications. (**TODO: why?**)

## See also

* [Bringing Android Native Firefox to Beta](https://blog.mozilla.org/futurereleases/2012/01/25/bringing-android-native-firefox-to-beta/)
* [Firefox for mobile – tracking progress](http://irinasandu.com/2012/03/12/firefox-for-mobile-tracking-progress/)


text:
#ifndef CXXLAPACK_INTERFACE_GTSV_H
#define CXXLAPACK_INTERFACE_GTSV_H 1

#include <cxxstd/complex.h>

namespace cxxlapack {

template <typename IndexType>
    IndexType
    gtsv(IndexType             n,
         IndexType             nRhs,
         float                 *dl,
         float                 *d,
         float                 *du,
         float                 *B,
         IndexType             ldB);

template <typename IndexType>
    IndexType
    gtsv(IndexType             n,
         IndexType             nRhs,
         double                *dl,
         double                *d,
         double                *du,
         double                *B,
         IndexType             ldB);

template <typename IndexType>
    IndexType
    gtsv(IndexType             n,
         IndexType             nRhs,
         std::complex<float >  *dl,
         std::complex<float >  *d,
         std::complex<float >  *du,
         std::complex<float >  *B,
         IndexType             ldB);

template <typename IndexType>
    IndexType
    gtsv(IndexType             n,
         IndexType             nRhs,
         std::complex<double>  *dl,
         std::complex<double>  *d,
         std::complex<double>  *du,
         std::complex<double>  *B,
         IndexType             ldB);

} // namespace cxxlapack

#endif // CXXLAPACK_INTERFACE_GTSV_H


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ReactiveDomain.Foundation;
using ReactiveDomain.Testing;
using ReactiveDomain.Messaging;
using Xunit;

namespace ReactiveDomain.Testing.EventStore
{

    public class StreamStoreSubscriptionTests : IClassFixture<StreamStoreConnectionFixture>
    {
        private readonly List<IStreamStoreConnection> _stores = new List<IStreamStoreConnection>();
        private readonly IStreamNameBuilder _streamNameBuilder;
        private readonly IEventSerializer _serializer = new JsonMessageSerializer();
        private readonly string _streamName;
        private readonly UserCredentials _admin;
        private const long True = 1;
        private const long False = 0;

        public StreamStoreSubscriptionTests(StreamStoreConnectionFixture fixture)
        {
            _admin = fixture.AdminCredentials;
            _streamNameBuilder = new PrefixedCamelCaseStreamNameBuilder("UnitTest");
#if !NETCOREAPP2_0 && !NETSTANDARD2_0 && !NET452
            var mockStreamStore = new MockStreamStoreConnection(nameof(MockStreamStoreConnection));
            mockStreamStore.Connect();
            _stores.Add(mockStreamStore);
#endif
            fixture.Connection.Connect();
            _stores.Add(fixture.Connection);

            _streamName = _streamNameBuilder.GenerateForAggregate(typeof(TestAggregate), Guid.NewGuid());
            var eventCount = 10;
            foreach (var store in _stores)
            {
                AppendEvents(eventCount, store, _streamName);
            }

        }
        private void AppendEvents(int numEventsToBeSent, IStreamStoreConnection conn, string streamName, int startNumber = 0)
        {
            for (int evtNumber = startNumber; evtNumber < numEventsToBeSent + startNumber; evtNumber++)
            {
                var evt = new SubscriptionTestEvent(evtNumber);
                conn.AppendToStream(streamName, ExpectedVersion.Any, null, _serializer.Serialize(evt));
            }
        }
        private void AppendEventsForAll(int numEventsToBeSent, IStreamStoreConnection conn, string streamName, int startNumber = 0)
        {
            for (int evtNumber = startNumber; evtNumber < numEventsToBeSent + startNumber; evtNumber++)
            {
                var evt = new AllSubscriptionTestEvent(evtNumber);
                conn.AppendToStream(streamName, ExpectedVersion.Any, null, _serializer.Serialize(evt));
            }
        }

        [Fact]
        public void can_subscribe_to_stream()
        {

            foreach (var conn in _stores)
            {

                var dropped = False;
                long evtCount = 0;
                long evtNumber = 0;
                var sub = conn.SubscribeToStream(
                                        _streamName,
                                        evt =>
                                        {
                                            var subEvent = (SubscriptionTestEvent)_serializer.Deserialize(evt);
                                            Interlocked.Increment(ref evtCount);
                                            Interlocked.Exchange(ref evtNumber, subEvent.MessageNumber);
                                        },
                                        (reason, ex) => Interlocked.Exchange(ref dropped, True));

                Assert.Equal(0, evtCount);
                Assert.Equal(0, evtNumber);

                AppendEvents(1, conn, _streamName, 11);

                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtCount) == 1);
                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtNumber) == 11);
                AppendEvents(5, conn, _streamName, 12);

                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtCount) == 6);
                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtNumber) == 16);

                sub.Dispose();
                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref dropped) == True, msg: "Failed to handle drop");
            }
        }

        [Fact]
        public void can_subscribe_to_stream_from()
        {

            var streamName = _streamNameBuilder.GenerateForAggregate(typeof(TestAggregate), Guid.NewGuid());

            foreach (var conn in _stores)
            {
                AppendEvents(5, conn, streamName);

                long evtCount = 0;
                var dropped = false;
                var liveProcessingStarted = false;

                var sub = conn.SubscribeToStreamFrom(
                                            streamName,
                                            2,//after the third event of 5
                                            CatchUpSubscriptionSettings.Default,
                                            // ReSharper disable once AccessToModifiedClosure
                                            evt => Interlocked.Increment(ref evtCount),
                                            _ => liveProcessingStarted = true,
                                            (reason, ex) => dropped = true);

                AssertEx.IsOrBecomesTrue(() => liveProcessingStarted, 2000, msg: "Failed handle live processing start");
                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtCount) == 2, 5000, msg: $"Expected 2 Events got { Interlocked.Read(ref evtCount)}");
                Task.Run(() => AppendEvents(5, conn, streamName));
                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtCount) == 7, 5000, msg: $"Expected 7 Events got { Interlocked.Read(ref evtCount)}");
                AppendEvents(5, conn, streamName);
                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtCount) == 12, 5000, msg: $"Expected 12 Events got { Interlocked.Read(ref evtCount)}");
                sub.Dispose();
                AssertEx.IsOrBecomesTrue(() => dropped, msg: "Failed to handle drop");
            }
        }

        [Fact]
        public void can_subscribe_to_all()
        {

            var streams = new List<string>
            {
                _streamNameBuilder.GenerateForAggregate(typeof(TestAggregate), Guid.NewGuid()),
                _streamNameBuilder.GenerateForAggregate(typeof(TestWoftamAggregate), Guid.NewGuid())
            };

            foreach (var conn in _stores)
            {
                //TODO: The Mock event store all stream implementation is fundamentally broken see issue #42
                if (conn is MockStreamStoreConnection)
                    continue;

                long evtCount = 0;
                var dropped = false;

                //first event in a stream is copied to the $streams projection in the in-Memory ES
                //the Mock ES does not support this projection
                foreach (var stream in streams)
                {
                    var evt = new StreamCreatedTestEvent();
                    conn.AppendToStream(stream, ExpectedVersion.Any, null, _serializer.Serialize(evt));
                }

                var events = new ConcurrentDictionary<string, int>();
                var sub = conn.SubscribeToAll(
                                        evt =>
                                        {
                                            if (events.ContainsKey(evt.EventType))
                                                events[evt.EventType] += 1;
                                            else
                                                events.TryAdd(evt.EventType, 1);

                                            if (string.Compare(evt.EventType, nameof(AllSubscriptionTestEvent), StringComparison.OrdinalIgnoreCase) == 0)
                                            {
                                                Interlocked.Increment(ref evtCount);
                                            }
                                        },
                                        (reason, ex) => dropped = true,
                                        _admin);

                foreach (var stream in streams)
                {
                    AppendEventsForAll(5, conn, stream);
                }
                foreach (var stream in streams)
                {
                    conn.TryConfirmStream(stream, 5);
                }
                Assert.False(dropped);
                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtCount) == 30,
                    2000,
                    $"evtCount: Expected {30}, Actual {Interlocked.Read(ref evtCount)} ");

                sub.Dispose();
                AssertEx.IsOrBecomesTrue(() => dropped, msg: "Failed to handle drop");
            }
        }
        [Fact]
        public void can_subscribe_to_event_type_stream()
        {

            var streamTypeName = _streamNameBuilder.GenerateForEventType(typeof(SubscriptionTestEvent).Name);
            var streams = new List<string>
            {
                _streamNameBuilder.GenerateForAggregate(typeof(TestAggregate), Guid.NewGuid()),
                _streamNameBuilder.GenerateForAggregate(typeof(TestAggregate), Guid.NewGuid())
            };

            foreach (var conn in _stores)
            {
                long evtCount = 0;
                var dropped = false;

                var sub = conn.SubscribeToStream(
                                    streamTypeName,
                                    // ReSharper disable once AccessToModifiedClosure
                                    evt => Interlocked.Increment(ref evtCount),
                                    (reason, ex) => dropped = true,
                                    _admin);

                foreach (var stream in streams)
                {
                    AppendEvents(5, conn, stream);
                }
                foreach (var stream in streams)
                {
                    conn.TryConfirmStream(stream, 5);
                }
                Assert.False(dropped);
                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtCount) >= 10, 2000, $"Expected 10 got {Interlocked.Read(ref evtCount)}");
                sub.Dispose();
                AssertEx.IsOrBecomesTrue(() => dropped, msg: "Failed to handle drop");
            }
        }
        public class STestCategoryAggregate : EventDrivenStateMachine { }
        [Fact]
        public void can_subscribe_to_category_stream()
        {
            var streamTypeName = _streamNameBuilder.GenerateForCategory(typeof(STestCategoryAggregate));
            var streams = new[]
            {
                _streamNameBuilder.GenerateForAggregate(typeof(STestCategoryAggregate), Guid.NewGuid()),
                _streamNameBuilder.GenerateForAggregate(typeof(STestCategoryAggregate), Guid.NewGuid())
            };

            foreach (var conn in _stores)
            {
                long evtCount = 0;
                var dropped = false;
                foreach (var stream in streams)
                {
                    AppendEvents(1, conn, stream);
                }

                Assert.True(conn.TryConfirmStream(streamTypeName, 2), "Stream not ready.");
                var sub = conn.SubscribeToStream(
                    streamTypeName,
                    // ReSharper disable once AccessToModifiedClosure
                    evt => Interlocked.Increment(ref evtCount),
                    (reason, ex) => dropped = true,
                    _admin);
                AppendEvents(5, conn, streams[0]);
                AppendEvents(5, conn, streams[1]);
                Assert.True(conn.TryConfirmStream(streamTypeName, 12), "Stream not ready.");
                AssertEx.IsOrBecomesTrue(() => Interlocked.Read(ref evtCount) == 10, 2000,
                    $"Expected 10 got {Interlocked.Read(ref evtCount)} on {conn.ConnectionName}");
                sub.Dispose();
                AssertEx.IsOrBecomesTrue(() => dropped, msg: "Failed to handle drop");
            }
        }

        public class StreamCreatedTestEvent : IMessage
        {
            public Guid MsgId { get; private set; }
            public StreamCreatedTestEvent()
            {
                MsgId = Guid.NewGuid();
            }
        }
        public class SubscriptionTestEvent : IMessage
        {
            public Guid MsgId { get; private set; }
            public readonly int MessageNumber;
            public SubscriptionTestEvent(
                int messageNumber)
            {
                MsgId = Guid.NewGuid();
                MessageNumber = messageNumber;
            }
        }
        public class AllSubscriptionTestEvent : IMessage
        {
            public Guid MsgId { get; private set; }
            public readonly int MessageNumber;
            public AllSubscriptionTestEvent(
                int messageNumber)
            {
                MsgId = Guid.NewGuid();
                MessageNumber = messageNumber;
            }
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<title>Acts 1 (WEB)</title>
<link href="../../../build/mobile.css" rel="stylesheet" />

World English BibleActs 1<
=
>

The Acts of the Apostles

1

1 The first book I wrote, Theophilus, concerned all that Jesus began both to do and to teach,
2 until the day in which he was received up, after he had given commandment through the Holy Spirit to the apostles whom he had chosen.
3 To these he also showed himself alive after he suffered, by many proofs, appearing to them over a period of forty days, and speaking about God's Kingdom.
4 Being assembled together with them, he commanded them, "Don't depart from Jerusalem, but wait for the promise of the Father, which you heard from me.
5  For John indeed baptized in water, but you will be baptized in the Holy Spirit not many days from now."

6 Therefore when they had come together, they asked him, "Lord, are you now restoring the kingdom to Israel?"

7 He said to them, "It isn't for you to know times or seasons which the Father has set within his own authority.
8  But you will receive power when the Holy Spirit has come upon you. You will be witnesses to me in Jerusalem, in all Judea and Samaria, and to the uttermost parts of the earth."

9 When he had said these things, as they were looking, he was taken up, and a cloud received him out of their sight.
10 While they were looking steadfastly into the sky as he went, behold,+ two men stood by them in white clothing,
11 who also said, "You men of Galilee, why do you stand looking into the sky? This Jesus, who was received up from you into the sky, will come back in the same way as you saw him going into the sky."

12 Then they returned to Jerusalem from the mountain called Olivet, which is near Jerusalem, a Sabbath day's journey away.
13 When they had come in, they went up into the upper room, where they were staying; that is Peter, John, James, Andrew, Philip, Thomas, Bartholomew, Matthew, James the son of Alphaeus, Simon the Zealot, and Judas the son of James.
14 All these with one accord continued steadfastly in prayer and supplication, along with the women, and Mary the mother of Jesus, and with his brothers.

15 In these days, Peter stood up in the middle of the disciples (and the number of names was about one hundred twenty), and said,
16 "Brothers, it was necessary that this Scripture should be fulfilled, which the Holy Spirit spoke before by the mouth of David concerning Judas, who was guide to those who took Jesus.
17 For he was counted with us, and received his portion in this ministry.
18 Now this man obtained a field with the reward for his wickedness, and falling headlong, his body burst open, and all his intestines gushed out.
19 It became known to everyone who lived in Jerusalem that in their language that field was called 'Akeldama,' that is, 'The field of blood.'
20 For it is written in the book of Psalms,

'Let his habitation be made desolate.

Let no one dwell therein;'+Psalm 69:25

and,

'Let another take his office.'+Psalm 109:8

21 "Of the men therefore who have accompanied us all the time that the Lord Jesus went in and out among us,
22 beginning from the baptism of John, to the day that he was received up from us, of these one must become a witness with us of his resurrection."

23 They put forward two, Joseph called Barsabbas, who was also called Justus, and Matthias.
24 They prayed, and said, "You, Lord, who know the hearts of all men, show which one of these two you have chosen
25 to take part in this ministry and apostleship from which Judas fell away, that he might go to his own place."
26 They drew lots for them, and the lot fell on Matthias, and he was counted with the eleven apostles.

+1:10"Behold", from "ἰδοὺ", means look at, take notice, observe, see, or gaze at. It is often used as an interjection.

<
=
>


text:
"""
Free clinical metadata relating to NGS experiments from Excel documents
"""

__title__            = 'WSTSFU'
__version__         = '0.1.1'
__description__     = 'WorkSheet To Something Fucking Useful'
__author__          = 'Mitchell Stanton-Cook'
__author_email__    = 'm.stantoncook@gmail.com'
__url__             = 'http://github.com/mscook/WSTSFU'
__licence__         = 'ECL 2.0'

import sys
import os
import traceback
import argparse
import envoy
import json

epi = ("Licence: " + __licence__ + " by "+__author__
       + " <" + __author_email__ + ">")

def to_CSV_to_JSON(file_path):
    """
    Convert the xls/xlsx file to a csv then to a json

    Returns the fullpath to the JSON file
    """
    r = envoy.run('in2csv ' + file_path)
    csv = r.std_out
    csv_file = file_path+'.csv'
    with open(csv_file, 'w') as fout:
        for line in csv:
            fout.write(line)
    json_file = file_path+'.json'
    r = envoy.run('csvjson ' + csv_file)
    json = r.std_out
    with open(json_file, 'w') as fout:
        for line in json:
            fout.write(line)
    return json_file

def manipulate_JSON(file_path, strainID_header, exclude):
    """
    Manipulate the JSON file
    """
    with open(file_path) as fin:
        data = json.loads(fin.readline())
    print "Have metadata on %i strains \n" % (len(data))
    for ele in data:
        ele['StrainID'] = ele[strainID_header]
        del ele[strainID_header]
    if exclude is not None:
        exclude_list = exclude.split()
        for ele in data:
            for e in exclude_list:
                del ele[e]
        with open(file_path, 'w') as fout:
            json.dump(data, fout)
    keys = data[0].keys()
    print "JSON Schema:"
    sep1 = '+-----------------------------+-----------------------------+'
    sep2 = '+=============================+=============================+'
    header = '| Key                         | Value (type)                |'
    print sep1+'\n'+header+'\n'+sep2
    for i, key in enumerate(keys):
        tmp = len(key)
        if i != 0:
            print sep1
        print "| "+key+(30-tmp-2)*' '+'| string or None'+14*' '+'|'
    print sep1+'\n'
    print "Please find your JSON file at: %s" % (file_path)

def core(args):
    """
    The core function
    """
    args.file = os.path.expanduser(args.file)
    if not os.path.isfile(args.file):
        print "Input file does not exit"
        sys.exit(1)
    else:
        json_path = to_CSV_to_JSON(args.file)
        manipulate_JSON(json_path, args.strainID_header, args.exclude)
    sys.exit(0)

if __name__ == '__main__':
    try:
        desc = __doc__.strip()
        parser = argparse.ArgumentParser(description=desc, epilog=epi)
        parser.add_argument('--version', action='version',
                            version='%(prog)s ' + __version__)
        parser.add_argument('-e', '--exclude', action='store',
                            help='Exclude these headers')
        parser.add_argument('-b', '--banzai', action='store_true',
                            default=False,
                            help=('Generate a pre_analystics file for '
                            'Banzai'))
        parser.add_argument('-s', '--seqID_header', action='store',
                            type=str, help=('The header containing the '
                            'sequencingID [required with -b]'))
        parser.add_argument('file', action='store', type=str,
                            help='Full path to the metadata file')
        parser.add_argument('strainID_header',  action='store', type=str,
                            help='The header containing the StrainID')
        parser.set_defaults(func=core)
        args = parser.parse_args()
        args.func(args)
        sys.exit(0)
    except KeyboardInterrupt, e: # Ctrl-C
        raise e
    except SystemExit, e: # sys.exit()
        raise e
    except Exception, e:
        print 'ERROR, UNEXPECTED EXCEPTION'
        print str(e)
        traceback.print_exc()
        os._exit(1)


text:
{
  if (supportsEventConstructors)
    return new OriginalEvent(type, unwrapOptions(options));
  var event = unwrap(document.createEvent(name));
  var defaultDict = defaultInitDicts[name];
  var args = [type];
  Object.keys(defaultDict).forEach(function(key) {
    var v = options != null && key in options ? options[key] : defaultDict[key];
    if (key === "relatedTarget") v = unwrap(v);
    args.push(v);
  });
  event["init" + name].apply(event, args);
  return event;
}


text:
* patches
    * Updating Tests. All are passing.


text:
Imports M_OrderLibrary

Public Class DettStatOrdini
    Inherits System.Windows.Forms.Form
    Friend WithEvents Label1 As System.Windows.Forms.Label

    Protected DettagliStatOrdine As New LibStatsOrdini

#If Not CONFIG = "Desktop" Then
    Friend WithEvents InputPanel1 As New Microsoft.WindowsCE.Forms.InputPanel

#End If
    Friend WithEvents Tpriga As System.Windows.Forms.ColumnHeader
    Protected dtLista As DataTable

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        MyBase.Dispose(disposing)
    End Sub

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    Friend WithEvents DataGridTableStyle1 As System.Windows.Forms.DataGridTableStyle
    Friend WithEvents DataGridTextBoxColumn1 As System.Windows.Forms.DataGridTextBoxColumn
    Friend WithEvents DataGridTextBoxColumn2 As System.Windows.Forms.DataGridTextBoxColumn
    Friend WithEvents DataGridTextBoxColumn3 As System.Windows.Forms.DataGridTextBoxColumn
    Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
    Friend WithEvents CodArt As System.Windows.Forms.ColumnHeader
    Friend WithEvents DescrArt As System.Windows.Forms.ColumnHeader
    Friend WithEvents Qta As System.Windows.Forms.ColumnHeader
    Friend WithEvents Importo As System.Windows.Forms.ColumnHeader
    Friend WithEvents ListaArticoli As System.Windows.Forms.ListView
    Friend WithEvents LbCliente As System.Windows.Forms.Label
    Friend WithEvents LbDataOrdine As System.Windows.Forms.Label
    Friend WithEvents Label3 As System.Windows.Forms.Label
    Friend WithEvents Label4 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents TxtTotale As System.Windows.Forms.Label
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.DataGridTableStyle1 = New System.Windows.Forms.DataGridTableStyle
        Me.DataGridTextBoxColumn1 = New System.Windows.Forms.DataGridTextBoxColumn
        Me.DataGridTextBoxColumn2 = New System.Windows.Forms.DataGridTextBoxColumn
        Me.DataGridTextBoxColumn3 = New System.Windows.Forms.DataGridTextBoxColumn
        Me.Label1 = New System.Windows.Forms.Label
        Me.MainMenu1 = New System.Windows.Forms.MainMenu
        Me.CodArt = New System.Windows.Forms.ColumnHeader
        Me.DescrArt = New System.Windows.Forms.ColumnHeader
        Me.Qta = New System.Windows.Forms.ColumnHeader
        Me.Importo = New System.Windows.Forms.ColumnHeader
        Me.ListaArticoli = New System.Windows.Forms.ListView
        Me.Tpriga = New System.Windows.Forms.ColumnHeader
        Me.LbCliente = New System.Windows.Forms.Label
        Me.LbDataOrdine = New System.Windows.Forms.Label
        Me.Label3 = New System.Windows.Forms.Label
        Me.Label4 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.TxtTotale = New System.Windows.Forms.Label

        Me.SuspendLayout()
        '
        'DataGridTableStyle1
        '
        Me.DataGridTableStyle1.GridColumnStyles.Add(Me.DataGridTextBoxColumn1)
        Me.DataGridTableStyle1.GridColumnStyles.Add(Me.DataGridTextBoxColumn2)
        Me.DataGridTableStyle1.GridColumnStyles.Add(Me.DataGridTextBoxColumn3)
        '
        'DataGridTextBoxColumn1
        '
        Me.DataGridTextBoxColumn1.Format = ""
        Me.DataGridTextBoxColumn1.FormatInfo = Nothing
        Me.DataGridTextBoxColumn1.HeaderText = "Articolo"
        Me.DataGridTextBoxColumn1.MappingName = "PECAR"
        '
        'DataGridTextBoxColumn2
        '
        Me.DataGridTextBoxColumn2.Format = ""
        Me.DataGridTextBoxColumn2.FormatInfo = Nothing
        Me.DataGridTextBoxColumn2.HeaderText = "Quantità"
        Me.DataGridTextBoxColumn2.MappingName = "PEQTO"
        '
        'DataGridTextBoxColumn3
        '
        Me.DataGridTextBoxColumn3.Format = ""
        Me.DataGridTextBoxColumn3.FormatInfo = Nothing
        Me.DataGridTextBoxColumn3.HeaderText = "Importo"
        Me.DataGridTextBoxColumn3.MappingName = "PEIMO"
        '
        'Label1
        '
        Me.Label1.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.Label1.Font = New System.Drawing.Font("Tahoma", 8.0!, System.Drawing.FontStyle.Bold)
        Me.Label1.Location = New System.Drawing.Point(8, 248)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(128, 20)
        Me.Label1.Text = "Totale dell'ordine:"
        '
        'CodArt
        '
        Me.CodArt.Text = "Codice"
        Me.CodArt.Width = 70
        '
        'DescrArt
        '
        Me.DescrArt.Text = "Descrizione"
        Me.DescrArt.Width = 120
        '
        'Qta
        '
        Me.Qta.Text = "Qta"
        Me.Qta.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
        Me.Qta.Width = 70
        '
        'Importo
        '
        Me.Importo.Text = "Importo"
        Me.Importo.TextAlign = System.Windows.Forms.HorizontalAlignment.Right
        Me.Importo.Width = 80
        '
        'ListaArticoli
        '
        Me.ListaArticoli.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.ListaArticoli.Columns.Add(Me.CodArt)
        Me.ListaArticoli.Columns.Add(Me.DescrArt)
        Me.ListaArticoli.Columns.Add(Me.Qta)
        Me.ListaArticoli.Columns.Add(Me.Importo)
        Me.ListaArticoli.Columns.Add(Me.Tpriga)
        Me.ListaArticoli.FullRowSelect = True
        Me.ListaArticoli.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable
        Me.ListaArticoli.Location = New System.Drawing.Point(0, 67)
        Me.ListaArticoli.Name = "ListaArticoli"
        Me.ListaArticoli.Size = New System.Drawing.Size(240, 178)
        Me.ListaArticoli.TabIndex = 6
        Me.ListaArticoli.View = System.Windows.Forms.View.Details
        '
        'Tpriga
        '
        Me.Tpriga.Text = "T.Riga"
        Me.Tpriga.Width = 40
        '
        'LbCliente
        '
        Me.LbCliente.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular)
        Me.LbCliente.Location = New System.Drawing.Point(8, 16)
        Me.LbCliente.Name = "LbCliente"
        Me.LbCliente.Size = New System.Drawing.Size(224, 16)
        '
        'LbDataOrdine
        '
        Me.LbDataOrdine.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular)
        Me.LbDataOrdine.ForeColor = System.Drawing.Color.Black
        Me.LbDataOrdine.Location = New System.Drawing.Point(110, 32)
        Me.LbDataOrdine.Name = "LbDataOrdine"
        Me.LbDataOrdine.Size = New System.Drawing.Size(122, 16)
        '
        'Label3
        '
        Me.Label3.Font = New System.Drawing.Font("Tahoma", 8.0!, System.Drawing.FontStyle.Bold)
        Me.Label3.ForeColor = System.Drawing.Color.Brown
        Me.Label3.Location = New System.Drawing.Point(8, 32)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(96, 16)
        Me.Label3.Text = "Data dell'ordine"
        '
        'Label4
        '
        Me.Label4.Font = New System.Drawing.Font("Tahoma", 8.0!, System.Drawing.FontStyle.Bold)
        Me.Label4.ForeColor = System.Drawing.Color.Brown
        Me.Label4.Location = New System.Drawing.Point(8, 48)
        Me.Label4.Name = "Label4"
        Me.Label4.Size = New System.Drawing.Size(152, 16)
        Me.Label4.Text = "Elenco degli Articoli"
        '
        'Label2
        '
        Me.Label2.Font = New System.Drawing.Font("Tahoma", 8.0!, System.Drawing.FontStyle.Bold)
        Me.Label2.ForeColor = System.Drawing.Color.Brown
        Me.Label2.Location = New System.Drawing.Point(8, 0)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(100, 16)
        Me.Label2.Text = "Cliente"
        '
        'TxtTotale
        '
        Me.TxtTotale.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
        Me.TxtTotale.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular)
        Me.TxtTotale.Location = New System.Drawing.Point(122, 248)
        Me.TxtTotale.Name = "TxtTotale"
        Me.TxtTotale.Size = New System.Drawing.Size(110, 20)
        '
        'DettStatOrdini
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(96.0!, 96.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi
        Me.AutoScroll = True
        Me.ClientSize = New System.Drawing.Size(240, 270)
        Me.Controls.Add(Me.TxtTotale)
        Me.Controls.Add(Me.Label4)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.LbCliente)
        Me.Controls.Add(Me.ListaArticoli)
        Me.Controls.Add(Me.LbDataOrdine)
        Me.Menu = Me.MainMenu1
        Me.MinimizeBox = False
        Me.Name = "DettStatOrdini"
        Me.Text = "Dettaglio Statistiche"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub DettStatOrdini_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Aspetto
        LibSize.SetAutoscale(Me)

        Me.LbDataOrdine.Text = DettagliStatOrdine.NormalizeDate(StatOrdini.DataOrdine)
        Me.LbCliente.Text = StatOrdini.DescrizioneCliente

        dtLista = DettagliStatOrdine.GetDetailsByDate(StatOrdini.DataOrdine, StatOrdini.CodiceCliente)

        Dim it As ListViewItem
        Dim row As DataRow
        If dtLista.Rows.Count > 0 Then

            Dim importoTotale As Decimal

            ListaArticoli.SuspendLayout()
            Me.ListaArticoli.BeginUpdate()

            For Each row In dtLista.Rows
                it = New ListViewItem(row("PECAR").ToString)

                it.SubItems.Add(row("PEDDA").ToString + " " + row("PEDPA").ToString)

                Dim qtaInt As Decimal
                qtaInt = Convert.ToDecimal(Convert.ToInt32(row("PEQTO")) / LibSetting.mille)
                it.SubItems.Add(qtaInt.ToString(LibSettings.formato, LibSettings.nfi))

                Dim importoInt As Decimal
                importoInt = Convert.ToDecimal(Convert.ToInt32(row("PEIMO")) / LibSetting.cento)

                Dim importo As String
                importo = importoInt.ToString(LibSettings.formato, LibSettings.nfi)
                it.SubItems.Add(importo)

                it.SubItems.Add(row("PETPR").ToString)

                importoTotale += importoInt
                Me.ListaArticoli.Items.Add(it)
            Next row

            Me.ListaArticoli.EndUpdate()
            ListaArticoli.ResumeLayout()
            Me.ListaArticoli.Refresh()

            Me.TxtTotale.Text = importoTotale.ToString(LibSettings.formato, LibSettings.nfi)

        End If
    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub

End Class


text:
using Bumblebee.Extensions;
using Bumblebee.IntegrationTests.Shared;
using Bumblebee.IntegrationTests.Shared.Hosting;
using Bumblebee.IntegrationTests.Shared.Pages;
using Bumblebee.Setup;

using FluentAssertions;

using NUnit.Framework;

// ReSharper disable InconsistentNaming

namespace Bumblebee.IntegrationTests.Setup.ThreadedSessionTests
{
	[TestFixture(typeof(HeadlessChrome))]
	public class Given_user_has_navigated_to_a_page<T> : HostTestFixture
	    where T : IDriverEnvironment, new()
    {
		[SetUp]
		public void TestSetUp()
		{
			Threaded<Session>
				.With<T>()
				.NavigateTo<DefaultPage>(GetUrl("Default.html"));
		}

		[TearDown]
		public void TestTearDown()
		{
			Threaded<Session>
				.End();
		}

		[Test]
		public void When_getting_current_page_as_correct_type_THen_should_return_page()
		{
			Threaded<Session>
				.CurrentPage<DefaultPage>()
				.VerifyThat(p => p.Should().NotBeNull())
				.VerifyThat(p => p.Should().BeOfType<DefaultPage>());
		}

		[Test]
		public void When_getting_current_page_as_incorrect_type_Then_should_return_page()
		{
			Threaded<Session>
				.CurrentPage<KeysPage>()
				.VerifyThat(p => p.Should().NotBeNull())
				.VerifyThat(p => p.Should().BeOfType<KeysPage>());
		}
	}
}


text:
require File.dirname(__FILE__) + '/test_helper'

class ExpanderTest < Test::Unit::TestCase

  def setup
    @expander = FontVariationDescription::Expander.new
  end

  # See expand.yml for test cases.
  FontVariationDescription::Test.expand_tests.each_with_index do |(fontface, fvd, description), index|
    define_method "test_#{index}_#{description.gsub(/\W/, '')}" do
      assert_equal @expander.parse(fvd), fontface, description
    end
  end

end


text:
import subprocess
import pyopencl as cl

gpu_idx = 0
platforms = cl.get_platforms()
i = 0
for platform in platforms:
    gpu_devices = platform.get_devices(device_type=cl.device_type.GPU)
    if gpu_idx < i + len(gpu_devices):
        context = cl.Context(devices=[gpu_devices[gpu_idx - i]])
        break
    i += len(gpu_devices)

print('context', context)
q = cl.CommandQueue(context)

mf = cl.mem_flags

kernel_source = """struct Eigen__TensorEvaluator {
    global float* f0;
    float f1;
};

kernel void foo(global float *floats0, global float* floats1) {
    global struct Eigen__TensorEvaluator *pstruct = (global struct Eigen__TensorEvaluator *)floats0;
    pstruct[0].f0 = floats1;
    pstruct[0].f0[0] = pstruct[0].f1;
}
"""

k2 = """
kernel void foo(global long *data, global float *floats0) {
    global float *global*data_as_ppfloat = (global float *global*)data;
    data_as_ppfloat[0] = floats0;
}
"""

def run():
    cl.Program(context, k2).build()
    print('compiled ok')

if __name__ == '__main__':
    run()


text:
module Spree
  module Core
    module Search
      class Base
        attr_accessor :properties
        attr_accessor :current_user
        attr_accessor :current_currency

        def initialize(params)
          self.current_currency = Spree::Config[:currency]
          @properties = {}
          prepare(params)
        end

        def all_products(with_group=true)
          products = get_base_scope(with_group)
          unless Spree::Config.show_products_without_price
            products = products
                       .where("spree_prices.amount IS NOT NULL")
                       .where("spree_prices.currency" => current_currency)
          end
          products
        end

        def retrieve_products(products=nil)
          curr_page = page || 1
          @products = products  || self.all_products()
          @products = @products.page(curr_page).per(per_page)
        end

        def method_missing(name)
          if @properties.has_key? name
            @properties[name]
          else
            super
          end
        end

        protected
          def get_base_scope(with_group=true)
            base_scope = Spree::Product.spree_base_scopes.active
            unless taxon.blank?
              if(with_group)
                base_scope = base_scope.in_taxon(taxon)
              else
                base_scope = base_scope.in_taxon_without_group(taxon)
              end
            end
            base_scope = get_products_conditions_for(base_scope, keywords)
            base_scope = add_search_scopes(base_scope)
            base_scope = add_eagerload_scopes(base_scope)
            base_scope
          end

          def add_eagerload_scopes scope
            # TL;DR Switch from `preload` to `includes` as soon as Rails starts honoring
            # `order` clauses on `has_many` associations when a `where` constraint
            # affecting a joined table is present (see
            # https://github.com/rails/rails/issues/6769).
            #
            # Ideally this would use `includes` instead of `preload` calls, leaving it
            # up to Rails whether associated objects should be fetched in one big join
            # or multiple independent queries. However as of Rails 4.1.8 any `order`
            # defined on `has_many` associations are ignored when Rails builds a join
            # query.
            #
            # Would we use `includes` in this particular case, Rails would do
            # separate queries most of the time but opt for a join as soon as any
            # `where` constraints affecting joined tables are added to the search;
            # which is the case as soon as a taxon is added to the base scope.
            scope = scope.preload(master: :prices)
            scope = scope.preload(master: :images) if include_images
            scope
          end

          def add_search_scopes(base_scope)
            search.each do |name, scope_attribute|
              scope_name = name.to_sym
              if base_scope.respond_to?(:search_scopes) && base_scope.search_scopes.include?(scope_name.to_sym)
                base_scope = base_scope.send(scope_name, *scope_attribute)
              else
                base_scope = base_scope.merge(Spree::Product.ransack({scope_name => scope_attribute}).result)
              end
            end if search.is_a?(Hash)
            base_scope
          end

          # method should return new scope based on base_scope
          def get_products_conditions_for(base_scope, query)
            unless query.blank?
              base_scope = base_scope.like_any([:name, :description], query.split)
            end
            base_scope
          end

          def prepare(params)
            @properties[:taxon] = params[:taxon].blank? ? nil : Spree::Taxon.find(params[:taxon])
            @properties[:keywords] = params[:keywords]
            @properties[:search] = params[:search]
            @properties[:include_images] = params[:include_images]

            per_page = params[:per_page].to_i
            @properties[:per_page] = per_page > 0 ? per_page : Spree::Config[:products_per_page]
            if params[:page].respond_to?(:to_i)
              @properties[:page] = (params[:page].to_i <= 0) ? 1 : params[:page].to_i
            else
              @properties[:page] = 1
            end
          end
      end
    end
  end
end


text:
package org.apache.hadoop.mapred;

import org.apache.hadoop.hdfs.Constant;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;

@SuppressWarnings("deprecation")
public class Reduce extends MapReduceBase implements
		Reducer<Text, Text, Text, Text>, Constant {

	private FileSystem fs;
	private Configuration conf;

	public void configure(JobConf configuration) {
		conf = new Configuration(configuration);
	}

	@Override
	public void reduce(Text key, Iterator<Text> values,
			OutputCollector<Text, Text> output, Reporter reporter)
			throws IOException {
		int size = 0;

		double averageIORate = 0;
		List<Float> list = new ArrayList<Float>();

		fs = FileSystem.get(conf);
		FSDataOutputStream out;

		if (fs.exists(new Path(OUTPUT, "result-writing")))
			out = fs.create(new Path(OUTPUT, "result-reading"), true);
		else
			out = fs.create(new Path(OUTPUT, "result-writing"), true);

		String mapper = conf.get("mapred.job.name");
		long bufferSize = mapper.equals("dfstest-writing") ? Long
				.parseLong(conf.get("dfs.buffer.size.write")) : Long
				.parseLong(conf.get("dfs.buffer.size.read"));
		long blockSize = Long.parseLong(conf.get("dfs.block.size"));
		long nTasks = Long.parseLong(conf.get("dfs.nTasks"));
		long replications = Long.parseLong(conf.get("dfs.replication"));
		long nmaps = Long.parseLong(conf.get("dfs.nmaps"));

		out.writeChars("-----------------------------\n");
		out.writeChars("Number of tasks:\t" + nmaps + "\n");
		out.writeChars("Replications:\t\t" + replications + "\n");
		out.writeChars("Files per task:\t\t" + nTasks + "\n");
		out.writeChars("BlockSize:\t\t" + blockSize + "\n");
		out.writeChars("BufferSize: " + bufferSize + "\tIORate\n");
		float min = Float.MAX_VALUE;
		float max = Float.MIN_VALUE;

		// TODO Auto-generated method stub
		for (; values.hasNext();) {
			size++;
			// tokens.nextToken(); there is only one value per line
			double ioRate = Double.parseDouble(values.next().toString());
			if (ioRate > max)
				max = (float) ioRate;
			if (ioRate < min)
				min = (float) ioRate;
			list.add((float) ioRate);
			// this is for testing
			// output.collect(new Text(String.valueOf(bufferSize)), new
			// Text(
			// String.valueOf(ioRate)));
			// out.writeChars(bufferSize + " bytes\t\t" + ioRate +
			// " Mb/s\n");
			averageIORate += ioRate;
		}
		out.writeChars("Min\t\t\t" + min + "\n");
		out.writeChars("Max\t\t\t" + max + "\n");
		averageIORate /= size;
		float temp = (float) 0.0;
		for (int i = 0; i < list.size(); i++) {
			temp += Math.pow(list.get(i) - averageIORate, 2);
		}
		out.writeChars("Average\t\t\t: " + averageIORate + "\n");
		float dev = (float) Math.sqrt(temp / size);
		out.writeChars("Std. dev\t\t: " + dev + "\n");
		out.close();
	}

}


text:
package com.intellij.codeInsight.navigation.actions;

import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.generation.actions.PresentableActionHandlerBasedAction;
import com.intellij.lang.CodeInsightActions;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageExtension;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtilCore;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

public class GotoSuperAction extends PresentableActionHandlerBasedAction implements CodeInsightActionHandler, DumbAware {

  @NonNls public static final String FEATURE_ID = "navigation.goto.super";

  @NotNull
  @Override
  protected CodeInsightActionHandler getHandler() {
    return this;
  }

  @Override
  public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) {
    int offset = editor.getCaretModel().getOffset();
    final Language language = PsiUtilCore.getLanguageAtOffset(file, offset);

    final CodeInsightActionHandler codeInsightActionHandler = CodeInsightActions.GOTO_SUPER.forLanguage(language);
    if (codeInsightActionHandler != null) {
      DumbService.getInstance(project).withAlternativeResolveEnabled(() -> codeInsightActionHandler.invoke(project, editor, file));
    }
  }

  @Override
  public boolean startInWriteAction() {
    return false;
  }

  @Override
  public void update(@NotNull final AnActionEvent event) {
    if (CodeInsightActions.GOTO_SUPER.hasAnyExtensions()) {
      event.getPresentation().setVisible(true);
      super.update(event);
    }
    else {
      event.getPresentation().setVisible(false);
    }
  }

  @NotNull
  @Override
  protected LanguageExtension<CodeInsightActionHandler> getLanguageExtension() {
    return CodeInsightActions.GOTO_SUPER;
  }
}


text:
const request = require('supertest');
const expect = require('chai').expect;
const resetDB = require('../scripts/methods/reset-db');
const createTestData = require('../scripts/methods/create-test-data');
const API = require('../../src/API');

let api;
let server;

describe('Group', () => {
  before(resetDB);

  before(async () => {
    api = new API();
    await api.start();
    server = api.server;
  });

  before(async () => {
    // Creates 10 users using the API
    await createTestData(api, server, 10, 0, 0);
  });

  after(async () => {
    await api.stop();
  });

  it('should get ids of users in a group success', async () => {
    const res = await request(server)
      .get('/api/group/group-a')
      .send()
      .set('Accept', 'application/json')
      .expect(200);

    expect(res.body.data).to.deep.equal([
      'user-0',
      'user-1',
      'user-2',
      'user-3',
      'user-4',
      'user-5',
      'user-6',
      'user-7',
      'user-8',
      'user-9',
    ]);
  });

  it('should add user to group successfully', async () => {
    const postRes = await request(server)
      .post('/api/group/user-0/new-group-01')
      .send()
      .set('Accept', 'application/json')
      .expect(200);

    expect(postRes.body.data).to.deep.equal({ id: 'user-0', group: 'new-group-01' });

    const getRes = await request(server)
      .get('/api/group/new-group-01')
      .send()
      .set('Accept', 'application/json')
      .expect(200);

    expect(getRes.body.data).to.deep.equal(['user-0']);
  });

  it('should remove user from group successfully', async () => {
    const deleteRes = await request(server)
      .delete('/api/group/user-0/new-group-01')
      .send()
      .set('Accept', 'application/json')
      .expect(200);

    expect(deleteRes.body.data).to.deep.equal({ id: 'user-0', group: 'new-group-01' });

    const getRes = await request(server)
      .get('/api/group/new-group-01')
      .send()
      .set('Accept', 'application/json')
      .expect(200);

    expect(getRes.body.data).to.deep.equal([]);
  });

  it('should delete all users from group successfully', async () => {
    const deleteRes = await request(server)
      .delete('/api/group/group-a')
      .send()
      .set('Accept', 'application/json')
      .expect(200);

    expect(getRes.body.data).to.deep.equal({group: 'group-a'});
  });
});


text:
<?php

/**
 * @group Database
 * @group Cache
 * @covers MessageCache
 */
class MessageCacheTest extends MediaWikiLangTestCase {

	protected function setUp() {
		parent::setUp();
		$this->configureLanguages();
		MessageCache::singleton()->enable();
	}

	/**
	 * Helper function -- setup site language for testing
	 */
	protected function configureLanguages() {
		// for the test, we need the content language to be anything but English,
		// let's choose e.g. German (de)
		$langCode = 'de';
		$langObj = Language::factory( $langCode );

		$this->setMwGlobals( array(
			'wgLanguageCode' => $langCode,
			'wgLang' => $langObj,
			'wgContLang' => $langObj,
		) );
	}

	function addDBData() {
		$this->configureLanguages();

		// Set up messages and fallbacks ab -> ru -> de
		$this->makePage( 'FallbackLanguageTest-Full', 'ab' );
		$this->makePage( 'FallbackLanguageTest-Full', 'ru' );
		$this->makePage( 'FallbackLanguageTest-Full', 'de' );

		// Fallbacks where ab does not exist
		$this->makePage( 'FallbackLanguageTest-Partial', 'ru' );
		$this->makePage( 'FallbackLanguageTest-Partial', 'de' );

		// Fallback to the content language
		$this->makePage( 'FallbackLanguageTest-ContLang', 'de' );

		// Add customizations for an existing message.
		$this->makePage( 'sunday', 'ru' );

		// Full key tests -- always want russian
		$this->makePage( 'MessageCacheTest-FullKeyTest', 'ab' );
		$this->makePage( 'MessageCacheTest-FullKeyTest', 'ru' );

		// In content language -- get base if no derivative
		$this->makePage( 'FallbackLanguageTest-NoDervContLang', 'de', 'de/none' );
	}

	/**
	 * Helper function for addDBData -- adds a simple page to the database
	 *
	 * @param string $title Title of page to be created
	 * @param string $lang Language and content of the created page
	 * @param string|null $content Content of the created page, or null for a generic string
	 */
	protected function makePage( $title, $lang, $content = null ) {
		global $wgContLang;

		if ( $content === null ) {
			$content = $lang;
		}
		if ( $lang !== $wgContLang->getCode() ) {
			$title = "$title/$lang";
		}

		$title = Title::newFromText( $title, NS_MEDIAWIKI );
		$wikiPage = new WikiPage( $title );
		$contentHandler = ContentHandler::makeContent( $content, $title );
		$wikiPage->doEditContent( $contentHandler, "$lang translation test case" );
	}

	/**
	 * Test message fallbacks, bug #1495
	 *
	 * @dataProvider provideMessagesForFallback
	 */
	public function testMessageFallbacks( $message, $lang, $expectedContent ) {
		$result = MessageCache::singleton()->get( $message, true, $lang );
		$this->assertEquals( $expectedContent, $result, "Message fallback failed." );
	}

	function provideMessagesForFallback() {
		return array(
			array( 'FallbackLanguageTest-Full', 'ab', 'ab' ),
			array( 'FallbackLanguageTest-Partial', 'ab', 'ru' ),
			array( 'FallbackLanguageTest-ContLang', 'ab', 'de' ),
			array( 'FallbackLanguageTest-None', 'ab', false ),

			// Existing message with customizations on the fallbacks
			array( 'sunday', 'ab', 'амҽыш' ),

			// bug 46579
			array( 'FallbackLanguageTest-NoDervContLang', 'de', 'de/none' ),
			// UI language different from content language should only use de/none as last option
			array( 'FallbackLanguageTest-NoDervContLang', 'fit', 'de/none' ),
		);
	}

	/**
	 * There's a fallback case where the message key is given as fully qualified -- this
	 * should ignore the passed $lang and use the language from the key
	 *
	 * @dataProvider provideMessagesForFullKeys
	 */
	public function testFullKeyBehaviour( $message, $lang, $expectedContent ) {
		$result = MessageCache::singleton()->get( $message, true, $lang, true );
		$this->assertEquals( $expectedContent, $result, "Full key message fallback failed." );
	}

	function provideMessagesForFullKeys() {
		return array(
			array( 'MessageCacheTest-FullKeyTest/ru', 'ru', 'ru' ),
			array( 'MessageCacheTest-FullKeyTest/ru', 'ab', 'ru' ),
			array( 'MessageCacheTest-FullKeyTest/ru/foo', 'ru', false ),
		);
	}

	/**
	 * @dataProvider provideNormalizeKey
	 */
	public function testNormalizeKey( $key, $expected ) {
		$actual = MessageCache::normalizeKey( $key );
		$this->assertEquals( $expected, $actual );
	}

	public function provideNormalizeKey() {
		return array(
			array( 'Foo', 'foo' ),
			array( 'foo', 'foo' ),
			array( 'fOo', 'fOo' ),
			array( 'FOO', 'fOO' ),
			array( 'Foo bar', 'foo_bar' ),
			array( 'Ćab', 'ćab' ),
			array( 'Ćab_e 3', 'ćab_e_3' ),
			array( 'ĆAB', 'ćAB' ),
			array( 'ćab', 'ćab' ),
			array( 'ćaB', 'ćaB' ),
		);
	}
}


text:
def meetup_api_key
  "meetup_key"
end

def meetup_url(url)
  "http://api.meetup.com#{url}"
end

def fixture_file(filename)
  return '' if filename == ''
  file_path =  File.expand_path('../../fixtures/' + filename, __FILE__)
  File.read(file_path)
end


text:
/**
 * Created at 1:25:51 PM Jan 23, 2011
 */
using System;
using SharpBox2D.Callbacks;
using SharpBox2D.Collision;
using SharpBox2D.Collision.Shapes;
using SharpBox2D.Common;
using SharpBox2D.Dynamics;
using SharpBox2D.Dynamics.Contacts;
using SharpBox2D.Dynamics.Joints;
using SharpBox2D.TestBed.Framework;

namespace SharpBox2D.TestBed.Tests
{

/**
 * @author Daniel Murphy
 */

    public class SensorTest : TestbedTest
    {

        private class BoolWrapper
        {
            public bool tf;
        }

        private const int _e_count = 7;
        private Fixture m_sensor;
        private Body[] m_bodies = new Body[_e_count];
        private BoolWrapper[] m_touching = new BoolWrapper[_e_count];

        public override void initTest(bool deserialized)
        {

            for (int i = 0; i < m_touching.Length; i++)
            {
                m_touching[i] = new BoolWrapper();
            }

            {
                BodyDef bd = new BodyDef();
                Body ground = getWorld().createBody(bd);

                {
                    EdgeShape shape = new EdgeShape();
                    shape.set(new Vec2(-40.0f, 0.0f), new Vec2(40.0f, 0.0f));
                    ground.createFixture(shape, 0.0f);
                }

                {
                    CircleShape shape = new CircleShape();
                    shape.m_radius = 5.0f;
                    shape.m_p.set(0.0f, 10.0f);

                    FixtureDef fd = new FixtureDef();
                    fd.shape = shape;
                    fd._isSensor = true;
                    m_sensor = ground.createFixture(fd);
                }
            }

            {
                CircleShape shape = new CircleShape();
                shape.m_radius = 1.0f;

                for (int i = 0; i < _e_count; ++i)
                {
                    BodyDef bd = new BodyDef();
                    bd.type = BodyType.DYNAMIC;
                    bd.position.set(-10.0f + 3.0f*i, 20.0f);
                    bd.userData = m_touching[i];

                    m_touching[i].tf = false;
                    m_bodies[i] = getWorld().createBody(bd);

                    m_bodies[i].createFixture(shape, 1.0f);
                }
            }
        }

        // Implement contact listener.
        public override void beginContact(Contact contact)
        {
            Fixture fixtureA = contact.getFixtureA();
            Fixture fixtureB = contact.getFixtureB();

            if (fixtureA == m_sensor)
            {
                Object userData = fixtureB.getBody().getUserData();
                if (userData != null)
                {
                    ((BoolWrapper) userData).tf = true;
                }
            }

            if (fixtureB == m_sensor)
            {
                Object userData = fixtureA.getBody().getUserData();
                if (userData != null)
                {
                    ((BoolWrapper) userData).tf = true;
                }
            }
        }

        // Implement contact listener.
        public override void endContact(Contact contact)
        {
            Fixture fixtureA = contact.getFixtureA();
            Fixture fixtureB = contact.getFixtureB();

            if (fixtureA == m_sensor)
            {
                Object userData = fixtureB.getBody().getUserData();
                if (userData != null)
                {
                    ((BoolWrapper) userData).tf = false;
                }
            }

            if (fixtureB == m_sensor)
            {
                Object userData = fixtureA.getBody().getUserData();
                if (userData != null)
                {
                    ((BoolWrapper) userData).tf = false;
                }
            }
        }

        public override void step(TestbedSettings settings)
        {
            // TODO Auto-generated method stub
            base.step(settings);

            // Traverse the contact results. Apply a force on shapes
            // that overlap the sensor.
            for (int i = 0; i < _e_count; ++i)
            {
                if (m_touching[i].tf == false)
                {
                    continue;
                }

                Body body = m_bodies[i];
                Body ground = m_sensor.getBody();

                CircleShape circle = (CircleShape) m_sensor.getShape();
                Vec2 center = ground.getWorldPoint(circle.m_p);

                Vec2 position = body.getPosition();

                Vec2 d = center.sub(position);
                if (d.lengthSquared() < Settings.EPSILON*Settings.EPSILON)
                {
                    continue;
                }

                d.normalize();
                d.mulLocal(100f);
                Vec2 F = d;
                body.applyForce(F, position);
            }
        }

        public override string getTestName()
        {
            return "Sensor Test";
        }
    }
}


text:
rm wordpress/composer.json
cp -a wordpress/* .
rm -rf wordpress

# Create mu-plugins directory and copy mu-plugin files to wp-content/mu-plugins
rm -rf wp-content/mu-plugins
mkdir wp-content/mu-plugins
cp -a vendor/contention/wp-setup/mu-plugins/* wp-content/mu-plugins/

# Copy global third party plugin files to wp-content/plugins
cp -a vendor/contention/wp-setup/plugins/* wp-content/plugins/

# Copy site-specific third party plugin files to wp-content/plugins
if [ -d src/plugins/ ]; then
cp -a src/plugins/* wp-content/plugins/
fi

# Copy all additional root files to root
cp -a vendor/contention/wp-setup/root/* .
cp -a vendor/contention/wp-setup/root/.htaccess .

# Create symlink for wp-config
rm wp-config-sample.php
ln -s src/wp-config.php wp-config.php

# Create symlink for theme directory
rm -rf wp-content/themes/theme
ln -s ../../src/theme/ wp-content/themes/theme