text:
from nipype.testing import assert_equal
from nipype.interfaces.mipav.developer import JistLaminarVolumetricLayering

def test_JistLaminarVolumetricLayering_inputs():
    input_map = dict(args=dict(argstr='%s',
    ),
    environ=dict(nohash=True,
    usedefault=True,
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    inInner=dict(argstr='--inInner %s',
    ),
    inLayering=dict(argstr='--inLayering %s',
    ),
    inLayering2=dict(argstr='--inLayering2 %s',
    ),
    inMax=dict(argstr='--inMax %d',
    ),
    inMin=dict(argstr='--inMin %f',
    ),
    inNumber=dict(argstr='--inNumber %d',
    ),
    inOuter=dict(argstr='--inOuter %s',
    ),
    inTopology=dict(argstr='--inTopology %s',
    ),
    incurvature=dict(argstr='--incurvature %d',
    ),
    inpresmooth=dict(argstr='--inpresmooth %s',
    ),
    inratio=dict(argstr='--inratio %f',
    ),
    null=dict(argstr='--null %s',
    ),
    outContinuous=dict(argstr='--outContinuous %s',
    hash_files=False,
    ),
    outDiscrete=dict(argstr='--outDiscrete %s',
    hash_files=False,
    ),
    outLayer=dict(argstr='--outLayer %s',
    hash_files=False,
    ),
    terminal_output=dict(nohash=True,
    ),
    xDefaultMem=dict(argstr='-xDefaultMem %d',
    ),
    xMaxProcess=dict(argstr='-xMaxProcess %d',
    usedefault=True,
    ),
    xPrefExt=dict(argstr='--xPrefExt %s',
    ),
    )
    inputs = JistLaminarVolumetricLayering.input_spec()

    for key, metadata in input_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(inputs.traits()[key], metakey), value

def test_JistLaminarVolumetricLayering_outputs():
    output_map = dict(outContinuous=dict(),
    outDiscrete=dict(),
    outLayer=dict(),
    )
    outputs = JistLaminarVolumetricLayering.output_spec()

    for key, metadata in output_map.items():
        for metakey, value in metadata.items():
            yield assert_equal, getattr(outputs.traits()[key], metakey), value


text:
layout: docs
title: setBodyf
id: class.Facebook.HackCodegen.CodegenFunctionish.setBodyf
docid: class.Facebook.HackCodegen.CodegenFunctionish.setBodyf
permalink: /docs/reference/class.Facebook.HackCodegen.CodegenFunctionish.setBodyf/
---
# Facebook\\HackCodegen\\CodegenFunctionish::setBodyf()

``` Hack
public function setBodyf(
  HH\Lib\Str\SprintfFormatString $body,
  mixed ...$args,
): this;
```

## Parameters

+ ` HH\Lib\Str\SprintfFormatString $body `
+ ` mixed ...$args `

## Returns

* ` this `

redpajama_set_name: RedPajamaGithub


text:
//
// Copyright 2007 ZXing authors
//
// 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.
///

ZXing.Binarizer = function (source) {
    this.source = null;
    if (!source) {
        throw new Error("Source must be non-null.");
    }
    this.source = source;
};
ZXing.Binarizer.prototype.get_LuminanceSource = function () {
    return this.source;
};
ZXing.Binarizer.prototype.get_Width = function () {
    return this.source.get_Width();
};
ZXing.Binarizer.prototype.get_Height = function () {
    return this.source.get_Height();
};


text:
raycr
==============
This is a simple game written in asm.

The objective is to put the arrow between the ever-faster random obstacles.

To compile, the following commands were used:

\masm32\bin\ml /c /Zd /coff raycr.asm

\masm32\bin\Link /SUBSYSTEM:CONSOLE raycr.obj


text:
/**
 * SECTION:element-irtspparse
 * @title: irtspparse
 * @short_description: Interleaved RTSP parser
 * @see_also: #GstPcapParse
 *
 * This is an interleaved RTSP parser that allows extracting specific
 * so-called "channels" from received interleaved (TCP) RTSP data
 * (typically extracted from some network capture).
 *
 * ## Example launch line
 * |[
 * gst-launch-1.0 filesrc location=h264crasher.pcap ! pcapparse ! irtspparse
 * ! rtph264depay ! ffdec_h264 ! fakesink
 * ]| Read from a pcap dump file using filesrc, extract the raw TCP packets,
 * depayload and decode them.
 *
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>

#include "gstirtspparse.h"
#include <gst/base/gstbytereader.h>

GST_DEBUG_CATEGORY_STATIC (irtsp_parse_debug);
#define GST_CAT_DEFAULT irtsp_parse_debug

enum
{
  PROP_0,
  PROP_CHANNEL_ID
};

static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("application/x-rtp ; application/x-rtcp"));

static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS_ANY);

static void gst_irtsp_parse_finalize (GObject * object);

static gboolean gst_irtsp_parse_start (GstBaseParse * parse);
static gboolean gst_irtsp_parse_stop (GstBaseParse * parse);
static GstFlowReturn gst_irtsp_parse_handle_frame (GstBaseParse * parse,
    GstBaseParseFrame * frame, gint * skipsize);

static void gst_irtsp_parse_set_property (GObject * object,
    guint prop_id, const GValue * value, GParamSpec * pspec);
static void gst_irtsp_parse_get_property (GObject * object,
    guint prop_id, GValue * value, GParamSpec * pspec);

#define parent_class gst_irtsp_parse_parent_class
G_DEFINE_TYPE (GstIRTSPParse, gst_irtsp_parse, GST_TYPE_BASE_PARSE);

static void
gst_irtsp_parse_class_init (GstIRTSPParseClass * klass)
{
  GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass);
  GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  GST_DEBUG_CATEGORY_INIT (irtsp_parse_debug, "irtspparse", 0,
      "Interleaved RTSP stream parser");

  object_class->finalize = gst_irtsp_parse_finalize;

  object_class->set_property = gst_irtsp_parse_set_property;
  object_class->get_property = gst_irtsp_parse_get_property;

  g_object_class_install_property (object_class, PROP_CHANNEL_ID,
      g_param_spec_int ("channel-id", "channel-id",
          "Channel Identifier", 0, 255,
          0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

  parse_class->start = GST_DEBUG_FUNCPTR (gst_irtsp_parse_start);
  parse_class->stop = GST_DEBUG_FUNCPTR (gst_irtsp_parse_stop);
  parse_class->handle_frame = GST_DEBUG_FUNCPTR (gst_irtsp_parse_handle_frame);

  gst_element_class_add_static_pad_template (element_class, &sink_template);
  gst_element_class_add_static_pad_template (element_class, &src_template);

  gst_element_class_set_static_metadata (element_class, "IRTSPParse",
      "Raw/Parser",
      "Parses a raw interleaved RTSP stream",
      "Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>");
}

static void
gst_irtsp_parse_reset (GstIRTSPParse * IRTSPParse)
{
}

static void
gst_irtsp_parse_init (GstIRTSPParse * IRTSPParse)
{
  gst_base_parse_set_min_frame_size (GST_BASE_PARSE (IRTSPParse), 4);
  gst_irtsp_parse_reset (IRTSPParse);
}

static void
gst_irtsp_parse_finalize (GObject * object)
{
  G_OBJECT_CLASS (parent_class)->finalize (object);
}

static gboolean
gst_irtsp_parse_start (GstBaseParse * parse)
{
  GstIRTSPParse *IRTSPParse = GST_IRTSP_PARSE (parse);

  GST_DEBUG_OBJECT (parse, "starting");

  gst_irtsp_parse_reset (IRTSPParse);

  return TRUE;
}

static gboolean
gst_irtsp_parse_stop (GstBaseParse * parse)
{
  GST_DEBUG_OBJECT (parse, "stopping");

  return TRUE;
}

static GstFlowReturn
gst_irtsp_parse_handle_frame (GstBaseParse * parse,
    GstBaseParseFrame * frame, gint * skipsize)
{
  GstIRTSPParse *IRTSPParse = GST_IRTSP_PARSE (parse);
  GstBuffer *buf = frame->buffer;
  GstByteReader reader;
  gint off;
  GstMapInfo map;
  guint framesize;

  gst_buffer_map (buf, &map, GST_MAP_READ);
  if (G_UNLIKELY (map.size < 4))
    goto exit;

  gst_byte_reader_init (&reader, map.data, map.size);

  off = gst_byte_reader_masked_scan_uint32 (&reader, 0xffff0000,
      0x24000000 + (IRTSPParse->channel_id << 16), 0, map.size);

  GST_LOG_OBJECT (parse, "possible sync at buffer offset %d", off);

  /* didn't find anything that looks like a sync word, skip */
  if (off < 0) {
    *skipsize = map.size - 3;
    goto exit;
  }

  /* possible frame header, but not at offset 0? skip bytes before sync */
  if (off > 0) {
    *skipsize = off;
    goto exit;
  }

  framesize = GST_READ_UINT16_BE (map.data + 2) + 4;
  GST_LOG_OBJECT (parse, "got frame size %d", framesize);

  if (!gst_pad_has_current_caps (GST_BASE_PARSE_SRC_PAD (parse))) {
    GstCaps *caps;

    caps = gst_caps_new_empty_simple ("application/x-rtp");
    gst_pad_set_caps (GST_BASE_PARSE_SRC_PAD (parse), caps);
    gst_caps_unref (caps);
  }

  if (framesize <= map.size) {
    gst_buffer_unmap (buf, &map);
    /* HACK HACK skip header.
     * could also ask baseparse to skip this,
     * but that would give us a discontinuity for free
     * which is a bit too much to have on all our packets */
    frame->out_buffer = gst_buffer_copy (frame->buffer);
    gst_buffer_resize (frame->out_buffer, 4, -1);
    GST_BUFFER_FLAG_UNSET (frame->out_buffer, GST_BUFFER_FLAG_DISCONT);
    return gst_base_parse_finish_frame (parse, frame, framesize);
  }

exit:
  gst_buffer_unmap (buf, &map);
  return GST_FLOW_OK;
}

static void
gst_irtsp_parse_set_property (GObject * object,
    guint prop_id, const GValue * value, GParamSpec * pspec)
{
  GstIRTSPParse *IRTSPParse = GST_IRTSP_PARSE (object);

  switch (prop_id) {
    case PROP_CHANNEL_ID:
      IRTSPParse->channel_id = g_value_get_int (value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_irtsp_parse_get_property (GObject * object,
    guint prop_id, GValue * value, GParamSpec * pspec)
{
  GstIRTSPParse *IRTSPParse = GST_IRTSP_PARSE (object);

  switch (prop_id) {
    case PROP_CHANNEL_ID:
      g_value_set_int (value, IRTSPParse->channel_id);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}


text:
layout: global
title: Acessando o Alluxio a partir do Zeppelin
nickname: Apache Zeppelin
group: Frameworks
priority: 4
---

[Apache Zeppelin](http://zeppelin-project.org/) é uma plataforma `web` que permite a análise
de dados interativa. A versão anterior de Alluxio (Tachyon 0.8.2) foi
[integrada](https://github.com/apache/incubator-zeppelin/blob/master/docs/interpreter/tachyon.md)
com o Zeppelin e, em breve, nós iremos atualizar a integração para trabalhar com a versão mais
atual do Alluxio.


text:
using Microsoft.Rest.Generator.ClientModel;
using Microsoft.Rest.Generator.Python.Properties;
using Microsoft.Rest.Generator.Python.Templates;
using Microsoft.Rest.Generator.Python.TemplateModels;
using Microsoft.Rest.Generator.Utilities;
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Microsoft.Rest.Generator.Python
{
    public class PythonCodeGenerator : CodeGenerator
    {
        private const string ClientRuntimePackage = "runtime.msrest version 1.1.0";

        public PythonCodeGenerator(Settings settings) : base(settings)
        {
            Namer = new PythonCodeNamer();
        }

        public PythonCodeNamer Namer { get; set; }

        public override string Name
        {
            get { return "Python"; }
        }

        public override string Description
        {
            // TODO resource string.
            get { return "Python for Http Client Libraries"; }
        }

        [SettingsInfo("The SDK version for generated setup.py.")]
        public string Version { get; set; }

        public override string UsageInstructions
        {
            get
            {
                return string.Format(CultureInfo.InvariantCulture,
                    Resources.UsageInformation, ClientRuntimePackage);
            }
        }

        public override string ImplementationFileExtension
        {
            get { return ".py"; }
        }

        /// <summary>
        /// Normalizes client model by updating names and types to be language specific.
        /// </summary>
        /// <param name="serviceClient"></param>
        public override void NormalizeClientModel(ServiceClient serviceClient)
        {
            Extensions.NormalizeClientModel(serviceClient, Settings);
            PopulateAdditionalProperties(serviceClient);
            Namer.NormalizeClientModel(serviceClient);
            Namer.ResolveNameCollisions(serviceClient, Settings.Namespace,
                Settings.Namespace + "_models");
        }

        private void PopulateAdditionalProperties(ServiceClient serviceClient)
        {
            if (Settings.AddCredentials)
            {
                if (!serviceClient.Properties.Any(p => p.Type == PrimaryType.Credentials))
                {
                    serviceClient.Properties.Add(new Property
                    {
                        Name = "credentials",
                        SerializedName = "credentials",
                        Type = PrimaryType.Credentials,
                        IsRequired = true,
                        Documentation = "Subscription credentials which uniquely identify client subscription."
                    });
                }
            }
        }

        /// <summary>
        /// Generate Python client code for given ServiceClient.
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <returns></returns>
        public override async Task Generate(ServiceClient serviceClient)
        {
            var serviceClientTemplateModel = new ServiceClientTemplateModel(serviceClient);

            if (!string.IsNullOrWhiteSpace(Version))
            {
                serviceClientTemplateModel.Version = Version;
            }

            // Service client
            var setupTemplate = new SetupTemplate
            {
                Model = serviceClientTemplateModel
            };
            await Write(setupTemplate, "setup.py");

            var serviceClientInitTemplate = new ServiceClientInitTemplate
            {
                Model = serviceClientTemplateModel
            };
            await Write(serviceClientInitTemplate, Path.Combine(serviceClient.Name.ToPythonCase(), "__init__.py"));

            var serviceClientTemplate = new ServiceClientTemplate
            {
                Model = serviceClientTemplateModel,
            };
            await Write(serviceClientTemplate, Path.Combine(serviceClient.Name.ToPythonCase(), "api_client.py"));

            //Models
            if (serviceClient.ModelTypes.Any())
            {
                var modelInitTemplate = new ModelInitTemplate
                {
                    Model = new ModelInitTemplateModel(serviceClient)
                };
                await Write(modelInitTemplate, Path.Combine(serviceClient.Name.ToPythonCase(), "models", "__init__.py"));

                foreach (var modelType in serviceClientTemplateModel.ModelTemplateModels)
                {
                    var modelTemplate = new ModelTemplate
                    {
                        Model = modelType
                    };
                    await Write(modelTemplate, Path.Combine(serviceClient.Name.ToPythonCase(), "models", modelType.Name.ToPythonCase() + ".py"));
                }
            }

            //MethodGroups
            if (serviceClientTemplateModel.MethodGroupModels.Any())
            {
                var methodGroupIndexTemplate = new MethodGroupInitTemplate
                {
                    Model = serviceClientTemplateModel
                };
                await Write(methodGroupIndexTemplate, Path.Combine(serviceClient.Name.ToPythonCase(), "operations", "__init__.py"));

                foreach (var methodGroupModel in serviceClientTemplateModel.MethodGroupModels)
                {
                    var methodGroupTemplate = new MethodGroupTemplate
                    {
                        Model = methodGroupModel
                    };
                    await Write(methodGroupTemplate, Path.Combine(serviceClient.Name.ToPythonCase(), "operations", methodGroupModel.MethodGroupType.ToPythonCase() + ".py"));
                }
            }

            // Enums
            if (serviceClient.EnumTypes.Any())
            {
                var enumTemplate = new EnumTemplate
                {
                    Model = new EnumTemplateModel(serviceClient.EnumTypes),
                };
                await Write(enumTemplate, Path.Combine(serviceClient.Name.ToPythonCase(), "models", "enums.py"));
            }
        }
    }
}


text:
fur-aggregator [![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/furrio/fur-aggregator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Stories in Ready](https://badge.waffle.io/furrio/fur-aggregator.svg?label=ready&title=Ready)](http://waffle.io/furrio/fur-aggregator)
==============

# Features

Planned:

- Store Credentials Locally
- Builds for Windows, Mac, and Ubuntu (Travis, Tested)
- Fave / Watchlist Sync
- Gallery
	- Tags / Keywords
- Artist Correlation
- Tag Filter
- Local Search / Filtering
	- Mature Content
	- Description Full Text Search
- Duplicate Elimination with Database / Percetual Hashing with `phash`
- Image Syncing between sites
- Multi-Site Publishing
- Quick Access Security PIN

Current:

- None so far.

## Network Support

Planned:

- FurAffinity
- Inkbunny
- SoFurry
- Weasyl
- e621
- DeviantArt
- Pixiv
- Imageboard Support (fchan, etc...)

Current:

- None so far.

# Contributors

Backend: Python
Frontend: NodeJS

Bundled as a Desktop App

## Dry
- Uploader
- Dependency Resolver

## Hunter
- Frontend
- Gallery
- App

## Kauko
- Weasyl Contact & API Guru

## Salmy
- FA Scraper
- Inkbunny API Guru

## Additional Contributors
- Tyler "Nighthound" McCall

# Acknowledgements

Project organized with inspiration from [the hackathon](https://www.anthrobot.org) at MWFF 2014.


text:
<?php declare(strict_types=1);

namespace PHPUnit\TestFixture;

use PHPUnit\Framework\TestCase;

/**
 * Tests for the BankAccount class.
 */
class BankAccountTest extends TestCase
{
    protected $ba;

    protected function setUp(): void
    {
        $this->ba = new BankAccount;
    }

    /**
     * @covers BankAccount::getBalance
     * @group balanceIsInitiallyZero
     * @group specification
     */
    public function testBalanceIsInitiallyZero(): void
    {
        $this->assertEquals(0, $this->ba->getBalance());
    }

    /**
     * @covers BankAccount::withdrawMoney
     * @group balanceCannotBecomeNegative
     * @group specification
     */
    public function testBalanceCannotBecomeNegative(): void
    {
        try {
            $this->ba->withdrawMoney(1);
        } catch (BankAccountException $e) {
            $this->assertEquals(0, $this->ba->getBalance());

            return;
        }

        $this->fail();
    }

    /**
     * @covers BankAccount::depositMoney
     * @group balanceCannotBecomeNegative
     * @group specification
     */
    public function testBalanceCannotBecomeNegative2(): void
    {
        try {
            $this->ba->depositMoney(-1);
        } catch (BankAccountException $e) {
            $this->assertEquals(0, $this->ba->getBalance());

            return;
        }

        $this->fail();
    }

    /*
     * @covers BankAccount::getBalance
     * @covers BankAccount::depositMoney
     * @covers BankAccount::withdrawMoney
     * @group balanceCannotBecomeNegative
     */
    /*
    public function testDepositingAndWithdrawingMoneyWorks()
    {
        $this->assertEquals(0, $this->ba->getBalance());
        $this->ba->depositMoney(1);
        $this->assertEquals(1, $this->ba->getBalance());
        $this->ba->withdrawMoney(1);
        $this->assertEquals(0, $this->ba->getBalance());
    }
    */
}


text:
package com.huffingtonpost.chronos.model;

import java.io.Closeable;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import com.huffingtonpost.chronos.agent.CallableJob;
import com.huffingtonpost.chronos.persist.BackendException;

public interface JobDao extends Closeable {

  public void setDrivers(List<SupportedDriver> drivers);

  public void init() throws BackendException;

  public long createJob(JobSpec jobSpec);

  public void updateJob(JobSpec jobSpec);

  public void deleteJob(long id);

  public List<JobSpec> getJobs();

  public JobSpec getJob(long id);

  public List<Map<String, String>> getJobResults(JobSpec jobSpec, int limit)
          throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException;

  public List<PlannedJob> getQueue(Long id);

  public void addToQueue(PlannedJob aJob);

  public PlannedJob removeFromQueue();

  public Map<Long, CallableJob> getJobRuns(Long id, int limit);

  public Map<Long, CallableJob> getRunningJobs();

  public long createJobRun(CallableJob cq);

  public void updateJobRun(CallableJob cq);

  public int cancelJob(PlannedJob pj);

  List<JobSpec> getJobVersions(long id);

  public void setDataSource(DataSource ds);

}


text:
<appc-page-heading text="Change password"></appc-page-heading>

<form class="form-horizontal" [formGroup]="changePasswordForm">

        Old password
        <input type="password" [class.error]="!changePasswordForm.get('oldPassword').valid" class="form-control input-lg" placeholder="Old password"
            formControlName="oldPassword" />

                    Old password is required

        New password
        <input type="password" [class.error]="!changePasswordForm.get('newPassword').valid" class="form-control input-lg" placeholder="New password"
            formControlName="newPassword" />

                    New password is required

        Confirm password
        <input type="password" [class.error]="!changePasswordForm.get('confirmPassword').valid" class="form-control input-lg" placeholder="Confirm password"
            formControlName="confirmPassword" />

                    Confirm password is required

    <button (click)="changePassword()" class="btn btn-primary pull-right">Change password</button>

</form>


text:
package org.wso2.developerstudio.datamapper.diagram.custom.dialogs;

import java.util.ArrayList;

import org.apache.commons.lang.StringUtils;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.edit.command.AddCommand;
import org.eclipse.emf.edit.command.DeleteCommand;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.wso2.developerstudio.datamapper.Concat;
import org.wso2.developerstudio.datamapper.DataMapperFactory;
import org.wso2.developerstudio.datamapper.DataMapperPackage;
import org.wso2.developerstudio.datamapper.OperatorLeftConnector;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.ConcatEditPart;
import org.wso2.developerstudio.datamapper.diagram.edit.parts.OperatorRectangle;
import org.wso2.developerstudio.datamapper.impl.ConcatImpl;

public class ConfigureConcatOperatorDialog extends AbstractConfigureOperatorDialog {

	private String inputCount;
	private String delimiter;
	private TransactionalEditingDomain editingDomain;
	private ArrayList<OperatorLeftConnector> caseOutputConnectors = new ArrayList<OperatorLeftConnector>();
	private ConcatImpl concatImpl;
	private EditPart editPart;

	public ConfigureConcatOperatorDialog(Shell parentShell, Concat concatOperator,
			TransactionalEditingDomain editingDomain, EditPart selectedEP) {
		super(parentShell);
		this.concatImpl = (ConcatImpl) concatOperator;
		this.editingDomain = editingDomain;
		this.editPart=selectedEP;
	}

	@Override
	public void create() {
		super.create();
		setTitle("Configure Concat Operator");
		setMessage("Set concat operator properties", IMessageProvider.INFORMATION);
	}

	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		// Set title.
		newShell.setText("Configure Concat Operator");
	}

	protected Control createDialogArea(Composite parent) {
		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NONE);
		container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		GridLayout layout = new GridLayout(2, false);
		container.setLayout(layout);

		Label concatInputConnectorCountLabel = new Label(container, SWT.NULL);
		concatInputConnectorCountLabel.setText("Number of Inputs : ");

		final Text inputConnectorCount = new Text(container, SWT.BORDER);
		inputConnectorCount.setLayoutData(dataPropertyConfigText);
		inputConnectorCount.setText(concatImpl.getBasicContainer().getLeftContainer().getLeftConnectors().size() + "");
		inputCount = inputConnectorCount.getText();
		inputConnectorCount.addListener(SWT.Modify, new Listener() {
			public void handleEvent(Event event) {
				try {
					inputCount = new String(inputConnectorCount.getText());
					if (!(StringUtils.isEmpty(inputCount) && StringUtils.isEmpty(delimiter))) {
						getButton(IDialogConstants.OK_ID).setEnabled(true);
						validate();
					} else {
						getButton(IDialogConstants.OK_ID).setEnabled(false);
					}
				} catch (Exception e) {
					getButton(IDialogConstants.OK_ID).setEnabled(false);
				}
			}
		});

		Label concatDelimiterLabel = new Label(container, SWT.NULL);
		concatDelimiterLabel.setText("Concat Delimiter : ");

		final Text delimiterText = new Text(container, SWT.BORDER);
		delimiterText.setLayoutData(dataPropertyConfigText);
		if (concatImpl.getDelimiter() != null) {
			delimiterText.setText(concatImpl.getDelimiter());
		} else {
			delimiterText.setText("");
		}
		delimiter = delimiterText.getText();

		delimiterText.addListener(SWT.Modify, new Listener() {
			public void handleEvent(Event event) {
				try {
					delimiter = new String(delimiterText.getText());
					if (!(StringUtils.isEmpty(inputCount) && StringUtils.isEmpty(delimiter))) {
						getButton(IDialogConstants.OK_ID).setEnabled(true);
						validate();
					} else {
						getButton(IDialogConstants.OK_ID).setEnabled(false);
					}
				} catch (Exception e) {
					getButton(IDialogConstants.OK_ID).setEnabled(false);
				}
			}
		});

		return area;
	}

	/**
	 * Create contents of the button bar.
	 *
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
		createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
		validate();
	}

	private void validate() {
		boolean isEnabled = false;
		Button okButton = getButton(IDialogConstants.OK_ID);
		if (delimiter != null && inputCount != null) {
			if (!StringUtils.isEmpty(delimiter)) {
				if (!inputCount.equals("0") && !StringUtils.isEmpty(inputCount)) {
					isEnabled = true;
				}
			}
		}
		if (okButton != null) {
			okButton.setEnabled(isEnabled);
		}
	}

	protected void okPressed() {

		if (!StringUtils.isEmpty(delimiter)) {
			Concat concatOperatorInstance = concatImpl;
			SetCommand setCmnd = new SetCommand(editingDomain, concatOperatorInstance,
					DataMapperPackage.Literals.CONCAT__DELIMITER, delimiter);
			if (setCmnd.canExecute()) {
				editingDomain.getCommandStack().execute(setCmnd);
			}
			((OperatorRectangle)((ConcatEditPart)editPart).getConcatFigure()).changeOperatorHeader("Concat : \""+delimiter+"\"");
		}
		int number = Integer.parseInt(inputCount)
				- concatImpl.getBasicContainer().getLeftContainer().getLeftConnectors().size();
		if (number > 0) {
			for (int i = 0; i < number; ++i) {
				OperatorLeftConnector concatOperatorContainers = DataMapperFactory.eINSTANCE
						.createOperatorLeftConnector();
				AddCommand addCmd = new AddCommand(editingDomain, concatImpl.getBasicContainer().getLeftContainer(),
						DataMapperPackage.Literals.OPERATOR_LEFT_CONTAINER__LEFT_CONNECTORS, concatOperatorContainers);
				if (addCmd.canExecute()) {
					editingDomain.getCommandStack().execute(addCmd);
				}

			}
		} else if (number < 0) {

			for (int i = 0; i < Math.abs(number); i++) {
				EList<OperatorLeftConnector> listOfLeftConnectors = concatImpl.getBasicContainer().getLeftContainer()
						.getLeftConnectors();
				OperatorLeftConnector concatOperatorConnector = listOfLeftConnectors
						.get(listOfLeftConnectors.size() - 1);
				caseOutputConnectors.add(concatOperatorConnector);
				DeleteCommand deleteCmd = new DeleteCommand(editingDomain, caseOutputConnectors);
				if (deleteCmd.canExecute()) {
					editingDomain.getCommandStack().execute(deleteCmd);
				}
				caseOutputConnectors.remove(concatOperatorConnector);
			}
		}

		super.okPressed();
	}

}


text:
import logging
import pprint
import json
import os, sys

import httplib2
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
from googleapiclient.errors import HttpError

from secret import GOOGLE_PRIVATE_KEY_FILE, GOOGLE_DEVELOPER_PROJECT_ID, GOOGLE_DEVELOPER_PROJECT_NUMBER, GOOGLE_SERVICE_EMAIL

from census_schema import demo_schema, group_schema, family_schema, income_schema

class GoogleBigQueryClient():
    """
    Google BigQuery API Client for GDELT access and processing.
    """
    def __init__(self):
        """
        Build authorized Google Big Query API Client from project_id and project_number given project google service email.
        """
        SCOPE = 'https://www.googleapis.com/auth/bigquery'
        self.get_private_key()
        credentials = SignedJwtAssertionCredentials(GOOGLE_SERVICE_EMAIL, self.private_key, SCOPE)
        http = httplib2.Http()
        self.http = credentials.authorize(http)
        self.client = build('bigquery', 'v2', http=self.http)

    def get_private_key(self):
        """
        Read from *.pem private key file. File path specified in secrets.py.
        """
        BASE = os.path.dirname(os.path.abspath(__file__))
        f = file(os.path.join(BASE, GOOGLE_PRIVATE_KEY_FILE), 'rb')
        self.private_key = f.read()
        f.close()

    def test_access(self):
        """
        Small response test to test authorized client. Working as of 02/25/15.
        """
        datasets = self.client.datasets()
        response = datasets.list(projectId=GOOGLE_DEVELOPER_PROJECT_NUMBER, all="true").execute()
        print(response)
        print('dataset list: \n')
        for d in response['datasets']:
            print("%s\n" % d['id'])

def loadTable(service, projectId, datasetId, targetTableId, sourceCSV, tableSchema, skip=0):
  """
  Load table from Google Cloud Storage into Big Query.
  """
  try:
    jobCollection = service.jobs()
    jobData = {
      'projectId': projectId,
      'configuration': {
          'load': {
            'sourceUris': [sourceCSV],
            'skipLeadingRows': skip,
            'fieldDelimiter': ",",
            'allowQuotedNewLines': True,
            'maxBadRecords': 1,
            'schema': {
              'fields': tableSchema
            },
            'destinationTable': {
              'projectId': projectId,
              'datasetId': datasetId,
              'tableId': targetTableId
            },
          }
        }
      }

    insertResponse = jobCollection.insert(projectId=projectId,
                                         body=jobData).execute()
    import time
    while True:
      job = jobCollection.get(projectId=projectId,
                                 jobId=insertResponse['jobReference']['jobId']).execute()
      print(">>> Google says the upload is: " + job['status']['state'])
      if 'DONE' == job['status']['state']:
          if 'errors' in job['status']:
            print(job['status']['errors'])
          return
      time.sleep(10)

    if 'errorResult' in job['status']:
      print 'Error loading table: ', pprint.pprint(job)
      return
  except HttpError as err:
    print 'Error in loadTable: ', pprint.pprint(err.resp)

def main():
  client = GoogleBigQueryClient()
  client.test_access()
  # loadTable(client.client, GOOGLE_DEVELOPER_PROJECT_ID, "new_jersey", "new_jersey_demo", "gs://demographic-data/NewJerseyQuery.csv", demo_schema)
  # loadTable(client.client, GOOGLE_DEVELOPER_PROJECT_ID, "new_jersey", "new_jersey_group", "gs://groupquarter-data/NewJerseyGQuery.txt", group_schema)
  # loadTable(client.client, GOOGLE_DEVELOPER_PROJECT_ID, "new_jersey", "new_jersey_family", "gs://family-data/NewJerseyFQuery.txt", family_schema)
  # loadTable(client.client, GOOGLE_DEVELOPER_PROJECT_ID, "new_jersey", "new_jersey_income", "gs://income-data/NewJerseyIncome.csv", income_schema)

if __name__ == "__main__":
    main()


text:
package software.amazon.awssdk.core.internal.waiters;

import static software.amazon.awssdk.utils.Validate.mutuallyExclusive;

import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;

/**
 * The default implementation of the {@link WaiterResponse}
 */
@SdkInternalApi
public final class DefaultWaiterResponse<T> implements WaiterResponse<T> {
    private final T result;
    private final Throwable exception;
    private final int attemptsExecuted;
    private final ResponseOrException<T> matched;

    private DefaultWaiterResponse(Builder<T> builder) {
        mutuallyExclusive("response and exception are mutually exclusive, set only one on the Builder",
                          builder.response, builder.exception);
        this.result = builder.response;
        this.exception = builder.exception;
        this.attemptsExecuted = Validate.paramNotNull(builder.attemptsExecuted, "attemptsExecuted");
        Validate.isPositive(builder.attemptsExecuted, "attemptsExecuted");
        matched = result != null ?
                  ResponseOrException.response(result) :
                  ResponseOrException.exception(exception);
    }

    public static <T> Builder<T> builder() {
        return new Builder<>();
    }

    @Override
    public ResponseOrException<T> matched() {
        return matched;
    }

    @Override
    public int attemptsExecuted() {
        return attemptsExecuted;
    }

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

        DefaultWaiterResponse<?> that = (DefaultWaiterResponse<?>) o;

        if (attemptsExecuted != that.attemptsExecuted) {
            return false;
        }
        if (!Objects.equals(result, that.result)) {
            return false;
        }
        return Objects.equals(exception, that.exception);
    }

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

    @Override
    public String toString() {
        ToString toString = ToString.builder("DefaultWaiterResponse")
                                    .add("attemptsExecuted", attemptsExecuted);

        matched.response().ifPresent(r -> toString.add("response", result));
        matched.exception().ifPresent(r -> toString.add("exception", exception));

        return toString.build();
    }

    public static final class Builder<T> {
        private T response;
        private Throwable exception;
        private Integer attemptsExecuted;

        private Builder() {
        }

        /**
         * Defines the response received that has matched with the waiter success condition.
         *
         * @param response the response
         * @return the chained builder
         */
        public Builder<T> response(T response) {
            this.response = response;
            return this;
        }

        /**
         * Defines the exception thrown from the waiter operation that has matched with the waiter success condition
         *
         * @param exception the exception
         * @return the chained builder
         */
        public Builder<T> exception(Throwable exception) {
            this.exception = exception;
            return this;
        }

        /**
         * Defines the number of attempts executed in the waiter operation
         *
         * @param attemptsExecuted the number of attempts
         * @return the chained builder
         */
        public Builder<T> attemptsExecuted(Integer attemptsExecuted) {
            this.attemptsExecuted = attemptsExecuted;
            return this;
        }

        public WaiterResponse<T> build() {
            return new DefaultWaiterResponse<>(this);
        }
    }
}


text:
#ifndef __CPU_BASE_DYN_INST_IMPL_HH__
#define __CPU_BASE_DYN_INST_IMPL_HH__

#include <iostream>
#include <set>
#include <sstream>
#include <string>

#include "base/cprintf.hh"
#include "base/trace.hh"
#include "config/the_isa.hh"
#include "cpu/base_dyn_inst.hh"
#include "cpu/exetrace.hh"
#include "debug/DynInst.hh"
#include "debug/IQ.hh"
#include "mem/request.hh"
#include "sim/faults.hh"

template <class Impl>
BaseDynInst<Impl>::BaseDynInst(StaticInstPtr _staticInst,
                               StaticInstPtr _macroop,
                               TheISA::PCState _pc, TheISA::PCState _predPC,
                               InstSeqNum seq_num, ImplCPU *cpu)
  : staticInst(_staticInst), cpu(cpu), traceData(NULL), macroop(_macroop)
{
    seqNum = seq_num;

    pc = _pc;
    predPC = _predPC;

    initVars();
}

template <class Impl>
BaseDynInst<Impl>::BaseDynInst(StaticInstPtr _staticInst,
                               StaticInstPtr _macroop)
    : staticInst(_staticInst), traceData(NULL), macroop(_macroop)
{
    seqNum = 0;
    initVars();
}

template <class Impl>
void
BaseDynInst<Impl>::initVars()
{
    memData = NULL;
    effAddr = 0;
    physEffAddr = 0;
    readyRegs = 0;

    status.reset();

    instFlags.reset();
    instFlags[RecordResult] = true;
    instFlags[Predicate] = true;

    lqIdx = -1;
    sqIdx = -1;

    // Eventually make this a parameter.
    threadNumber = 0;

    // Also make this a parameter, or perhaps get it from xc or cpu.
    asid = 0;

    // Initialize the fault to be NoFault.
    fault = NoFault;

#ifndef NDEBUG
    ++cpu->instcount;

    if (cpu->instcount > 1500) {
#ifdef DEBUG
        cpu->dumpInsts();
        dumpSNList();
#endif
        assert(cpu->instcount <= 1500);
    }

    DPRINTF(DynInst,
        "DynInst: [sn:%lli] Instruction created. Instcount for %s = %i\n",
        seqNum, cpu->name(), cpu->instcount);
#endif

#ifdef DEBUG
    cpu->snList.insert(seqNum);
#endif

    reqToVerify = NULL;
}

template <class Impl>
BaseDynInst<Impl>::~BaseDynInst()
{
    if (memData) {
        delete [] memData;
    }

    if (traceData) {
        delete traceData;
    }

    fault = NoFault;

#ifndef NDEBUG
    --cpu->instcount;

    DPRINTF(DynInst,
        "DynInst: [sn:%lli] Instruction destroyed. Instcount for %s = %i\n",
        seqNum, cpu->name(), cpu->instcount);
#endif
#ifdef DEBUG
    cpu->snList.erase(seqNum);
#endif

    if (reqToVerify)
        delete reqToVerify;
}

#ifdef DEBUG
template <class Impl>
void
BaseDynInst<Impl>::dumpSNList()
{
    std::set<InstSeqNum>::iterator sn_it = cpu->snList.begin();

    int count = 0;
    while (sn_it != cpu->snList.end()) {
        cprintf("%i: [sn:%lli] not destroyed\n", count, (*sn_it));
        count++;
        sn_it++;
    }
}
#endif

template <class Impl>
void
BaseDynInst<Impl>::dump()
{
    cprintf("T%d : %#08d `", threadNumber, pc.instAddr());
    std::cout << staticInst->disassemble(pc.instAddr());
    cprintf("'\n");
}

template <class Impl>
void
BaseDynInst<Impl>::dump(std::string &outstring)
{
    std::ostringstream s;
    s << "T" << threadNumber << " : 0x" << pc.instAddr() << " "
      << staticInst->disassemble(pc.instAddr());

    outstring = s.str();
}

template <class Impl>
void
BaseDynInst<Impl>::markSrcRegReady()
{
    DPRINTF(IQ, "[sn:%lli] has %d ready out of %d sources. RTI %d)\n",
            seqNum, readyRegs+1, numSrcRegs(), readyToIssue());
    if (++readyRegs == numSrcRegs()) {
        setCanIssue();
    }
}

template <class Impl>
void
BaseDynInst<Impl>::markSrcRegReady(RegIndex src_idx)
{
    _readySrcRegIdx[src_idx] = true;

    markSrcRegReady();
}

template <class Impl>
bool
BaseDynInst<Impl>::eaSrcsReady()
{
    // For now I am assuming that src registers 1..n-1 are the ones that the
    // EA calc depends on.  (i.e. src reg 0 is the source of the data to be
    // stored)

    for (int i = 1; i < numSrcRegs(); ++i) {
        if (!_readySrcRegIdx[i])
            return false;
    }

    return true;
}

#endif//__CPU_BASE_DYN_INST_IMPL_HH__


text:
rule('test/build/*.o', { 'test/src/*.c', 'test/build' }, function(target, match)
  print('Compiling ' .. target .. ' with generic rule...')
  exec('touch ' .. target)
end)


text:
<br />

<file-settings></file-settings>
<data-table></data-table>


text:
package types

import (
	"container/list"
	"fmt"

	. "github.com/tendermint/tmlibs/common"
)

type KVStore interface {
	Set(key, value []byte)
	Get(key []byte) (value []byte)
}

//----------------------------------------

type MemKVStore struct {
	m map[string][]byte
}

func NewMemKVStore() *MemKVStore {
	return &MemKVStore{
		m: make(map[string][]byte, 0),
	}
}

func (mkv *MemKVStore) Set(key []byte, value []byte) {
	mkv.m[string(key)] = value
}

func (mkv *MemKVStore) Get(key []byte) (value []byte) {
	return mkv.m[string(key)]
}

//----------------------------------------

// A Cache that enforces deterministic sync order.
type KVCache struct {
	store    KVStore
	cache    map[string]kvCacheValue
	keys     *list.List
	logging  bool
	logLines []string
}

type kvCacheValue struct {
	v []byte        // The value of some key
	e *list.Element // The KVCache.keys element
}

// NOTE: If store is nil, creates a new MemKVStore
func NewKVCache(store KVStore) *KVCache {
	if store == nil {
		store = NewMemKVStore()
	}
	return (&KVCache{
		store: store,
	}).Reset()
}

func (kvc *KVCache) SetLogging() {
	kvc.logging = true
}

func (kvc *KVCache) GetLogLines() []string {
	return kvc.logLines
}

func (kvc *KVCache) ClearLogLines() {
	kvc.logLines = nil
}

func (kvc *KVCache) Reset() *KVCache {
	kvc.cache = make(map[string]kvCacheValue)
	kvc.keys = list.New()
	return kvc
}

func (kvc *KVCache) Set(key []byte, value []byte) {
	if kvc.logging {
		line := fmt.Sprintf("Set %v = %v", LegibleBytes(key), LegibleBytes(value))
		kvc.logLines = append(kvc.logLines, line)
	}
	cacheValue, ok := kvc.cache[string(key)]
	if ok {
		kvc.keys.MoveToBack(cacheValue.e)
	} else {
		cacheValue.e = kvc.keys.PushBack(key)
	}
	cacheValue.v = value
	kvc.cache[string(key)] = cacheValue
}

func (kvc *KVCache) Get(key []byte) (value []byte) {
	cacheValue, ok := kvc.cache[string(key)]
	if ok {
		if kvc.logging {
			line := fmt.Sprintf("Get (hit) %v = %v", LegibleBytes(key), LegibleBytes(cacheValue.v))
			kvc.logLines = append(kvc.logLines, line)
		}
		return cacheValue.v
	} else {
		value := kvc.store.Get(key)
		kvc.cache[string(key)] = kvCacheValue{
			v: value,
			e: kvc.keys.PushBack(key),
		}
		if kvc.logging {
			line := fmt.Sprintf("Get (miss) %v = %v", LegibleBytes(key), LegibleBytes(value))
			kvc.logLines = append(kvc.logLines, line)
		}
		return value
	}
}

//Update the store with the values from the cache
func (kvc *KVCache) Sync() {
	for e := kvc.keys.Front(); e != nil; e = e.Next() {
		key := e.Value.([]byte)
		value := kvc.cache[string(key)]
		kvc.store.Set(key, value.v)
	}
	kvc.Reset()
}

//----------------------------------------

func LegibleBytes(data []byte) string {
	s := ""
	for _, b := range data {
		if 0x21 <= b && b < 0x7F {
			s += Green(string(b))
		} else {
			s += Blue(Fmt("%02X", b))
		}
	}
	return s
}


text:
  * `page: number`: Current page number.
  * `total: number`: Total number of items in all pages.
  * `limit?: number = 0`:  Limit number of visible pages. A value less than one indicates that there is no limitation.
  * `boundaryLinks?: boolean = false`: Whether to display First / Last buttons.
  * `boundaryNumbers?: number = 0`: Define how many of the first and last page numbers to always show.
  * `perPage?: number = 10`: Maximum number of items per page.

### Output

  * `pageChange: EventEmitter<number>`: the page clicked in order to select

### Export

  * `start: number`: Starting row index of current page
  * `end: number`: Last row index of current page


text:
class RssIconInput < SimpleForm::Inputs::Base
  def input(wrapper_options)
    input_html_options[:placeholder] ||= I18n.t 'simple_form.placeholders.subscription.rss'
    "#{@builder.text_field(attribute_name, input_html_options)}".html_safe
  end
end


text:
describe('Domu', function() {

  describe('getParams', function() {

    it('should be able to get params from window url', function() {
      if (window) {
        var params = domu.getParams();
        var url = window.location + '?foo=bar';
        window.history.pushState('test', 'Title', url);
      } else {
        var params = 'http://example.com/?foo=bar';
      }

      params = domu.getParams();

      expect(params.foo === 'bar').toBeTruthy();
    });

    it('should be able to get params from user url', function() {

      var url = 'http://example.com/?foo=bar&baz=qux';
      var params = domu.getParams(url);

      expect(params.foo === 'bar').toBeTruthy();
    });

  });

  describe('isMobileDevice', function() {
    it('should check if is mobile device', function() {
      var isMobileDevice = domu.isMobileDevice();
      expect(isMobileDevice).toMatch(/(true|false)/);
    });

    it('should check if is mobile device ios', function() {
      var isMobileDevice = domu.isMobileDevice('ios');
      expect(isMobileDevice).toBeFalsy();
    });

    it('should check if is mobile device ios7', function() {
      var isMobileDevice = domu.isMobileDevice('ios7');
      expect(isMobileDevice).toBeFalsy();
    });

    it('should check if is mobile device android', function() {
      var isMobileDevice = domu.isMobileDevice('android');
      expect(isMobileDevice).toBeFalsy();
    });

  });

  describe('parseHashtag', function() {

    it('should linkify hashtag', function() {
      var string = 'loremipsum http://example.com/ #foo #bar';
      var newString = domu.parseHashtag(string, 'http://twitter.com/search?q={{tag}}');

        expect(newString).toMatch(/href/);
    });
  });

  describe('parseUsername', function() {

    it('should linkify username', function() {
      var string = 'loremipsum http://example.com/ @github @twitter';
      var newString = domu.parseUsername(string, 'http://twitter.com/{{username}}');

        expect(newString).toMatch(/href/);
    });
  });

  describe('parseUrl', function() {

    it('should linkify url', function() {
      var string = 'loremipsum http://example.com/ http://github.com/ #foo #bar';
      var newString = domu.parseUrl(string);

      expect(newString).toMatch(/(href)/);
    });
  });

  describe('setQueryStringParam', function() {
    it('should update query string param', function() {
      var uri = 'http://example.com?foo=bar&baz=qux';
      uri = domu.setQueryStringParam(uri, 'foo', 'qux');
      expect(uri).toMatch(/foo=qux/);
    });

    it("should set query string param", function() {
      var uri = 'http://example.com?blank=';
      uri = domu.setQueryStringParam(uri, 'foo', 'qux');
      expect(uri).toMatch(/foo=qux/);
    });
  });

  describe('stripTags', function() {

    it('should strip html tags', function() {
      var string = '
foo
';
      var newString = domu.stripTags(string);

      expect(newString).toMatch(/^foo$/);
    });
  });

});


text:
from . import nanomsg, ffi
from .constants import *
import sys

NN_MSG = int(ffi.cast("size_t", -1))

class Socket(object):

	def __init__(self, domain, protocol):
		self.sock = nanomsg.nn_socket(domain, protocol)

	def close(self):
		nanomsg.nn_close(self.sock)

	def getsockopt(self, level, option):
		buf = ffi.new('int*')
		size = ffi.new('size_t*')
		size[0] = 4
		rc = nanomsg.nn_getsockopt(self.sock, level, option, buf, size)
		assert rc >= 0, rc
		return buf[0]

	def setsockopt(self, level, option, value):
		if isinstance(value, int):
			buf = ffi.new('int*')
			buf[0] = value
			vlen = 4
		elif isinstance(value, str):
			buf = ffi.new('char[%s]' % len(value), value.encode())
			vlen = len(value)
		elif isinstance(value, bytes):
			buf = ffi.new('char[%s]' % len(value), value)
			vlen = len(value)
		else:
			raise TypeError("value must be a int, str or bytes")
		rc = nanomsg.nn_setsockopt(self.sock, level, option, buf, vlen)
		assert rc >= 0, rc

	def bind(self, addr):
		addr = addr.encode() if isinstance(addr, str) else addr
		buf = ffi.new('char[]', addr)
		rc = nanomsg.nn_bind(self.sock, buf)
		assert rc > 0, rc

	def connect(self, addr):
		addr = addr.encode() if isinstance(addr, str) else addr
		buf = ffi.new('char[]', addr)
		rc = nanomsg.nn_connect(self.sock, buf)
		assert rc > 0, rc

	def send(self, data, flags=0):
		data = data.encode() if isinstance(data, str) else data
		l = len(data)
		buf = ffi.new('char[%i]' % l, data)
		rc = nanomsg.nn_send(self.sock, buf, l, flags)
		assert rc > 0, rc

	def recv(self, flags=0):
		buf = ffi.new('char**')
		rc = nanomsg.nn_recv(self.sock, buf, NN_MSG, flags)
		assert rc > 0, rc
		s = ffi.buffer(buf[0], rc)[:]
		nanomsg.nn_freemsg(buf[0])
		return s


text:
package sampler.cluster.abc.algorithm

import sampler.Implicits.SamplableMap
import sampler.cluster.abc.Model
import sampler.cluster.abc.Weighted
import sampler.cluster.abc.actor.LoggingAdapterComponent
import sampler.cluster.abc.actor.Report
import sampler.cluster.abc.actor.ScoredParticles
import sampler.cluster.abc.actor.Tagged
import sampler.cluster.abc.actor.WeighedParticles
import sampler.cluster.abc.actor.root.GettersComponent
import sampler.cluster.abc.algorithm.component.ToleranceCalculatorComponent
import sampler.cluster.abc.config.ABCConfig
import sampler.data.Distribution
import sampler.math.Random
import sampler.math.StatisticsComponent
import scala.collection.immutable.Queue
import sampler.cluster.abc.algorithm.component.ParticleMixerComponent

trait AlgorithmComponent {
	val algorithm: Algorithm
}

trait Algorithm {
	def addWeighted[P](incomingWeighted: WeighedParticles[P], gen: Generation[P]): Generation[P]
	def filterAndQueueForWeighing[P](taggedAndScored: ScoredParticles[P], gen: Generation[P]): Generation[P]
	def flushGeneration[P](gen: Generation[P], numParticles: Int, memoryGenerations: Int): Generation[P]
	def isEnoughParticles(gen: Generation[_], config: ABCConfig): Boolean
	def emptyWeighingBuffer[P](gen: Generation[P]): Generation[P]

	def buildMixPayload[P](gen: Generation[P], abcParameters: ABCConfig): Option[ScoredParticles[P]]
	def buildReport[P](gen: Generation[P], config: ABCConfig): Report[P]
}

/*
 * Use of a base trait and Impl allows us to strip out all the
 * self typing and simplify mocking
 */
trait AlgorithmComponentImpl extends AlgorithmComponent {
	this: ToleranceCalculatorComponent
		with StatisticsComponent
		with LoggingAdapterComponent
		with ParticleMixerComponent
		with GettersComponent =>

	val algorithm: Algorithm

	trait AlgorithmImpl extends Algorithm {
		implicit val r = Random

		def addWeighted[P](
				incoming: WeighedParticles[P],
				gen: Generation[P]
		): Generation[P] = {
			val weightedParticles = gen.weighted

			gen.copy(
					weighted = weightedParticles.add(incoming)
			)
		}

		def filterAndQueueForWeighing[P](
			taggedAndScoredParamSets: ScoredParticles[P],
			gen: Generation[P]
		): Generation[P] = {
			val observedIds = gen.idsObserved
			val particlesDueWeighting = gen.dueWeighing

			val filtered = taggedAndScoredParamSets.seq.filter(tagged => !observedIds.contains(tagged.id))

			gen.copy(
					dueWeighing = particlesDueWeighting.add(filtered),
					idsObserved = observedIds ++ filtered.map(_.id)
			)
		}

		def flushGeneration[P](gen: Generation[P], numParticles: Int, memoryGenerations: Int): Generation[P] = {
			val dueWeighing = gen.dueWeighing
		    val weightedParticles = gen.weighted
			val currentTolerance = gen.currentTolerance
			val currentIteration = gen.currentIteration
			val model = gen.model
			val queuedIds = gen.idsObserved

			assert(numParticles <= weightedParticles.size)

			val seqWeighted = weightedParticles.seq.map(_.value) //Strip out tags

			def consolidateToWeightsTable[P](model: Model[P], population: Seq[Weighted[P]]): Map[P, Double] = {
				population
				.groupBy(_.params)
				.map{case (k,v) => (k, v.map(_.weight).sum)}
			}

			def trimObservedIds(queue: Queue[Long]) = {
				val maxNum = memoryGenerations * numParticles

				val queueSize = queuedIds.size

				if(queueSize >= maxNum) {
				  val reducedNum = (memoryGenerations -1) * numParticles
				  val toDrop = queueSize - reducedNum
				  queuedIds.drop(toDrop)
				} else queuedIds
			}

			gen.copy(
			    dueWeighing = dueWeighing.empty,
			    weighted = weightedParticles.empty,
				currentTolerance = toleranceCalculator(seqWeighted, currentTolerance),
				currentIteration = currentIteration + 1,
				prevWeightsTable = consolidateToWeightsTable(model, seqWeighted),
				idsObserved = trimObservedIds(queuedIds)
			)
		}

		def isEnoughParticles(gen: Generation[_], config: ABCConfig): Boolean =
			gen.weighted.size >= config.job.numParticles

		def emptyWeighingBuffer[P](gen: Generation[P]): Generation[P] =
			gen.copy(dueWeighing = gen.dueWeighing.empty)

		//TODO can we simplify tagged and scored parm sets?
		def buildMixPayload[P](gen: Generation[P], abcParameters: ABCConfig): Option[ScoredParticles[P]] = {
			particleMixer.apply(gen, abcParameters)
		}

		def buildReport[P](gen: Generation[P], config: ABCConfig): Report[P] = {
		    val iteration = gen.currentIteration
		    val tolerance = gen.currentTolerance
		    val weightsTable = gen.prevWeightsTable

			val samples: Seq[P] = Distribution
				.fromProbabilityTable(weightsTable)
				.until(_.size == getters.getNumParticles(config))
				.sample

			Report(
				iteration,
				tolerance,
				samples
			)
		}
	}
}


text:
package com.demo.mummyding.multiimagechooser.adapter;

import android.content.Context;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.demo.mummyding.multiimagechooser.Utils.ScreenUtil;
import com.demo.mummyding.multiimagechooser.model.ImageBean;

import java.util.List;

/**
 * Created by mummyding on 15-11-3.
 */
public abstract class BasicAdapter extends BaseAdapter{
    protected List<ImageBean> mList;
    protected Context mContext;
    protected static int imageWidth;
    protected static LinearLayout.LayoutParams linearParams;
    protected static FrameLayout.LayoutParams frameParams;
    static {
        imageWidth = ScreenUtil.getScreenWidth()/3;
        linearParams = new LinearLayout.LayoutParams(imageWidth,imageWidth);
        frameParams = new FrameLayout.LayoutParams(imageWidth,imageWidth);
    }

    public BasicAdapter(Context mContext) {
        this.mContext = mContext;
    }

    public BaseAdapter setList(List<ImageBean> list){
        this.mList = list;
        return this;
    }
    public BaseAdapter updateUI(){
        this.notifyDataSetChanged();
        return this;
    }
    public List<ImageBean> getList(){
        return mList;
    }
    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return mList.get(position).getID();
    }
}


text:
package org.holoeverywhere.widget;

import org.holoeverywhere.app.AlertDialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.SpinnerAdapter;

import com.actionbarsherlock.R;

public class Spinner extends AbsSpinner implements OnClickListener {
    private class DialogPopup implements SpinnerPopup,
            DialogInterface.OnClickListener {
        private ListAdapter mListAdapter;
        private AlertDialog mPopup;
        private CharSequence mPrompt;

        @Override
        public void dismiss() {
            mPopup.dismiss();
            mPopup = null;
        }

        @Override
        public Drawable getBackground() {
            return null;
        }

        @Override
        public CharSequence getHintText() {
            return mPrompt;
        }

        @Override
        public int getHorizontalOffset() {
            return 0;
        }

        @Override
        public int getVerticalOffset() {
            return 0;
        }

        @Override
        public boolean isShowing() {
            return mPopup != null ? mPopup.isShowing() : false;
        }

        @Override
        public void onClick(DialogInterface dialog, final int which) {
            setSelection(which);
            if (mOnItemClickListener != null) {
                performItemClick(null, which, mListAdapter.getItemId(which));
            }
            dismiss();
        }

        @Override
        public void setAdapter(ListAdapter adapter) {
            mListAdapter = adapter;
        }

        @Override
        public void setBackgroundDrawable(Drawable bg) {
            Log.e(Spinner.TAG,
                    "Cannot set popup background for MODE_DIALOG, ignoring");
        }

        @Override
        public void setHorizontalOffset(int px) {
            Log.e(Spinner.TAG,
                    "Cannot set horizontal offset for MODE_DIALOG, ignoring");
        }

        @Override
        public void setPromptText(CharSequence hintText) {
            mPrompt = hintText;
        }

        @Override
        public void setVerticalOffset(int px) {
            Log.e(Spinner.TAG,
                    "Cannot set vertical offset for MODE_DIALOG, ignoring");
        }

        @Override
        public void show() {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            if (mPrompt != null) {
                builder.setTitle(mPrompt);
            }
            mPopup = builder.setSingleChoiceItems(mListAdapter,
                    getSelectedItemPosition(), this).show();
        }
    }

    private static class DropDownAdapter implements ListAdapter, SpinnerAdapter {
        private SpinnerAdapter mAdapter;
        private ListAdapter mListAdapter;

        public DropDownAdapter(SpinnerAdapter adapter) {
            mAdapter = adapter;
            if (adapter instanceof ListAdapter) {
                mListAdapter = (ListAdapter) adapter;
            }
        }

        @Override
        public boolean areAllItemsEnabled() {
            final ListAdapter adapter = mListAdapter;
            if (adapter != null) {
                return adapter.areAllItemsEnabled();
            } else {
                return true;
            }
        }

        @Override
        public int getCount() {
            return mAdapter == null ? 0 : mAdapter.getCount();
        }

        @Override
        public View getDropDownView(int position, View convertView,
                ViewGroup parent) {
            return mAdapter == null ? null : mAdapter.getDropDownView(position,
                    convertView, parent);
        }

        @Override
        public Object getItem(int position) {
            return mAdapter == null ? null : mAdapter.getItem(position);
        }

        @Override
        public long getItemId(int position) {
            return mAdapter == null ? -1 : mAdapter.getItemId(position);
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getDropDownView(position, convertView, parent);
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public boolean hasStableIds() {
            return mAdapter != null && mAdapter.hasStableIds();
        }

        @Override
        public boolean isEmpty() {
            return getCount() == 0;
        }

        @Override
        public boolean isEnabled(int position) {
            final ListAdapter adapter = mListAdapter;
            if (adapter != null) {
                return adapter.isEnabled(position);
            } else {
                return true;
            }
        }

        @Override
        public void registerDataSetObserver(DataSetObserver observer) {
            if (mAdapter != null) {
                mAdapter.registerDataSetObserver(observer);
            }
        }

        @Override
        public void unregisterDataSetObserver(DataSetObserver observer) {
            if (mAdapter != null) {
                mAdapter.unregisterDataSetObserver(observer);
            }
        }
    }

    private class DropdownPopup extends ListPopupWindow implements SpinnerPopup,
            PopupWindow.OnDismissListener {
        private ListAdapter mAdapter;
        private CharSequence mHintText;

        private boolean mSelectionSetted = false;

        public DropdownPopup(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, R.attr.listPopupWindowStyle);
            setAnchorView(Spinner.this);
            setModal(true);
            setPromptPosition(ListPopupWindow.POSITION_PROMPT_ABOVE);
            setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(android.widget.AdapterView<?> parent,
                        final View v, final int position, long id) {
                    Spinner.this.setSelection(position);
                    if (mOnItemClickListener != null) {
                        Spinner.this.performItemClick(v, position,
                                mAdapter.getItemId(position));
                    }
                    dismiss();
                }
            });
        }

        @Override
        public CharSequence getHintText() {
            return mHintText;
        }

        @Override
        public void onDismiss() {
            mSelectionSetted = false;
        }

        @Override
        public void setAdapter(ListAdapter adapter) {
            super.setAdapter(adapter);
            mAdapter = adapter;
        }

        @Override
        public void setPromptText(CharSequence hintText) {
            mHintText = hintText;
        }

        @Override
        public void show() {
            final Drawable background = getBackground();
            int bgOffset = 0;
            if (background != null) {
                background.getPadding(mTempRect);
                bgOffset = -mTempRect.left;
            } else {
                mTempRect.left = mTempRect.right = 0;
            }
            final int spinnerPaddingLeft = getPaddingLeft();
            if (mDropDownWidth == LayoutParams.WRAP_CONTENT) {
                final int spinnerWidth = Spinner.this.getWidth();
                final int spinnerPaddingRight = getPaddingRight();
                int contentWidth = measureContentWidth(
                        (SpinnerAdapter) mAdapter, getBackground());
                final int contentWidthLimit = getContext().getResources()
                        .getDisplayMetrics().widthPixels
                        - mTempRect.left
                        - mTempRect.right;
                if (contentWidth > contentWidthLimit) {
                    contentWidth = contentWidthLimit;
                }
                setContentWidth(Math.max(contentWidth, spinnerWidth
                        - spinnerPaddingLeft - spinnerPaddingRight));
            } else if (mDropDownWidth == LayoutParams.MATCH_PARENT) {
                final int spinnerWidth = Spinner.this.getWidth();
                final int spinnerPaddingRight = getPaddingRight();
                setContentWidth(spinnerWidth - spinnerPaddingLeft
                        - spinnerPaddingRight);
            } else {
                setContentWidth(mDropDownWidth);
            }
            setHorizontalOffset(bgOffset + spinnerPaddingLeft);
            setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
            super.show();
            getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
            if (!mSelectionSetted) {
                mSelectionSetted = true;
                setSelection(Spinner.this.getSelectedItemPosition());
            }
            setOnDismissListener(this);
        }
    }

    private interface SpinnerPopup {
        public void dismiss();

        public Drawable getBackground();

        public CharSequence getHintText();

        public int getHorizontalOffset();

        public int getVerticalOffset();

        public boolean isShowing();

        public void setAdapter(ListAdapter adapter);

        public void setBackgroundDrawable(Drawable bg);

        public void setHorizontalOffset(int px);

        public void setPromptText(CharSequence hintText);

        public void setVerticalOffset(int px);

        public void show();
    }

    private static final int MAX_ITEMS_MEASURED = 15;
    public static final int MODE_DIALOG = 0;
    public static final int MODE_DROPDOWN = 1;
    private static final int MODE_THEME = -1;
    private static final String TAG = "Spinner";
    private boolean mDisableChildrenWhenDisabled;
    int mDropDownWidth;
    private int mGravity;

    private SpinnerPopup mPopup;

    private DropDownAdapter mTempAdapter;

    private Rect mTempRect = new Rect();

    public Spinner(Context context) {
        this(context, null);
    }

    public Spinner(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.spinnerStyle);
    }

    public Spinner(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs, defStyle, Spinner.MODE_THEME);
    }

    public Spinner(Context context, AttributeSet attrs, int defStyle, int mode) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.Spinner, defStyle, R.style.Holo_Spinner);
        if (mode == Spinner.MODE_THEME) {
            mode = a.getInt(R.styleable.Spinner_spinnerMode,
                    Spinner.MODE_DIALOG);
        }
        switch (mode) {
            case MODE_DIALOG: {
                mPopup = new DialogPopup();
                break;
            }
            case MODE_DROPDOWN: {
                DropdownPopup popup = new DropdownPopup(context, attrs, defStyle);
                mDropDownWidth = a.getLayoutDimension(
                        R.styleable.Spinner_android_dropDownWidth,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                popup.setBackgroundDrawable(a
                        .getDrawable(R.styleable.Spinner_android_popupBackground));
                final int verticalOffset = a.getDimensionPixelOffset(
                        R.styleable.Spinner_dropDownVerticalOffset, 0);
                if (verticalOffset != 0) {
                    popup.setVerticalOffset(verticalOffset);
                }
                final int horizontalOffset = a.getDimensionPixelOffset(
                        R.styleable.Spinner_dropDownHorizontalOffset, 0);
                if (horizontalOffset != 0) {
                    popup.setHorizontalOffset(horizontalOffset);
                }
                mPopup = popup;
                break;

            }
        }
        mGravity = a
                .getInt(R.styleable.Spinner_android_gravity, Gravity.CENTER);
        mPopup.setPromptText(a.getString(R.styleable.Spinner_android_prompt));
        mDisableChildrenWhenDisabled = a.getBoolean(
                R.styleable.Spinner_disableChildrenWhenDisabled, false);
        a.recycle();
        if (mTempAdapter != null) {
            mPopup.setAdapter(mTempAdapter);
            mTempAdapter = null;
        }
    }

    public Spinner(Context context, int mode) {
        this(context, null, R.attr.spinnerStyle, mode);
    }

    @Override
    public int getBaseline() {
        View child = null;
        if (getChildCount() > 0) {
            child = getChildAt(0);
        } else if (getAdapter() != null && getAdapter().getCount() > 0) {
            child = makeAndAddView(0);
            mRecycler.put(0, child);
            removeAllViewsInLayout();
        }
        if (child != null) {
            final int childBaseline = child.getBaseline();
            return childBaseline >= 0 ? child.getTop() + childBaseline : -1;
        } else {
            return -1;
        }
    }

    public int getDropDownHorizontalOffset() {
        return mPopup.getHorizontalOffset();
    }

    public int getDropDownVerticalOffset() {
        return mPopup.getVerticalOffset();
    }

    public int getDropDownWidth() {
        return mDropDownWidth;
    }

    public int getGravity() {
        return mGravity;
    }

    public Drawable getPopupBackground() {
        return mPopup.getBackground();
    }

    public CharSequence getPrompt() {
        return mPopup.getHintText();
    }

    public void internalSetOnItemClickListener(OnItemClickListener l) {
        super.setOnItemClickListener(l);
    }

    @Override
    public void layout(int delta, boolean animate) {
        int childrenLeft = mSpinnerPadding.left;
        int childrenWidth = getRight() - getLeft() - mSpinnerPadding.left
                - mSpinnerPadding.right;
        if (mDataChanged) {
            handleDataChanged();
        }
        if (mItemCount == 0) {
            resetList();
            return;
        }
        if (mNextSelectedPosition >= 0) {
            setSelectedPositionInt(mNextSelectedPosition);
        }
        recycleAllViews();
        removeAllViewsInLayout();
        mFirstPosition = mSelectedPosition;
        View sel = makeAndAddView(mSelectedPosition);
        int width = sel.getMeasuredWidth();
        int selectedOffset = childrenLeft;
        switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
            case Gravity.CENTER_HORIZONTAL:
                selectedOffset = childrenLeft + childrenWidth / 2 - width / 2;
                break;
            case Gravity.RIGHT:
                selectedOffset = childrenLeft + childrenWidth - width;
                break;
        }
        sel.offsetLeftAndRight(selectedOffset);
        mRecycler.clear();
        invalidate();
        checkSelectionChanged();
        mDataChanged = false;
        mNeedSync = false;
        setNextSelectedPositionInt(mSelectedPosition);
    }

    private View makeAndAddView(int position) {
        View child;
        if (!mDataChanged) {
            child = mRecycler.get(position);
            if (child != null) {
                setUpChild(child);
                return child;
            }
        }
        child = mAdapter.getView(position, null, this);
        setUpChild(child);
        return child;
    }

    int measureContentWidth(SpinnerAdapter adapter, Drawable background) {
        if (adapter == null) {
            return 0;
        }
        int width = 0;
        View itemView = null;
        int itemType = 0;
        final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED);
        int start = Math.max(0, getSelectedItemPosition());
        final int end = Math.min(adapter.getCount(), start
                + Spinner.MAX_ITEMS_MEASURED);
        final int count = end - start;
        start = Math.max(0, start - (Spinner.MAX_ITEMS_MEASURED - count));
        for (int i = start; i < end; i++) {
            final int positionType = adapter.getItemViewType(i);
            if (positionType != itemType) {
                itemType = positionType;
                itemView = null;
            }
            itemView = adapter.getView(i, itemView, this);
            if (itemView.getLayoutParams() == null) {
                itemView.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            itemView.measure(widthMeasureSpec, heightMeasureSpec);
            width = Math.max(width, itemView.getMeasuredWidth());
        }
        if (background != null) {
            background.getPadding(mTempRect);
            width += mTempRect.left + mTempRect.right;
        }
        return width;
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        setSelection(which);
        dialog.dismiss();
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mPopup != null && mPopup.isShowing()) {
            mPopup.dismiss();
        }
    }

    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(Spinner.class.getName());
    }

    @Override
    @SuppressLint("NewApi")
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(Spinner.class.getName());
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        layout(0, false);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (mPopup != null
                && MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.AT_MOST) {
            final int measuredWidth = getMeasuredWidth();
            setMeasuredDimension(
                    Math.min(
                            Math.max(
                                    measuredWidth,
                                    measureContentWidth(getAdapter(),
                                            getBackground())), MeasureSpec
                                    .getSize(widthMeasureSpec)),
                    getMeasuredHeight());
        }
    }

    @Override
    public boolean performClick() {
        boolean handled = super.performClick();
        if (!handled) {
            handled = true;
            if (!mPopup.isShowing()) {
                mPopup.show();
            }
        }
        return handled;
    }

    @Override
    public void setAdapter(SpinnerAdapter adapter) {
        super.setAdapter(adapter);
        if (mPopup != null) {
            mPopup.setAdapter(new DropDownAdapter(adapter));
        } else {
            mTempAdapter = new DropDownAdapter(adapter);
        }
    }

    public void setDropDownHorizontalOffset(int pixels) {
        mPopup.setHorizontalOffset(pixels);
    }

    public void setDropDownVerticalOffset(int pixels) {
        mPopup.setVerticalOffset(pixels);
    }

    public void setDropDownWidth(int pixels) {
        if (!(mPopup instanceof DropdownPopup)) {
            Log.e(Spinner.TAG,
                    "Cannot set dropdown width for MODE_DIALOG, ignoring");
            return;
        }
        mDropDownWidth = pixels;
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (mDisableChildrenWhenDisabled) {
            final int count = getChildCount();
            for (int i = 0; i < count; i++) {
                getChildAt(i).setEnabled(enabled);
            }
        }
    }

    public void setGravity(int gravity) {
        if (mGravity != gravity) {
            if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) {
                gravity |= Gravity.LEFT;
            }
            mGravity = gravity;
            requestLayout();
        }
    }

    @Override
    public void setOnItemClickListener(OnItemClickListener l) {
        throw new RuntimeException(
                "setOnItemClickListener cannot be used with a spinner.");
    }

    public void setPopupBackgroundDrawable(Drawable background) {
        if (!(mPopup instanceof DropdownPopup)) {
            Log.e(Spinner.TAG,
                    "setPopupBackgroundDrawable: incompatible spinner mode; ignoring...");
            return;
        }
        ((DropdownPopup) mPopup).setBackgroundDrawable(background);
    }

    public void setPopupBackgroundResource(int resId) {
        setPopupBackgroundDrawable(getContext().getResources().getDrawable(
                resId));
    }

    public void setPrompt(CharSequence prompt) {
        mPopup.setPromptText(prompt);
    }

    public void setPromptId(int promptId) {
        setPrompt(getContext().getText(promptId));
    }

    private void setUpChild(View child) {
        ViewGroup.LayoutParams lp = child.getLayoutParams();
        if (lp == null) {
            lp = generateDefaultLayoutParams();
        }
        addViewInLayout(child, 0, lp);
        child.setSelected(hasFocus());
        if (mDisableChildrenWhenDisabled) {
            child.setEnabled(isEnabled());
        }
        int childHeightSpec = ViewGroup.getChildMeasureSpec(mHeightMeasureSpec,
                mSpinnerPadding.top + mSpinnerPadding.bottom, lp.height);
        int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
                mSpinnerPadding.left + mSpinnerPadding.right, lp.width);
        child.measure(childWidthSpec, childHeightSpec);
        int childLeft = 0;
        int childTop = mSpinnerPadding.top
                + (getMeasuredHeight() - mSpinnerPadding.bottom
                        - mSpinnerPadding.top - child.getMeasuredHeight()) / 2;
        int childBottom = childTop + child.getMeasuredHeight();
        int width = child.getMeasuredWidth();
        int childRight = childLeft + width;
        child.layout(childLeft, childTop, childRight, childBottom);
    }
}


text:
import { defineMessages } from 'react-intl';

const translations = defineMessages({
  deleteSuccess: {
    id: 'course.assessment.fileManager.deleteSuccess',
    defaultMessage: '"{name}" was deleted.',
  },
  deleteFail: {
    id: 'course.assessment.fileManager.deleteFail',
    defaultMessage: 'Failed to delete "{name}", please try again.',
  },
  uploadFail: {
    id: 'course.assessment.fileManager.uploadFail',
    defaultMessage: 'Failed to upload materials.',
  },
  addFiles: {
    id: 'course.assessment.fileManager.addFiles',
    defaultMessage: 'Add Files',
  },
  deleteSelected: {
    id: 'course.assessment.fileManager.deleteSelected',
    defaultMessage: 'Delete Selected',
  },
  fileName: {
    id: 'course.assessment.fileManager.fileName',
    defaultMessage: 'File name',
  },
  dateAdded: {
    id: 'course.assessment.fileManager.dateAdded',
    defaultMessage: 'Date added',
  },
  uploadingFile: {
    id: 'course.assessment.fileManager.uploadingFile',
    defaultMessage: 'Uploading file...',
  },
  disableNewFile: {
    id: 'course.assessment.fileManager.disableNewFile',
    defaultMessage:
      'You cannot add new files because the Materials component is disabled in Course Settings.',
  },
  studentCannotSeeFiles: {
    id: 'course.assessment.fileManager.studentCannotSeeFiles',
    defaultMessage:
      'Students cannot see these files because the Materials component is disabled in Course Settings.',
  },
});

export default translations;


text:
package io.mycat.net2.mysql.packet;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;

import io.mycat.net2.ByteBufferArray;

/**
 * @author mycat
 */
public class MySQLMessage {
    public static final long NULL_LENGTH = -1;
    private static final byte[] EMPTY_BYTES = new byte[0];

    // private final byte[] data;
    private final int length;
    private int position;
    private final ByteBufferArray bufferArray;
    private final int packetIndex;

    public MySQLMessage(ByteBufferArray bufferArray, int packetIndex) {
        this.bufferArray = bufferArray;
        this.length = bufferArray.getPacageLength(packetIndex);
        this.position = 0;
        this.packetIndex = packetIndex;
    }

    public int length() {
        return length;
    }

    public int position() {
        return position;
    }

    // public byte[] bytes() {
    // return data;
    // }

    public void move(int i) {
        position += i;
    }

    public void position(int i) {
        this.position = i;
    }

    public boolean hasRemaining() {
        return length > position;
    }

    public byte read(int i) {
        return bufferArray.readPacket(packetIndex, i);
    }

    public byte read() {
        return bufferArray.readPacket(packetIndex, position++);
    }

    public int readUB2() {
        int i = read() & 0xff;
        i |= (read() & 0xff) << 8;
        return i;
    }

    public int readUB3() {
        int i = read() & 0xff;
        i |= (read() & 0xff) << 8;
        i |= (read() & 0xff) << 16;
        return i;
    }

    public long readUB4() {
        long l = (long) (read() & 0xff);
        l |= (long) (read() & 0xff) << 8;
        l |= (long) (read() & 0xff) << 16;
        l |= (long) (read() & 0xff) << 24;
        return l;
    }

    public int readInt() {
        int i = read() & 0xff;
        i |= (read() & 0xff) << 8;
        i |= (read() & 0xff) << 16;
        i |= (read() & 0xff) << 24;
        return i;
    }

    public float readFloat() {
        return Float.intBitsToFloat(readInt());
    }

    public long readLong() {
        long l = (long) (read() & 0xff);
        l |= (long) (read() & 0xff) << 8;
        l |= (long) (read() & 0xff) << 16;
        l |= (long) (read() & 0xff) << 24;
        l |= (long) (read() & 0xff) << 32;
        l |= (long) (read() & 0xff) << 40;
        l |= (long) (read() & 0xff) << 48;
        l |= (long) (read() & 0xff) << 56;
        return l;
    }

    public double readDouble() {
        return Double.longBitsToDouble(readLong());
    }

    public long readLength() {
        int length = read() & 0xff;
        switch (length) {
        case 251:
            return NULL_LENGTH;
        case 252:
            return readUB2();
        case 253:
            return readUB3();
        case 254:
            return readLong();
        default:
            return length;
        }
    }

    private void arraycopy(byte[] dest) {
        arraycopy(dest, dest.length);
    }

    private void arraycopy(byte[] dest, int length) {
        for (int i = 0; i < length; i++) {
            dest[i] = read(position + i);
        }
    }

    public byte[] readBytes() {
        if (position >= length) {
            return EMPTY_BYTES;
        }
        byte[] ab = new byte[length - position];
        // System.arraycopy(data, position, ab, 0, ab.length);
        arraycopy(ab);
        position = length;
        return ab;
    }

    public byte[] readBytes(int length) {
        byte[] ab = new byte[length];
        // System.arraycopy(data, position, ab, 0, length);
        arraycopy(ab, length);
        position += length;
        return ab;
    }

    public byte[] readBytesWithNull() {
        if (position >= length) {
            return EMPTY_BYTES;
        }
        int offset = -1;
        for (int i = position; i < length; i++) {
            if (read(i) == 0) {
                offset = i;
                break;
            }
        }
        switch (offset) {
        case -1:
            byte[] ab1 = new byte[length - position];
            // System.arraycopy(b, position, ab1, 0, ab1.length);
            arraycopy(ab1);
            position = length;
            return ab1;
        case 0:
            position++;
            return EMPTY_BYTES;
        default:
            byte[] ab2 = new byte[offset - position];
            // System.arraycopy(b, position, ab2, 0, ab2.length);
            arraycopy(ab2);
            position = offset + 1;
            return ab2;
        }
    }

    public byte[] readBytesWithLength() {
        int length = (int) readLength();
        if (length == NULL_LENGTH) {
            return null;
        }
        if (length <= 0) {
            return EMPTY_BYTES;
        }

        byte[] ab = new byte[length];
        // System.arraycopy(data, position, ab, 0, ab.length);
        arraycopy(ab);
        position += length;
        return ab;
    }

    public String readString() {
        if (position >= length) {
            return null;
        }
        byte[] ab = new byte[length - position];
        arraycopy(ab);
        String s = new String(ab);
        position = length;
        return s;
    }

    public String readString(String charset) throws UnsupportedEncodingException {
        if (position >= length) {
            return null;
        }
        byte[] ab = new byte[length - position];
        arraycopy(ab);
        String s = new String(ab, charset);
        position = length;
        return s;
    }

    public String readStringWithNull() {
        if (position >= length) {
            return null;
        }
        int offset = -1;
        for (int i = position; i < length; i++) {
            if (read(i) == 0) {
                offset = i;
                break;
            }
        }
        if (offset == -1) {
            byte[] ab = new byte[length - position];
            arraycopy(ab);
            String s = new String(ab);
            position = length;
            return s;
        }
        if (offset > position) {
            byte[] ab = new byte[offset - position];
            arraycopy(ab);
            String s = new String(ab);
            position = offset + 1;
            return s;
        } else {
            position++;
            return null;
        }
    }

    public String readStringWithNull(String charset) throws UnsupportedEncodingException {
        if (position >= length) {
            return null;
        }
        int offset = -1;
        for (int i = position; i < length; i++) {
            if (read(i) == 0) {
                offset = i;
                break;
            }
        }
        switch (offset) {
        case -1:
            byte[] ab = new byte[length - position];
            arraycopy(ab);
            String s1 = new String(ab, charset);
            position = length;
            return s1;
        case 0:
            position++;
            return null;
        default:
            byte[] b = new byte[offset - position];
            arraycopy(b);
            String s2 = new String(b, charset);
            position = offset + 1;
            return s2;
        }
    }

    public String readStringWithLength() {
        int length = (int) readLength();
        if (length <= 0) {
            return null;
        }
        byte[] ab = new byte[length - position];
        arraycopy(ab);
        String s = new String(ab);
        position += length;
        return s;
    }

    public String readStringWithLength(String charset) throws UnsupportedEncodingException {
        int length = (int) readLength();
        if (length <= 0) {
            return null;
        }
        byte[] ab = new byte[length - position];
        arraycopy(ab);
        String s = new String(ab, charset);
        position += length;
        return s;
    }

    public java.sql.Time readTime() {
        move(6);
        int hour = read();
        int minute = read();
        int second = read();
        Calendar cal = getLocalCalendar();
        cal.set(0, 0, 0, hour, minute, second);
        return new Time(cal.getTimeInMillis());
    }

    public java.util.Date readDate() {
        byte length = read();
        int year = readUB2();
        byte month = read();
        byte date = read();
        int hour = read();
        int minute = read();
        int second = read();
        if (length == 11) {
            long nanos = readUB4();
            Calendar cal = getLocalCalendar();
            cal.set(year, --month, date, hour, minute, second);
            Timestamp time = new Timestamp(cal.getTimeInMillis());
            time.setNanos((int) nanos);
            return time;
        } else {
            Calendar cal = getLocalCalendar();
            cal.set(year, --month, date, hour, minute, second);
            return new java.sql.Date(cal.getTimeInMillis());
        }
    }

    public BigDecimal readBigDecimal() {
        String src = readStringWithLength();
        return src == null ? null : new BigDecimal(src);
    }

    public String toString() {
        return bufferArray.toString();
    }

    private static final ThreadLocal<Calendar> localCalendar = new ThreadLocal<Calendar>();

    private static final Calendar getLocalCalendar() {
        Calendar cal = localCalendar.get();
        if (cal == null) {
            cal = Calendar.getInstance();
            localCalendar.set(cal);
        }
        return cal;
    }

}