text:
proxyswitcher
=============

## New design for current version 2.0.0:

An Alfred.app workflow for switching proxy states of Mac OS X.

With this workflow, you will need not dive deepl into system preferences panel for toggling proxy states.

This workflow will show proxy options(need to pre-configured in a dot file) of current primary network service (usually the "Wi-Fi" serivce on a MacBook X).

### Requirements:

 1. Alfred.app with PowerPack activated.

### Install steps:

 1. Download the ProxySwitcher.alfredworkflow file.

 2. Double-click it.

### Usage:

Put a file names `.proxyswitcher.rc` to your home directory, edit this file like this:

```yaml
AutoDiscoveryProxy:   # AutoDiscoveryProxy has no options
AutoProxy:
  URL: "file://localhost/Applications/Safari.app/Contents/Resources/autoproxy.pac"  # URL of pac file
SocksProxy:
  Host: 127.0.0.1
  Port: 8080
  Auth: true
  Username: hello
  Password: 123123
HTTPProxy:
  Host: 127.0.0.1
  Port: 8080
  Auth: false
HTTPSProxy:
  Host: 127.0.0.1
  Port: 8080
  Auth: false
FTPProxy:
  Host: 127.0.0.1
  Port: 8080
  Auth: false
RTSPProxy:
  Host: 127.0.0.1
  Port: 8080
  Auth: false
GopherProxy:
  Host: 127.0.0.1
  Port: 8080
  Auth: false
```

The workflow will only show proxies already pre-configured in `.proxyswitcher.rc` file.

In Alfre.app text input field, type "proxy", move cursor to one proxy option and press enter, the worlflow will toggle state of that proxy option.

## Specification for version 1.0.0:

An Alfred.app workflow for switching proxy states of Mac OS X.

With this workflow, you will need not dive deepl into system preferences panel for toggling proxy states.

The searching keyword is names of the sevices, such as, `Wi-Fi`, `Ethernet`, etc.

By Default, ProxySwitcher will show all proxy options for each services.

If you have a file named `.proxyswitcher.rc` in your home dir, then ProxySwitcher will only show proxy options for those services with names in this file, each service name is in one single line.

 You could get all available service names via this command:  `networksetup -listallnetworkservices`

### Requirements:

 1. Alfred.app with PowerPack activated.

### Install steps:

 1. Download the ProxySwitcher.alfredworkflow file.

 2. Double-click it.

 3. If you want ProxySwitcher only show proxy options for Wi-Fi, then you can put one line `"Wi-Fi\n"`(without quotes, and `\n` means an UNIX new-line character) into `~/.proxyswitcher.rc`

### Screenshots:

 ![images](https://github.com/lululau/proxyswitcher/raw/master/screenshot.png)


text:
class Solution(object):
    def coinChange(self, coins, amount):
        """
        :type coins: List[int]
        :type amount: int
        :rtype: int
        """
        if amount < 1:
            return 0
        count = [0 for i in xrange(amount + 1)]
        self.helper(coins, amount, count)
        return count[amount]

    def helper(self, coins, remainder, count):
        if remainder <0:
            return -1
        if remainder == 0:
            return 0
        if count[remainder]!=0:
            return count[remainder]
        min = 9999999
        for c in coins:
            noOfCoinsNeeded = self.helper(coins, remainder - c, count)
            if noOfCoinsNeeded >=0 and noOfCoinsNeeded < min:
                min = 1 + noOfCoinsNeeded
        if min != 9999999:
            count [remainder] = min
        else:
            count [remainder] = -1
        return count[remainder]

redpajama_set_name: RedPajamaGithub


text:
![build](https://github.com/rkoval/alfred-aws-console-services-workflow/workflows/build/badge.svg)

A powerful workflow for quickly opening up AWS Console Services in your browser or searching for entities within them.

Supports Alfred 3 and 4

![AWS Console Services - Alfred Workflow Demo](demo.gif)

## Installation
- [Download and extract the latest release](https://github.com/rkoval/alfred-aws-console-services-workflow/releases)
- Open the .alfredworkflow file in Finder
- Make sure your AWS Credentials and Region are set in your `~/.aws/credentials` and `~/.aws/config` files, respectively. This workflow will use your `default` profile by default within these files. See [the official AWS docs](https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html#specifying-the-region) for more info on how to configure these

## Usage
To use, activate Alfred and type `aws` to trigger this workflow. From there:

- type any search term to search for services
- if the current service result has a 🗂 in the subtitle, press Tab to autocomplete into sub-services (for example, navigate to "Security Groups" within the "EC2" service)
- keep typing after autocompleting to filter sub-services
- if the current sub-service result has a 🔎 in the subtitle, press Tab again to start searching for its entities (for example, you can search for EC2 Instances when tabbed to `aws ec2 instances `)

At any time:
- press Enter to open the current result in your default browser
- press ⌘+Enter to copy the result's URL to clipboard.

*Note that you must be logged in for the page to open directly to your service*. See [this config file](console-services.yml) for the full list of supported services and their sub-services and [this file](searchers/searchers_by_service_id.go) for the list of supported searchers.

## Advanced Features

- [Fuzzy filtering](https://godoc.org/github.com/deanishe/awgo/fuzzy) a la Sublime Text is supported
- Configurable [workflow environment variables](https://www.alfredapp.com/help/workflows/advanced/variables/#environment)
  - Search alias – If a sub-service has a ⭐ in the subtitle, you can use `,` as an alias for it to more quickly search for that entity. For example, in this workflow, the EC2 service's default entity is an EC2 instance, so `aws ec2 ,searchterm` is a shorter alias for `aws ec2 instances searchterm`. You can customize this alias by setting the `ALFRED_AWS_CONSOLE_SERVICES_WORKFLOW_SEARCH_ALIAS` environment variable to any other string.
  - Region override - By default, searchers will use the region configured in your `~/.aws/config` file. However, you can override this on a single query basis by typing `$`. This workflow will then populate a list of regions to select for this query. You can customize this alias by setting the `ALFRED_AWS_CONSOLE_SERVICES_OVERRIDE_AWS_REGION_ALIAS` environment variable to any other string.
  - Profile override - By default, searchers will use the default profile configured in your `~/.aws/credentials` file. However, you can override this on a single query basis by typing `@`. This workflow will then populate the list of profiles defined in your `~/.aws/credentials` file. You can customize this alias by setting the `ALFRED_AWS_CONSOLE_SERVICES_OVERRIDE_AWS_PROFILE_ALIAS` environment variable to any other string.
  - Cache expiration age – Sub-service entity searching makes heavy use of caching to make filtering performant and to prevent handling big requests/responses to/from AWS on every execution. The cache expiration age for each entity is set to 3 minutes by default. If you find that this is too short/long for your usage, you can set the `ALFRED_AWS_CONSOLE_SERVICES_WORKFLOW_MAX_CACHE_AGE_SECONDS` environment variable to the number of seconds that better suits your need.
  - Custom AWS Management Console domain – If your AWS account's management console lives at a domain that is not the standard "console.amazonaws.com", you can set a custom domain with the `ALFRED_AWS_CONSOLE_SERVICES_WORKFLOW_AWS_CONSOLE_DOMAIN` environment variable. This workflow will then populate all relevant URLs with that domain when opening links.
  - AWS settings – You can override any/all AWS configuration values which the underlying AWS library should respect.

## Contributing

See [this README](CONTRIBUTING.md)

## Packaging for Release

See [this README](release_tools/README.md)

## Donating

Like this workflow? Consider donating! 😻

- [Patreon](https://www.patreon.com/rkoval_alfred_aws_console_services_workflow)
-
- [ryankoval.pizza](https://ryankoval.pizza)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>LIBM: trunc</title>

<meta name="description" content="LIBM: trunc">
<meta name="keywords" content="LIBM: trunc">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Document-Index.html#Document-Index" rel="index" title="Document Index">
<link href="Document-Index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Math.html#Math" rel="up" title="Math">
<link href="Complex.html#Complex" rel="next" title="Complex">
<link href="tanh.html#tanh" rel="prev" title="tanh">

Previous: tanh, Up: Math   [Contents][Index]

1.59 trunc, truncf—round to integer, towards zero

Synopsis

#include <math.h>
double trunc(double <var>x</var>);
float truncf(float <var>x</var>);

Description

The trunc functions round their argument to the integer value, in
floating format, nearest to but no larger in magnitude than the
argument, regardless of the current rounding direction.  (While the
"inexact" floating-point exception behavior is unspecified by the C
standard, the trunc functions are written so that "inexact" is not
raised if the result does not equal the argument, which behavior is as
recommended by IEEE 754 for its related functions.)

Returns

<var>x</var> truncated to an integral value.

Portability

ANSI C, POSIX


text:
<?php

use Brainformatik\CalDAV\Connection\Client;
use \Brainformatik\CalDAV\Helper\BaseTestCase;

class ClientTest extends BaseTestCase {

    /**
     * @var array
     */
    protected static $dummyData = [
        'baseUri' => 'http://127.0.0.1/caldav/',
        'userName' => 'defaultUser',
        'password' => 'defaultPassword'
    ];

    public function testGetBaseUrl() {
        $client = new Client(self::$dummyData);
        $this->assertEquals(self::$dummyData['baseUri'], $client->getBaseUrl());
    }

    public function testIsValidConnection() {
        $clientMockInvalid = $this->getMockBuilder(Client::class)
            ->setMethods([
                'options'
            ])
            ->setConstructorArgs([self::$dummyData])
            ->getMock();
        $clientMockInvalid->method('options')->will($this->returnValue([]));

        $this->assertFalse($clientMockInvalid->isValidConnection());

        $clientMockValid = $this->getMockBuilder(Client::class)
            ->setMethods([
                'options'
            ])
            ->setConstructorArgs([self::$dummyData])
            ->getMock();
        $clientMockValid->method('options')->will($this->returnValue(['calendar-access']));

        $this->assertTrue($clientMockValid->isValidConnection());
    }
}


text:
About {#mainpage}
=================

For more information on MNE-CPP please visit https://mne-cpp.github.io/.

A guide on how to integrate this documentation into the QtCreator can be found [here](https://mne-cpp.github.io/pages/contribute/conv_style.html).


text:
require_relative "token"

module Lex
  # Represents token definition
  class Lexeme
    attr_reader :name, :pattern, :action

    def initialize(name, pattern, &action)
      @name    = name
      @pattern = pattern
      @action  = action
    end

    def match(scanner)
      match = scanner.check(pattern)
      if match
        return Token.new(name, match.to_s, &action)
      end
      match
    end

    # @api public
    def ==(other)
      @name == other.name
    end
  end # Lexeme
end # Lex


text:
<Alloy>
	<View id="imageListItem" onClick="onClick">
		<ImageView id="image" />
		<View id="markerHolder" onClick="onMarkerClick">
			<View id="marker" />
		</View>
		<View id="titles" layout="vertical" />
	</View>
</Alloy>


text:
package cucumber.examples.spring.txn;

import cucumber.api.java.en.Given;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import static org.junit.Assert.assertTrue;

import java.util.List;

public class UserStepdefs {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private MessageRepository messageRepository;

    private User user;

    public void thereIsAuser() {
        user = new User();
        user.setUsername("testuser");
        userRepository.save(user);
    }

    @Given("^a User has posted the following messages:$")
    public void a_User_has_posted_the_following_messages(List<Message> messages) throws Throwable {
        thereIsAuser();
        for (Message m : messages) {
            m.setAuthor(user);
            messageRepository.save(m);
        }
	assertTrue("No transaction is active",
		   TransactionSynchronizationManager.isActualTransactionActive());
    }
}


text:
import {
  async,
  inject,
  TestBed,
  ComponentFixture
} from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';

import { Speaker } from '../speaker/speaker';

// Load the implementations that should be tested
import { SpeakerListComponent } from './speaker-list.component';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { ActivatedRouteStub } from '../../app.routes-stub';

describe("SpeakerList", () => {

  let comp: SpeakerListComponent;
  let fixture: ComponentFixture<SpeakerListComponent>;
  let de: DebugElement;
  let el: HTMLElement;
  let expectedSpeaker: Speaker;
  let activatedRoute: ActivatedRouteStub;
  let mockSpeakers: Speaker[];

  beforeEach(() => {
    activatedRoute = new ActivatedRouteStub();
    mockSpeakers = [{
      id: 1,
      name: "Test",
      surname: "Testy",
      company: "Test Corp",
      img: "speaker-1",
      desc: "Lorem ipsum"
    }, {
      id: 2,
      name: "Temp",
      surname: "Temppy",
      company: "Temp Corp",
      img: "speaker-2",
      desc: "Lorem ipsum"
    }];
    activatedRoute.testData = { speakers: mockSpeakers };
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [SpeakerListComponent],
      providers: [{ provide: ActivatedRoute, useValue: activatedRoute }],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SpeakerListComponent);
    comp = fixture.componentInstance;
  });

  it('should set speakers', () => {
    expect(comp.speakers).not.toBeDefined();
    fixture.detectChanges();

    expect(comp.speakers).toEqual(mockSpeakers);
  });

  it('should not have selectedSpeaker', () => {
    fixture.detectChanges();
    expect(comp.selectedSpeaker).not.toBeDefined();
  });

  it('should select speaker when speaker-item clicked', () => {
    fixture.detectChanges();
    expect(comp.speakers).toEqual(mockSpeakers);
    expect(comp.selectedSpeaker).not.toBeDefined();

    de = fixture.debugElement.queryAll(By.css('speaker-item'))[1];
    de.triggerEventHandler("click", null);

    expect(comp.selectedSpeaker).toBe(comp.speakers[1]);
  })
});


text:
package tech.receipts.data.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import javax.inject.Inject;

import tech.receipts.injection.ApplicationContext;
import timber.log.Timber;

import static tech.receipts.data.database.DbConstants.COLUMN_POS_NAME;
import static tech.receipts.data.database.DbConstants.COLUMN_POS_SCORE;
import static tech.receipts.data.database.DbConstants.COLUMN_POS_TAX_NUMBER;
import static tech.receipts.data.database.DbConstants.COLUMN_TAX_NUMBER;
import static tech.receipts.data.database.DbConstants.COLUMN_TAX_SCORE;
import static tech.receipts.data.database.DbConstants.DATABASE_NAME;
import static tech.receipts.data.database.DbConstants.POS_TABLE_NAME;
import static tech.receipts.data.database.DbConstants.TAX_TABLE_NAME;

public class AutocompleteDbOpenHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;

    private static final String SQL_TAX_TABLE_CREATE =
            "CREATE TABLE " + TAX_TABLE_NAME + " (" +
                    COLUMN_TAX_NUMBER + " TEXT PRIMARY KEY, " +
                    COLUMN_TAX_SCORE + " LONG);";

    private static final String SQL_POS_TABLE_CREATE =
            "CREATE TABLE " + POS_TABLE_NAME + " (" +
                    COLUMN_POS_TAX_NUMBER + " TEXT, " +
                    COLUMN_POS_SCORE + " LONG, " +
                    COLUMN_POS_NAME + " TEXT," +
                    "PRIMARY KEY(" + COLUMN_POS_TAX_NUMBER + ", " + COLUMN_POS_NAME + "));";

    private static final String SQL_TAX_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TAX_TABLE_NAME;
    private static final String SQL_POS_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + POS_TABLE_NAME;

    public static final String SQL_GET_TAX_COLLECTION = "SELECT " + COLUMN_TAX_NUMBER + " FROM " + TAX_TABLE_NAME + " ORDER BY " + COLUMN_TAX_NUMBER + " ASC";
    public static final String SQL_GET_POS_COLLECTION = "SELECT " + COLUMN_POS_NAME + "," + COLUMN_POS_TAX_NUMBER + " FROM " + POS_TABLE_NAME + " ORDER BY " + COLUMN_POS_NAME + " ASC";

    public static final String SQL_UPDATE_TAX = "UPDATE " + TAX_TABLE_NAME + " SET " + COLUMN_TAX_SCORE + " = " + COLUMN_TAX_SCORE + " + 1 WHERE " + COLUMN_TAX_NUMBER + " = ?";
    public static final String SQL_UPDATE_POS = "UPDATE " + POS_TABLE_NAME + " SET " + COLUMN_POS_SCORE + " = " + COLUMN_POS_SCORE + " + 1 WHERE " + COLUMN_POS_NAME + " = ? AND " + COLUMN_POS_TAX_NUMBER + " = ?";

    @Inject
    public AutocompleteDbOpenHelper(@ApplicationContext Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Timber.e("Create databases");
        db.beginTransaction();
        try {
            //Uncomment line below if you want to enable foreign keys
            //db.execSQL("PRAGMA foreign_keys=ON;");
            db.execSQL(SQL_TAX_TABLE_CREATE);
            db.execSQL(SQL_POS_TABLE_CREATE);
            //Add other tables here
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_TAX_DELETE_ENTRIES);
        db.execSQL(SQL_POS_DELETE_ENTRIES);
        onCreate(db);
    }
}


text:
"""
Benchmark of how long calculating shakemaps actually takes, based on dummy data.

.. note::
    The code in here should *NOT* ever be used in a real scenario as e.g.
    generating the same shakemap multiple times as it happens in the interpolate
    method is idiotic in a normal scenario - it is only done for testing out the
    speed the api can currently generate shakemaps!
"""

from eqep.data.eqdata import EQData
from eqep.interpolation.rbf_pgvinterpolator import RbfPGVInterpolator
from eqep.shakemap.display.styles import *
from eqep.shakemap.shakemap import ShakeMap
from eqep.shakemap.display.scales import *
import random
from time import clock

def generate_data(amount):
    """Generates a dummy EQData object with nonsense-data

    Parameters
    ----------
    amount : int
        amount of data inside the object

    Returns
    -------
    EQData
        with the specified amount of data
    """

    names = []
    longs = np.array([])
    lats = np.array([])
    values = np.array([])

    for number in range(amount):
        names.append("name{}".format(number))
        longs = np.append(longs, number)
        lats = np.append(lats, number)
        values = np.append(values, random.randint(0, 100))

    return EQData(values, longs, lats, names)

def interpolate(data, count_maps, reinterpolate, depth):
    """Interpolates all of an EQData object.

    Parameters
    ----------
    data : EQData
        holding all necessary data
    count_maps : int
        how often to generate the same shakemap (just for benchmarking
        purposes)
    reinterpolate : bool
        whether to reinterpolate the image (much smoother or not)
    depth : tuple of int
        depth of the grid to be interpolated
    """

    durations = []
    start = clock()

    # ShakeMap settings
    longs_range = (min(data.longs), max(data.longs))
    lats_range = (min(data.lats), max(data.lats))

    for map_num in range(count_maps):  # amount of shakemaps
        start_loop = clock()
        sm = ShakeMap(data, RbfPGVInterpolator(), RainbowSMScale(),
                      PlainStyle())
        if depth is not None:
            sm.calc(longs_range, lats_range, steps=depth)
        else:
            sm.calc(longs_range, lats_range)

        if reinterpolate is True:  # with reinterpolation
            sm.calc_graphics()
        elif reinterpolate is False:  # without
            sm.calc_graphics(interpolation=None)
        del sm
        end_loop = clock()
        durations.append(end_loop - start_loop)
    end = clock()
    return (end - start), durations

def benchmark(amount_data, amount_maps, reinterpolate, depth):
    """Benchmarks the duration a given configuration takes and outputs min, max,
    average and overall time.
    """

    data = generate_data(amount_data)
    info = ("Started with %3s data points, reinterpolate: %5s, depth: %s" %
            (len(data.pgvs), reinterpolate, depth))
    overall, durations = interpolate(generate_data(100), amount_maps,
                                     reinterpolate, depth)
    val = ('Took: %07.4fs, on average %07.4fs, shortest took: %07.4fs, longest '
           'took: %07.4fs' % (round(overall, 4),
                              round(np.average(durations), 4),
                              round(min(durations), 4),
                              round(max(durations), 4)))
    print(info, "\n", val)

print("Starting benchmark. Please stand by.. \n")

benchmark(20, 10, True, (100, 100))

benchmark(20, 10, True, (1000, 1000))

benchmark(20, 10, False, (100, 100))

benchmark(20, 10, False, (1000, 1000))

benchmark(100, 20, True, (100, 100))

benchmark(100, 20, True, (1000, 1000))

benchmark(100, 20, False, (100, 100))

benchmark(100, 20, False, (1000, 1000))


text:
layout: postag
title: 'VERB'
shortdef: 'verb'
---

This document is a placeholder for the language-specific documentation
for `VERB`.


text:
/* eslint-disable @typescript-eslint/no-unused-vars */

import { FieldBlockDefinition } from './FieldBlock';
import {
  StreamBlockDefinition,
  StreamBlockValidationError,
} from './StreamBlock';

import $ from 'jquery';
window.$ = $;

window.comments = {
  getContentPath: jest.fn(),
};

// Define some callbacks in global scope that can be mocked in tests
let constructor = (_widgetName, _name, _id, _initialState) => {};
let setState = (_widgetName, _state) => {};
let getState = (_widgetName) => {};
let getValue = (_widgetName) => {};
let focus = (_widgetName) => {};

class DummyWidgetDefinition {
  constructor(widgetName) {
    this.widgetName = widgetName;
  }

  render(placeholder, name, id, initialState) {
    const widgetName = this.widgetName;
    constructor(widgetName, { name, id, initialState });

    $(placeholder).replaceWith(
      `<p name="${name}" id="${id}">${widgetName}</p>`,
    );
    return {
      setState(state) {
        setState(widgetName, state);
      },
      getState() {
        getState(widgetName);
        return `state: ${widgetName} - ${name}`;
      },
      getValue() {
        getValue(widgetName);
        return `value: ${widgetName} - ${name}`;
      },
      focus() {
        focus(widgetName);
      },
      idForLabel: id,
    };
  }
}

class ValidationError {
  constructor(messages) {
    this.messages = messages;
  }
}

describe('telepath: wagtail.blocks.StreamBlock', () => {
  let boundBlock;

  beforeEach(() => {
    // Create mocks for callbacks
    constructor = jest.fn();
    setState = jest.fn();
    getState = jest.fn();
    getValue = jest.fn();
    focus = jest.fn();

    // Define a test block
    const blockDef = new StreamBlockDefinition(
      '',
      [
        [
          '',
          [
            new FieldBlockDefinition(
              'test_block_a',
              new DummyWidgetDefinition('Block A widget'),
              {
                label: 'Test Block A',
                required: true,
                icon: 'placeholder',
                classname:
                  'field char_field widget-text_input fieldname-test_charblock',
              },
            ),
            new FieldBlockDefinition(
              'test_block_b',
              new DummyWidgetDefinition('Block B widget'),
              {
                label: 'Test Block B',
                required: true,
                icon: 'pilcrow',
                classname:
                  'field char_field widget-admin_auto_height_text_input fieldname-test_textblock',
              },
            ),
          ],
        ],
      ],
      {
        test_block_a: 'Block A options',
        test_block_b: 'Block B options',
      },
      {
        label: '',
        required: true,
        icon: 'placeholder',
        classname: null,
        helpText: 'use plenty of these',
        helpIcon: '
?
',
        maxNum: null,
        minNum: null,
        blockCounts: {},
        strings: {
          MOVE_UP: 'Move up',
          MOVE_DOWN: 'Move down',
          DELETE: 'Delete',
          DUPLICATE: 'Duplicate',
          ADD: 'Add',
        },
      },
    );

    // Render it
    document.body.innerHTML = '

';
    boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
    ]);
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toMatchSnapshot();
  });

  test('it renders menus on opening', () => {
    boundBlock.inserters[1].open();
    expect(document.body.innerHTML).toMatchSnapshot();
  });

  test('Widget constructors are called with correct parameters', () => {
    expect(constructor.mock.calls.length).toBe(2);

    expect(constructor.mock.calls[0][0]).toBe('Block A widget');
    expect(constructor.mock.calls[0][1]).toEqual({
      name: 'the-prefix-0-value',
      id: 'the-prefix-0-value',
      initialState: 'First value',
    });

    expect(constructor.mock.calls[1][0]).toBe('Block B widget');
    expect(constructor.mock.calls[1][1]).toEqual({
      name: 'the-prefix-1-value',
      id: 'the-prefix-1-value',
      initialState: 'Second value',
    });
  });

  test('getValue() calls getValue() on widget for both values', () => {
    const value = boundBlock.getValue();
    expect(getValue.mock.calls.length).toBe(2);
    expect(value).toEqual([
      {
        id: '1',
        type: 'test_block_a',
        value: 'value: Block A widget - the-prefix-0-value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'value: Block B widget - the-prefix-1-value',
      },
    ]);
  });

  test('getState() calls getState() on all widgets', () => {
    const state = boundBlock.getState();
    expect(getState.mock.calls.length).toBe(2);
    expect(state).toEqual([
      {
        id: '1',
        type: 'test_block_a',
        value: 'state: Block A widget - the-prefix-0-value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'state: Block B widget - the-prefix-1-value',
      },
    ]);
  });

  test('setState() creates new widgets', () => {
    boundBlock.setState([
      {
        id: '1',
        type: 'test_block_a',
        value: 'Changed first value',
      },
      {
        id: '3',
        type: 'test_block_b',
        value: 'Third value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Changed second value',
      },
    ]);

    // Includes the two initial calls, plus the three new ones
    expect(constructor.mock.calls.length).toBe(5);

    expect(constructor.mock.calls[2][0]).toBe('Block A widget');
    expect(constructor.mock.calls[2][1]).toEqual({
      name: 'the-prefix-0-value',
      id: 'the-prefix-0-value',
      initialState: 'Changed first value',
    });

    expect(constructor.mock.calls[3][0]).toBe('Block B widget');
    expect(constructor.mock.calls[3][1]).toEqual({
      name: 'the-prefix-1-value',
      id: 'the-prefix-1-value',
      initialState: 'Third value',
    });

    expect(constructor.mock.calls[4][0]).toBe('Block B widget');
    expect(constructor.mock.calls[4][1]).toEqual({
      name: 'the-prefix-2-value',
      id: 'the-prefix-2-value',
      initialState: 'Changed second value',
    });

    // Let's get the state now to make sure the initial widgets are gone
    const state = boundBlock.getState();
    expect(getState.mock.calls.length).toBe(3);
    expect(state).toEqual([
      {
        id: '1',
        type: 'test_block_a',
        value: 'state: Block A widget - the-prefix-0-value',
      },
      {
        id: '3',
        type: 'test_block_b',
        value: 'state: Block B widget - the-prefix-1-value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'state: Block B widget - the-prefix-2-value',
      },
    ]);
  });

  test('focus() calls focus() on first widget', () => {
    boundBlock.focus();
    expect(focus.mock.calls.length).toBe(1);
    expect(focus.mock.calls[0][0]).toBe('Block A widget');
  });

  test('blocks can be reordered upward', () => {
    boundBlock.moveBlock(1, 0);
    expect(document.body.innerHTML).toMatchSnapshot();
  });

  test('blocks can be reordered downward', () => {
    boundBlock.moveBlock(0, 1);
    expect(document.body.innerHTML).toMatchSnapshot();
  });

  test('blocks can be duplicated', () => {
    boundBlock.duplicateBlock(1);

    expect(constructor.mock.calls.length).toBe(3);

    expect(constructor.mock.calls[2][0]).toBe('Block B widget');
    expect(constructor.mock.calls[2][1]).toEqual({
      name: 'the-prefix-2-value',
      id: 'the-prefix-2-value',
      // new block gets state from the one being duplicated
      initialState: 'state: Block B widget - the-prefix-1-value',
    });

    expect(document.body.innerHTML).toMatchSnapshot();
  });

  test('setError renders error messages', () => {
    boundBlock.setError([
      new StreamBlockValidationError(
        [
          /* non-block error */
          new ValidationError(['At least three blocks are required']),
        ],
        {
          /* block error */
          1: [new ValidationError(['Not as good as the first one'])],
        },
      ),
    ]);
    expect(document.body.innerHTML).toMatchSnapshot();
  });
});

describe('telepath: wagtail.blocks.StreamBlock with labels that need escaping', () => {
  let boundBlock;

  beforeEach(() => {
    // Create mocks for callbacks
    constructor = jest.fn();
    setState = jest.fn();
    getState = jest.fn();
    getValue = jest.fn();
    focus = jest.fn();

    // Define a test block
    const blockDef = new StreamBlockDefinition(
      '',
      [
        [
          '',
          [
            new FieldBlockDefinition(
              'test_block_a',
              new DummyWidgetDefinition('Block A widget'),
              {
                label: 'Test Block ',
                required: true,
                icon: 'placeholder',
                classname:
                  'field char_field widget-text_input fieldname-test_charblock',
              },
            ),
            new FieldBlockDefinition(
              'test_block_b',
              new DummyWidgetDefinition('Block B widget'),
              {
                label: 'Test Block ',
                required: true,
                icon: 'pilcrow',
                classname:
                  'field char_field widget-admin_auto_height_text_input fieldname-test_textblock',
              },
            ),
          ],
        ],
      ],
      {
        test_block_a: 'Block A options',
        test_block_b: 'Block B options',
      },
      {
        label: '',
        required: true,
        icon: 'placeholder',
        classname: null,
        helpText: 'use plenty of these',
        helpIcon: '
?
',
        maxNum: null,
        minNum: null,
        blockCounts: {},
        strings: {
          MOVE_UP: 'Move up',
          MOVE_DOWN: 'Move down',
          DELETE: 'Delete & kill with fire',
          DUPLICATE: 'Duplicate',
          ADD: 'Add',
        },
      },
    );

    // Render it
    document.body.innerHTML = '

';
    boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
    ]);
  });

  test('it renders correctly', () => {
    boundBlock.inserters[0].open();
    expect(document.body.innerHTML).toMatchSnapshot();
  });
});

describe('telepath: wagtail.blocks.StreamBlock with maxNum set', () => {
  // Define a test block
  const blockDef = new StreamBlockDefinition(
    '',
    [
      [
        '',
        [
          new FieldBlockDefinition(
            'test_block_a',
            new DummyWidgetDefinition('Block A widget'),
            {
              label: 'Test Block ',
              required: true,
              icon: 'placeholder',
              classname:
                'field char_field widget-text_input fieldname-test_charblock',
            },
          ),
          new FieldBlockDefinition(
            'test_block_b',
            new DummyWidgetDefinition('Block B widget'),
            {
              label: 'Test Block ',
              required: true,
              icon: 'pilcrow',
              classname:
                'field char_field widget-admin_auto_height_text_input fieldname-test_textblock',
            },
          ),
        ],
      ],
    ],
    {
      test_block_a: 'Block A options',
      test_block_b: 'Block B options',
    },
    {
      label: '',
      required: true,
      icon: 'placeholder',
      classname: null,
      helpText: 'use plenty of these',
      helpIcon: '
?
',
      maxNum: 3,
      minNum: null,
      blockCounts: {},
      strings: {
        MOVE_UP: 'Move up',
        MOVE_DOWN: 'Move down',
        DELETE: 'Delete & kill with fire',
        DUPLICATE: 'Duplicate',
        ADD: 'Add',
      },
    },
  );

  const assertCanAddBlock = () => {
    // Test duplicate button
    // querySelector always returns the first element it sees so this only checks the first block
    expect(
      document
        .querySelector('button[title="Duplicate"]')
        .getAttribute('disabled'),
    ).toBe(null);

    // Test menu
    expect(
      document
        .querySelector('button[data-streamblock-menu-open]')
        .getAttribute('disabled'),
    ).toBe(null);
  };

  const assertCannotAddBlock = () => {
    // Test duplicate button
    // querySelector always returns the first element it sees so this only checks the first block
    expect(
      document
        .querySelector('button[title="Duplicate"]')
        .getAttribute('disabled'),
    ).toEqual('disabled');

    // Test menu
    expect(
      document
        .querySelector('button[data-streamblock-menu-open]')
        .getAttribute('disabled'),
    ).toEqual('disabled');
  };

  test('test can add block when under limit', () => {
    document.body.innerHTML = '

';
    const boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
    ]);
    boundBlock.inserters[0].open();

    assertCanAddBlock();
  });

  test('initialising at maxNum disables adding new block and duplication', () => {
    document.body.innerHTML = '

';
    const boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
      {
        id: '3',
        type: 'test_block_b',
        value: 'Third value',
      },
    ]);
    boundBlock.inserters[0].open();

    assertCannotAddBlock();
  });

  test('insert disables new block', () => {
    document.body.innerHTML = '

';
    const boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
    ]);
    boundBlock.inserters[0].open();

    assertCanAddBlock();

    boundBlock.insert(
      {
        id: '3',
        type: 'test_block_b',
        value: 'Third value',
      },
      2,
    );

    assertCannotAddBlock();
  });

  test('delete enables new block', () => {
    document.body.innerHTML = '

';
    const boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
      {
        id: '3',
        type: 'test_block_b',
        value: 'Third value',
      },
    ]);
    boundBlock.inserters[0].open();

    assertCannotAddBlock();

    boundBlock.deleteBlock(2);

    assertCanAddBlock();
  });
});

describe('telepath: wagtail.blocks.StreamBlock with blockCounts.max_num set', () => {
  // Define a test block
  const blockDef = new StreamBlockDefinition(
    '',
    [
      [
        '',
        [
          new FieldBlockDefinition(
            'test_block_a',
            new DummyWidgetDefinition('Block A widget'),
            {
              label: 'Test Block ',
              required: true,
              icon: 'placeholder',
              classname:
                'field char_field widget-text_input fieldname-test_charblock',
            },
          ),
          new FieldBlockDefinition(
            'test_block_b',
            new DummyWidgetDefinition('Block B widget'),
            {
              label: 'Test Block ',
              required: true,
              icon: 'pilcrow',
              classname:
                'field char_field widget-admin_auto_height_text_input fieldname-test_textblock',
            },
          ),
        ],
      ],
    ],
    {
      test_block_a: 'Block A options',
      test_block_b: 'Block B options',
    },
    {
      label: '',
      required: true,
      icon: 'placeholder',
      classname: null,
      helpText: 'use plenty of these',
      helpIcon: '
?
',
      maxNum: null,
      minNum: null,
      blockCounts: {
        test_block_a: {
          max_num: 2,
        },
      },
      strings: {
        MOVE_UP: 'Move up',
        MOVE_DOWN: 'Move down',
        DELETE: 'Delete & kill with fire',
        DUPLICATE: 'Duplicate',
        ADD: 'Add',
      },
    },
  );

  const assertCanAddBlock = () => {
    // Test duplicate button
    // querySelector always returns the first element it sees so this only checks the first block
    expect(
      document
        .querySelector('button[title="Duplicate"]')
        .getAttribute('disabled'),
    ).toBe(null);

    // Test menu item
    expect(
      document
        .querySelector('button.action-add-block-test_block_a')
        .getAttribute('disabled'),
    ).toBe(null);
  };

  const assertCannotAddBlock = () => {
    // Test duplicate button
    // querySelector always returns the first element it sees so this only checks the first block
    expect(
      document
        .querySelector('button[title="Duplicate"]')
        .getAttribute('disabled'),
    ).toEqual('disabled');

    // Test menu item
    expect(
      document
        .querySelector('button.action-add-block-test_block_a')
        .getAttribute('disabled'),
    ).toEqual('disabled');
  };

  test('single instance allows creation of new block and duplication', () => {
    document.body.innerHTML = '

';
    const boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
    ]);
    boundBlock.inserters[0].open();

    assertCanAddBlock();
  });

  test('initialising at max_num disables adding new block of that type and duplication', () => {
    document.body.innerHTML = '

';
    const boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
      {
        id: '3',
        type: 'test_block_a',
        value: 'Third value',
      },
    ]);
    boundBlock.inserters[0].open();

    assertCannotAddBlock();
  });

  test('insert disables new block', () => {
    document.body.innerHTML = '

';
    const boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
    ]);
    boundBlock.inserters[0].open();

    assertCanAddBlock();

    boundBlock.insert(
      {
        id: '3',
        type: 'test_block_a',
        value: 'Third value',
      },
      2,
    );

    assertCannotAddBlock();
  });

  test('delete enables new block', () => {
    document.body.innerHTML = '

';
    const boundBlock = blockDef.render($('#placeholder'), 'the-prefix', [
      {
        id: '1',
        type: 'test_block_a',
        value: 'First value',
      },
      {
        id: '2',
        type: 'test_block_b',
        value: 'Second value',
      },
      {
        id: '3',
        type: 'test_block_a',
        value: 'Third value',
      },
    ]);
    boundBlock.inserters[0].open();

    assertCannotAddBlock();

    boundBlock.deleteBlock(2);

    assertCanAddBlock();
  });
});


text:
import jsdom from 'jsdom';

describe('bundle', function() {
    it('should correctly wire-up all the dependencies via their UMD-exposed globals (w/o d3-transition)', function(done) {
        jsdom.env({
            html: '',
            virtualConsole: jsdom.createVirtualConsole().sendTo(console),
            scripts: [
                './node_modules/d3-selection/build/d3-selection.js',
                './build/d3fc-data-join.js'
            ],
            done: (_, win) => {
                const dataJoin = win.fc.dataJoin();
                const selection = win.d3.select(win.document);
                dataJoin(selection, []);
                done();
            }
        });
    });
    it('should correctly wire-up all the dependencies via their UMD-exposed globals (w/ d3-transition)', function(done) {
        jsdom.env({
            html: '',
            virtualConsole: jsdom.createVirtualConsole().sendTo(console),
            scripts: [
                './node_modules/d3-selection/build/d3-selection.js',
                './node_modules/d3-color/build/d3-color.js',
                './node_modules/d3-dispatch/build/d3-dispatch.js',
                './node_modules/d3-ease/build/d3-ease.js',
                './node_modules/d3-interpolate/build/d3-interpolate.js',
                './node_modules/d3-timer/build/d3-timer.js',
                './node_modules/d3-transition/build/d3-transition.js',
                './build/d3fc-data-join.js'
            ],
            done: (_, win) => {
                const dataJoin = win.fc.dataJoin();
                const selection = win.d3.select(win.document);
                dataJoin(selection, []);
                done();
            }
        });
    });
});


text:
package org.apache.camel.component.jetty;

import java.util.concurrent.Executor;

import javax.net.ssl.SSLContext;

import org.apache.camel.util.ObjectHelper;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;

public abstract class CamelHttpClient extends HttpClient {

    private boolean supportRedirect;

    public CamelHttpClient(SslContextFactory sslContextFactory) {
        super(sslContextFactory);
    }

    @Deprecated
    /**
     * It does nothing here, please setup SslContextFactory directly, it will be removed in Camel 2.16.0
     * @param context
     */
    public void setSSLContext(SSLContext context) {
        // do nothing here, please setup SslContextFactory directly.
    }

    @Override
    protected void doStart() throws Exception {
        if (!hasThreadPool()) {
            // if there is no thread pool then create a default thread pool using daemon threads
            QueuedThreadPool qtp = new QueuedThreadPool();
            // 16 max threads is the default in the http client
            qtp.setMaxThreads(16);
            qtp.setDaemon(true);
            // let the thread names indicate they are from the client
            qtp.setName("CamelJettyClient(" + ObjectHelper.getIdentityHashCode(this) + ")");
            setThreadPoolOrExecutor(qtp);
        }
        super.doStart();
    }

    protected abstract boolean hasThreadPool();

    protected abstract void setThreadPoolOrExecutor(Executor pool);

    public abstract void setProxy(String host, int port);

    public boolean isSupportRedirect() {
        return supportRedirect;
    }

    public void setSupportRedirect(boolean supportRedirect) {
        this.supportRedirect = supportRedirect;
    }

    public abstract String getProxyHost();

    public abstract int getProxyPort();

}


text:
// ---------------------
// Code for example 3.26
// ---------------------

package chap03

import adt._

object Ex26 {

  // Naive version
  // Causes stack overflow with very deep trees
  def maximumNaive[A: Numeric](t: Tree[A]): A = {
    val maxOp: (A, A) => A = implicitly[Numeric[A]].max _
    t match {
      case Leaf(x) => x
      case Branch(l, r) => maxOp(maximum(l), maximum(r))
    }
  }

  // Tail recursive version
  def maximum[A: Numeric](t: Tree[A]): A = {
    val maxOp: (A, A) => A = implicitly[Numeric[A]].max _

    // This should be the smallest possible value for
    // Numeric type A
    // However, Numeric.MinValue is not defined in Scala,
    // so we are using Int.MinValue
    // (it will fail for values lower that Int.MinValue, e.g.
    // with Doubles smaller than Int.MinValue)
    val zero = implicitly[Numeric[A]].fromInt(Int.MinValue)

    @annotation.tailrec
    def loop(t1: List[Tree[A]], m: A): A = {
      t1 match {
        case Nil => m
        case Leaf(x) :: lt => loop(lt, maxOp(m, x))
        case Branch(l, r) :: lt => loop(l :: r :: lt, m)
      }
    }

    loop(List(t), zero)
  }
}


text:
/* global isPWE */
'use strict';

// Element for the project list
var projectList = $('#project-list'),
  projectBox = $('#project-box');

// Hide projectBox if there is no project
if ($('#project-list>li').length === 0) {
  projectBox.hide();
}

// Code for new project
$('#new-project').on('show.bs.modal', function() {
  // Dialog for the project type
  var projectTypeDlg = $('#project-type');

  // Dialog for the project format
  var projectFormatDlg = $('#project-format');

  // Dialog for the profile and version
  var profileVersionDlg = $('#profile-version');

  // Dialog for the template or sample
  var templateSampleDlg = $('#template-sample');

  // Dialog for the project properties
  var propertyDlg = $('#project-property');

  // Variable for the project
  var currentProcess = 'project-type',
    emptyProject = false,
    projectFormat = 'template',
    projectProfile = 'mobile',
    projectVersion = '4.0',
    projectType = 'wasm',
    projectName = '',
    projectDescription = '',
    templateName = '';

  // Button for the dialog
  var backBtn = $('#back-button'),
    finishBtn = $('#finish-button'),
    mobileBtn = $('#mobile-button'),
    nextBtn = $('#next-button'),
    sampleBtn = $('#sample-button'),
    templateBtn = $('#template-button'),
    wasmBtn = $('#wasm-button'),
    wearableBtn = $('#wearable-button'),
    webBtn = $('#web-button');

  // Input element on the dialog
  var projectNameInput = $('#project-name'),
    projectDescriptionInput = $('#project-description');

  var mobileVersion = $('#mobile-version'),
    wearableVersion = $('#wearable-version');

  // Handle buttons click event
  mobileBtn.click(function() {
    wearableBtn.removeClass('btn-primary');
    mobileBtn.addClass('btn-primary');
  });

  wearableBtn.click(function() {
    mobileBtn.removeClass('btn-primary');
    wearableBtn.addClass('btn-primary');
  });

  templateBtn.click(function() {
    sampleBtn.removeClass('btn-primary');
    templateBtn.addClass('btn-primary');
  });

  sampleBtn.click(function() {
    templateBtn.removeClass('btn-primary');
    sampleBtn.addClass('btn-primary');
  });

  wasmBtn.click(function() {
    webBtn.removeClass('btn-primary');
    wasmBtn.addClass('btn-primary');
  });

  webBtn.click(function() {
    wasmBtn.removeClass('btn-primary');
    webBtn.addClass('btn-primary');
  });

  $("#empty-checkbox").on('change', function() {
    emptyProject = this.checked;
    if (emptyProject) {
      templateBtn.attr('disabled', 'disabled');
      templateBtn.removeClass('btn-primary');
      sampleBtn.attr('disabled', 'disabled');
      sampleBtn.removeClass('btn-primary');
    } else {
      templateBtn.addClass('btn-primary');
      templateBtn.removeAttr('disabled');
      sampleBtn.removeAttr('disabled');
    }
  });

  $('#mobile-version-dropdown>li').click(function() {
    var version = $(this).text();
    mobileVersion.text(version);
    projectVersion = version.split('v')[1];
  });

  $('#wearable-version-dropdown>li').click(function() {
    var version = $(this).text();
    wearableVersion.text(version);
    projectVersion = version.split('v')[1];
  });

  // Init button state and value
  nextBtn.removeAttr('disabled');
  backBtn.attr('disabled', 'disabled');
  finishBtn.attr('disabled', 'disabled');
  projectNameInput.val('');
  projectDescriptionInput.val('');
  mobileVersion.text('Mobile v4.0');
  wearableVersion.text('Wearable v4.0');
  projectTypeDlg.show();
  projectFormatDlg.hide();
  profileVersionDlg.hide();
  templateSampleDlg.hide();
  propertyDlg.hide();
  mobileBtn.trigger('click');
  templateBtn.trigger('click');
  wasmBtn.trigger('click');
  $('#empty-checkbox')[0].checked = false;

  if (isPWE) {
    projectTypeDlg.hide();
    projectFormatDlg.show();
    currentProcess = 'project-format';
    projectType = 'pwe';
  }

  // Update the list of template or sample
  function updateTemplateSample(projectFormat, projectType) {
    $.post('/update/template', {
      format: projectFormat,
      type: projectType
    }).done(function(data) {
      templateSampleDlg.html(data);

      $('a.list-group-item').click(function() {
        $('a.list-group-item').removeClass('active');
        $(this).addClass('active');
        templateName = $(this).find('.list-group-item-src').text();
      });

      if ($('a.list-group-item').length > 0) {
        $($('a.list-group-item')[0]).addClass('active');
        templateName = $($('a.list-group-item')[0]).find('.list-group-item-src').text();
      } else {
        // Disable next button when there is no template or sample
        nextBtn.attr('disabled', 'disabled');
      }
    });
  }

  nextBtn.click(function() {
    switch (currentProcess) {
    case 'project-type':
      // Save selected application type
      if (wasmBtn.hasClass('btn-primary')) {
        projectType = 'wasm';
      } else if (webBtn.hasClass('btn-primary')) {
        projectType = 'web';
      }

      projectTypeDlg.hide();
      projectFormatDlg.show();
      backBtn.removeAttr('disabled');
      currentProcess = 'project-format';

      break;
    case 'project-format':
      // Hide current dialog and then show next dialog
      projectFormatDlg.hide();

      // Save selected project type
      if (templateBtn.hasClass('btn-primary')) {
        projectFormat = 'template';
      } else if (sampleBtn.hasClass('btn-primary')) {
        projectFormat = 'sample';
      }

      if (projectType === 'web') {
        profileVersionDlg.show();
        currentProcess = 'profile-version';
      } else {
        if (projectType === 'pwe') {
          backBtn.removeAttr('disabled');
        }

        if (emptyProject) {
          propertyDlg.show();
          nextBtn.attr('disabled', 'disabled');
          currentProcess = 'project-property';
        } else {
          // Skip profile-version on WASM Module
          updateTemplateSample(projectFormat, projectType);
          templateSampleDlg.show();
          currentProcess = 'template-sample';
        }
      }

      break;
    case 'profile-version':
      profileVersionDlg.hide();

      if (mobileBtn.hasClass('btn-primary')) {
        projectProfile = 'mobile';
      } else if (wearableBtn.hasClass('btn-primary')) {
        projectProfile = 'wearable';
      }

      if (emptyProject) {
        propertyDlg.show();
        nextBtn.attr('disabled', 'disabled');
        currentProcess = 'project-property';
      } else {
        updateTemplateSample(projectFormat, projectType);
        templateSampleDlg.show();
        currentProcess = 'template-sample';
      }
      break;
    case 'template-sample':
      templateSampleDlg.hide();
      propertyDlg.show();
      nextBtn.attr('disabled', 'disabled');
      currentProcess = 'project-property';

      break;
    }
  });

  backBtn.click(function() {
    switch (currentProcess) {
    case 'project-format':
      projectFormatDlg.hide();
      projectTypeDlg.show();
      backBtn.attr('disabled', 'disabled');
      currentProcess = 'project-type';
      break;
    case 'profile-version':
      profileVersionDlg.hide();
      projectFormatDlg.show();
      currentProcess = 'project-format';
      break;
    case 'template-sample':
      nextBtn.removeAttr('disabled');
      if (projectType === 'web') {
        templateSampleDlg.hide();
        profileVersionDlg.show();
        currentProcess = 'profile-version';
      } else {
        if (projectType === 'pwe') {
          backBtn.attr('disabled', 'disabled');
        }

        templateSampleDlg.hide();
        projectFormatDlg.show();
        currentProcess = 'project-format';
      }
      break;
    case 'project-property':
      propertyDlg.hide();
      nextBtn.removeAttr('disabled');
      finishBtn.attr('disabled', 'disabled');

      if (emptyProject) {
        if (projectType === 'web') {
          profileVersionDlg.show();
          currentProcess = 'profile-version';
        } else {
          projectFormatDlg.show();
          currentProcess = 'project-format';
        }
      } else {
        templateSampleDlg.show();
        currentProcess = 'template-sample';
      }
      break;
    }
  });

  projectNameInput.keyup(function() {
    if (projectNameInput.val().length > 0) {
      finishBtn.removeAttr('disabled');
    } else {
      finishBtn.attr('disabled', 'disabled');
    }
  });

  finishBtn.click(function() {
    projectName = projectNameInput.val();
    projectDescription = projectDescriptionInput.val();

    // Check only project name whether it is empty or not
    if (projectName === '') {
      window.alert('You must specify the project name');
      return;
    }

    $.ajax({
      url: '/project',
      type: 'put',
      data: {
        name: projectName,
        description: projectDescription,
        format: projectFormat,
        profile: projectProfile,
        version: projectVersion,
        type: projectType,
        templateName: templateName.trim(),
      }
    }).done(function() {
      $.get('/update').done(function(data) {
        projectList.html(data);
        projectBox.show();
        $('#new-project').modal('hide');
      });
    }).fail(function(err) {
      if (err.responseText !== "") {
        alert("Error:" + err.responseText);
      }
      console.error(err);
    });
  });
});

// Unbind the event listeners for the new project
$('#new-project').on('hide.bs.modal', function() {
  $('#back-button').off();
  $('#cancel-button').off();
  $("#empty-checkbox").off();
  $('#finish-button').off();
  $('#mobile-button').off();
  $('#mobile-version-dropdown>li').off();
  $('#next-button').off();
  $('#project-name').off();
  $('#sample-button').off();
  $('#template-button').off();
  $('#template-list>li').off();
  $('#wasm-button').off();
  $('#wearable-button').off();
  $('#wearable-version-dropdown>li').off();
  $('#web-button').off();
});

// Code for delete project
$('#delete-project').on('show.bs.modal', function(evt) {
  var button = $(evt.relatedTarget);
  var id = button.data('whatever');

  $('#delete-button').on('click', function() {
    $.ajax({
      url: '/project/'+id,
      type: 'delete'
    }).done(function() {
      $.get('/update').done(function(data) {
        projectList.html(data);

        if (data.trim() === '') {
          projectBox.hide();
        }

        $('#delete-project').modal('hide');
      });
    }).fail(function(err) {
      console.error(err);
    });
  });
});

// Unbind the event listeners for the delete project
$('#delete-project').on('hide.bs.modal', function() {
  $('#delete-button').off();
});

// Code for import project
$('#import-project').on('show.bs.modal', function() {
  var currentTab = 'file',
    file;

  var nextBtn = $('#import-next-button'),
    backBtn = $('#import-back-button'),
    finishBtn = $('#import-button'),
    fileTab = $('#import-file-tab'),
    urlTab = $('#import-url-tab'),
    selectPanel = $('#select-file-url'),
    propertyPanel = $('#import-project-property'),
    importFileInput = $('#import-file-input'),
    importFile = $('#import-file'),
    projectNameInput = $('#import-project-name'),
    projectDescriptionInput = $('#import-project-description');

  $('#import-tabs>li').click(function(evt) {
    $('#import-tabs>li').removeClass('active');
    $(this).addClass('active');

    if (evt.target.id === 'import-file-button') {
      urlTab.hide();
      fileTab.show();
      currentTab = 'file';
    } else {
      fileTab.hide();
      urlTab.show();
      currentTab = 'url';
    }
  });

  $('#import-file').on('change', function(evt) {
    var files = evt.target.files;

    if (!files.length) {
      importFileInput.val('');
      return;
    }

    file = files[0];
    var fileExtension = file.name.split('.').pop();

    if (fileExtension === 'zip' || fileExtension === 'wgt') {
      importFileInput.val(file.name);
    } else {
      file = undefined;
      window.alert('You can only select zip/wgt!');
      return;
    }
  });

  nextBtn.click(function() {
    if (!file) {
      window.alert('You have to select file!');
      return;
    }

    selectPanel.hide();
    propertyPanel.show();

    nextBtn.attr('disabled', 'disabled');
    backBtn.removeAttr('disabled');

    projectNameInput.keyup(function() {
      if (projectNameInput.val().length > 0) {
        finishBtn.removeAttr('disabled');
      } else {
        finishBtn.attr('disabled', 'disabled');
      }
    });
    importFile.val('');
  });

  backBtn.click(function() {
    propertyPanel.hide();
    selectPanel.show();

    backBtn.attr('disabled', 'disabled');
    nextBtn.removeAttr('disabled');
  });

  finishBtn.click(function() {
    var projectName = projectNameInput.val();
    var projectDescription = projectDescriptionInput.val();

    // Show progress dialog
    $('#progress-dialog').modal('show');

    if (currentTab === 'file') {
      var formData = new FormData();
      formData.append('uploads[]', file, file.name);

      $.ajax({
        url: '/import/archive',
        type: 'put',
        data: {
          name: projectName,
          filename: file.name,
          description: projectDescription
        }
      }).done(function(projectId) {
        $.ajax({
          url: '/import/archive/upload/'+projectId,
          type: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          success: function(){
            $('#progress-dialog').modal('hide');
            $.get('/update').done(function(data) {
              projectList.html(data);
              projectBox.show();
              $('#import-project').modal('hide');
            });
          },
          error: function(err) {
            $('#progress-dialog').modal('hide');
            console.error(err);
            window.alert(err.responseText);
          },
          xhr: function() {
            // create an XMLHttpRequest
            var xhr = new XMLHttpRequest();

            // listen to the 'progress' event
            xhr.upload.addEventListener('progress', function(evt) {
              if (evt.lengthComputable) {
                // calculate the percentage of upload completed
                var percentComplete = evt.loaded / evt.total;
                percentComplete = parseInt(percentComplete * 100);

                // update the Bootstrap progress bar with the new percentage
                $('.progress-bar').text(percentComplete + '%');
                $('.progress-bar').width(percentComplete + '%');

                // once the upload reaches 100%, set the progress bar text to done
                if (percentComplete === 100) {
                  $('.progress-bar').html('Done');
                }
              }
            }, false);

            return xhr;
          }
        });
      }).fail(function(err) {
        if (err) {
          $('#progress-dialog').modal('hide');
          console.error(err);
          window.alert(err.responseText);
        }
      });
    } else {
      // currentTab === 'url'
      // WIP...
    }
  });

  // Init button state and value
  $('#import-tabs>li').removeClass('active');
  $($('#import-tabs>li')[0]).addClass('active');
  urlTab.hide();
  fileTab.show();
  propertyPanel.hide();
  selectPanel.show();
  backBtn.attr('disabled', 'disabled');
  nextBtn.removeAttr('disabled');
  projectNameInput.val('');
  projectDescriptionInput.val('');
  importFileInput.val('');
  importFile.val('');
});

// Unbind the event listeners for the import project
$('#import-project').on('hide.bs.modal', function() {
  $('#import-tabs>li').off();
  $('#import-file').off();
  $('#import-cancel-button').off();
  $('#import-button').off();
  $('#import-next-button').off();
  $('#import-back-button').off();
  $('#import-project-name').off();
});

// Code for edit project
$('#edit-project').on('show.bs.modal', function(event) {
  var projectId = $(event.relatedTarget).data('whatever');

  $.get('/project/'+projectId).done(function(data) {
    $('#edit-project-name').val(data.name);
    $('#edit-project-description').val(data.description);
    $('#edit-project-type').val(data.type);
    if (data.type === 'web') {
      $('#edit-profile').text(data.profile);
      $('#edit-version').text(data.version);
      $('#edit-project-profile').show();
      $('#edit-project-version').show();
    }
  });

  $('#edit-profile-dropdown>li').click(function() {
    $('#edit-profile').text($(this).text());
  });

  $('#edit-version-dropdown>li').click(function() {
    $('#edit-version').text($(this).text());
  });

  $('#edit-save-button').click(function() {
    var projectType = $('#edit-project-type').val();
    var projectProfile = '';
    var projectVersion = '';

    if (projectType === 'web') {
      projectProfile = $('#edit-profile').text();
      projectVersion = $('#edit-version').text();
    }

    $.post('/project/'+projectId, {
      name: $('#edit-project-name').val(),
      description: $('#edit-project-description').val(),
      profile: projectProfile,
      version: projectVersion,
    }).done(function() {
      $.get('/update').done(function(data) {
        projectList.html(data);
        $('#edit-project').modal('hide');
      });
    }).fail(function(error) {
      if (error) {
        console.error(error);
      }
    });
  });
});

// Unbind the event listeners for the edit project
$('#edit-project').on('hide.bs.modal', function() {
  $('#edit-project-profile').hide();
  $('#edit-project-version').hide();
  $('#edit-save-button').off();
  $('#edit-profile-dropdown>li').off();
  $('#edit-version-dropdown>li').off();
});

// Code for export project
$('#export-project').on('show.bs.modal', function(event) {
  var projectId = $(event.relatedTarget).data('whatever');
  var target;
  var shareUrl;

  $.get('/project/' + projectId).done(function(data) {
    var type = data.type;

    var lists = $('#export-list>li');
    for (var i=0; i<lists.length; i++) {
      var list = lists[i];
      if (list.type === type || list.type === 'all') {
        $(list).show();
      } else {
        $(list).hide();
      }
    }

    $('#export-list>li').click(function() {
      $('#export-list>li').removeClass('btn-primary active');
      $(this).addClass('btn-primary active');
      target = $(this).text().trim().toLowerCase();
    });

    $('#export-button').click(function() {
      if (target === 'web') {
        $.post('/export/web',
          { projectId: projectId }
        ).done(function(data) {
          $('#export-project').modal('hide');
          $('#share-project').modal('show');
          shareUrl = [location.origin,'temp',data].join('/');
          $('#share-url').val(shareUrl);
        }).fail(function(error) {
          console.error(error);
        });
      } else if (target === 'share') {
        $.post('/export/share', {
          projectId: projectId,
          projectName: data.name
        }).done(function() {
          $('#export-project').modal('hide');
        }).fail(function(error) {
          console.error(error);
        });
      } else if (target === 'tizen') {
        $.get('/export/tizen/'+projectId).done(function(data) {
          var anchor = document.createElement('a');
          var wgtPath = [window.location.origin, data.path].join('/');
          anchor.href = wgtPath;
          anchor.download = data.name;
          anchor.click();
          $('#export-project').modal('hide');
        }).fail(function() {
          window.alert('Not found wgt file');
        });
      }
    });
  });
});

$('#export-project').on('hide.bs.modal', function() {
  $('#export-list>li').removeClass('btn-primary active');
  $('#export-list>li').off();
  $('#export-button').off();
});

$('#share-project').on('show.bs.modal', function() {
  $('#share-copy-button').click(function() {
    $('#share-url').select();
    document.execCommand('copy');
  });

  $('#share-open-button').click(function() {
    window.open($('#share-url').val());
  });
});

$('#share-project').on('hide.bs.modal', function() {
  $('#share-url').val('');
  $('#share-copy-button').off();
  $('#share-open-button').off();
});


text:
<?php
/*!
* WordPress Social Login
*
* http://hybridauth.sourceforge.net/wsl/index.html | http://github.com/hybridauth/WordPress-Social-Login
*    (c) 2011-2013 Mohamed Mrassi and contributors | http://wordpress.org/extend/plugins/wordpress-social-login/
*/

/**
* Widget Customization
*/

// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;

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

function wsl_component_loginwidget_setup()
{
	// HOOKABLE:
	do_action( "wsl_component_loginwidget_setup_start" );
?>

			<?php _wsl_e("Basic Settings", 'wordpress-social-login') ?>

				<?php _wsl_e("Connect with caption", 'wordpress-social-login') ?> :

				<input type="text" class="inputgnrc" value="<?php echo get_option( 'wsl_settings_connect_with_label' ); ?>" name="wsl_settings_connect_with_label" >

				<?php _wsl_e("Social icon set", 'wordpress-social-login') ?> :

					<select name="wsl_settings_social_icon_set" style="width:400px">
						<option <?php if( get_option( 'wsl_settings_social_icon_set' )   == "wpzoom" ) echo "selected"; ?>   value="wpzoom"><?php _wsl_e("WPZOOM social networking icon set", 'wordpress-social-login') ?></option>
						<option <?php if( get_option( 'wsl_settings_social_icon_set' ) == "icondock" ) echo "selected"; ?> value="icondock"><?php _wsl_e("Icondock vector social media icons", 'wordpress-social-login') ?></option>
					</select>

				<?php _wsl_e("Users avatars", 'wordpress-social-login') ?> :

					<select name="wsl_settings_users_avatars" style="width:400px">
						<option <?php if( ! get_option( 'wsl_settings_users_avatars' ) ) echo "selected"; ?> value="0"><?php _wsl_e("Display the default users avatars", 'wordpress-social-login') ?></option>
						<option <?php if(   get_option( 'wsl_settings_users_avatars' ) ) echo "selected"; ?> value="1"><?php _wsl_e("Display users avatars from social networks when available", 'wordpress-social-login') ?></option>
					</select>

			<?php _wsl_e("Advanced Settings", 'wordpress-social-login') ?>

				<?php _wsl_e("Redirect URL", 'wordpress-social-login') ?> :

					<input type="text" name="wsl_settings_redirect_url" value="<?php echo get_option( 'wsl_settings_redirect_url' ); ?>" class="inputgnrc">

				<?php _wsl_e("Authentication flow", 'wordpress-social-login') ?> :

					<select name="wsl_settings_use_popup" style="width:400px">
						<option <?php if( get_option( 'wsl_settings_use_popup' ) == 1 ) echo "selected"; ?> value="1"><?php _wsl_e("Using popup window", 'wordpress-social-login') ?></option>
						<option <?php if( get_option( 'wsl_settings_use_popup' ) == 2 ) echo "selected"; ?> value="2"><?php _wsl_e("No popup window", 'wordpress-social-login') ?></option>
					</select>

				<?php _wsl_e("Widget display", 'wordpress-social-login') ?> :

					<select name="wsl_settings_widget_display" style="width:400px">
						<option <?php if( get_option( 'wsl_settings_widget_display' ) == 1 ) echo "selected"; ?> value="1"><?php _wsl_e("Display the widget in the comments area, login and register forms", 'wordpress-social-login') ?></option>
						<option <?php if( get_option( 'wsl_settings_widget_display' ) == 2 ) echo "selected"; ?> value="2"><?php _wsl_e("Display the widget ONLY in the comments area", 'wordpress-social-login') ?></option>
						<option <?php if( get_option( 'wsl_settings_widget_display' ) == 3 ) echo "selected"; ?> value="3"><?php _wsl_e("Display the widget ONLY in the login form", 'wordpress-social-login') ?></option>
					</select>

				<?php _wsl_e("Notification", 'wordpress-social-login') ?> :

					<select name="wsl_settings_users_notification" style="width:400px">
						<option <?php if( ! get_option( 'wsl_settings_users_notification' )      ) echo "selected"; ?> value="0"><?php _wsl_e("No notification", 'wordpress-social-login') ?></option>
						<option <?php if(   get_option( 'wsl_settings_users_notification' ) == 1 ) echo "selected"; ?> value="1"><?php _wsl_e("Notify ONLY the blog admin of a new user", 'wordpress-social-login') ?></option>
					</select>

			<?php _wsl_e("Custom CSS", 'wordpress-social-login') ?>

				<?php _wsl_e("Widget CSS", 'wordpress-social-login') ?> :

				<?php _wsl_e("To customize the default widget styles you can either: edit the css file /wordpress-social-login/assets/css/style.css, or change it from this text area", 'wordpress-social-login') ?>.

				<textarea style="width:100%;height:120px;margin-top:6px;" name="wsl_settings_authentication_widget_css"><?php echo get_option( 'wsl_settings_authentication_widget_css' );  ?></textarea>

<?php _wsl_e("The basic widget markup is the following", 'wordpress-social-login') ?>:

<span id="wp-social-login-connect-with">{connect_with_caption}</span>

<div id="wp-social-login-connect-options">
    <a class="wsl_connect_with_provider">
        <img src="{provider_icon_facebook}" />
    </a>

    <a class="wsl_connect_with_provider">
        <img src="{provider_icon_google}" />
    </a>

    etc.
</div>

		<input type="submit" class="button-primary" value="<?php _wsl_e("Save Settings", 'wordpress-social-login') ?>" />

<?php
	// HOOKABLE:
	do_action( "wsl_component_loginwidget_setup_end" );
}

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


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="colorAccent">@color/accent</item>
        <!--<item name="title_color">@color/text</item>-->
        <!--<item name="dim_title_color">@color/secondaryText</item>-->
        <!--<item name="list_bg_color">@color/divider</item>-->
    </style>

</resources>


text:
package org.bubblecloud.zigbee.api.device.impl;

import org.bubblecloud.zigbee.ZigBeeApiContext;
import org.bubblecloud.zigbee.api.DeviceBase;
import org.bubblecloud.zigbee.network.ZigBeeEndpoint;
import org.bubblecloud.zigbee.api.ZigBeeDeviceException;
import org.bubblecloud.zigbee.api.AbstractDeviceDescription;
import org.bubblecloud.zigbee.api.DeviceDescription;

import java.util.ArrayList;

/**
 * This class should be used by the refinment driver when there is no device matching the DeviceId

 * of the service
 *
 * @author Stefano "Kismet" Lenzi
 * @author Francesco Furfari
 * @author Manlio Bacco
 * @version $LastChangedRevision: 799 $ ($LastChangedDate: 2013-08-06 19:00:05 +0300 (Tue, 06 Aug 2013) $)
 */
public class GenericDevice extends DeviceBase {

    private int[] mandatory;
    private int[] optional;
    private int[] standard;
    private int[] custom;

    public GenericDevice(ZigBeeApiContext ctx, ZigBeeEndpoint zbDevice) throws ZigBeeDeviceException {
        super(ctx, zbDevice);

        mandatory = new int[0]; // we don't know the device so we cannot distinuish
        optional = new int[0];

        int[] clusterIDs = zbDevice.getInputClusters();
        ArrayList<Integer> standardList = new ArrayList<Integer>();
        ArrayList<Integer> customList = new ArrayList<Integer>();
        for (int i = 0; i < clusterIDs.length; i++) {
//			if (ZigBeeApiConstants.clusters.containsKey(clusterIDs[i])){
//				standardList.add(clusterIDs[i]);
//			} else {
//				customList.add(clusterIDs[i]);
//			}
        }
        standard = new int[standardList.size()];
        for (int i = 0; i < standard.length; i++) {
            standard[i] = standardList.get(i).intValue();
        }
        custom = new int[customList.size()];
        for (int i = 0; i < custom.length; i++) {
            custom[i] = customList.get(i).intValue();
        }

        for (int i = 0; i < standard.length; i++) {
            addCluster(standard[i]);
        }
    }

    final DeviceDescription descriptor = new AbstractDeviceDescription() {

        public int[] getCustomClusters() {
            return custom;
        }

        public int[] getMandatoryCluster() {
            return mandatory;
        }

        public int[] getOptionalCluster() {
            return optional;
        }

        public int[] getStandardClusters() {
            return standard;
        }

    };

    @Override
    public DeviceDescription getDescription() {
        return descriptor;
    }

    @Override
    public String getDeviceType() {
        return "Generic HA Device";
    }

}


text:
/* Testing module for multi-phase initialization of extension modules (PEP 489)
 */

#include "Python.h"

/* Example objects */
typedef struct {
    PyObject_HEAD
    PyObject            *x_attr;        /* Attributes dictionary */
} ExampleObject;

typedef struct {
    PyObject *integer;
} testmultiphase_state;

/* Example methods */

static int
Example_traverse(ExampleObject *self, visitproc visit, void *arg)
{
    Py_VISIT(self->x_attr);
    return 0;
}

static void
Example_finalize(ExampleObject *self)
{
    Py_CLEAR(self->x_attr);
}

static PyObject *
Example_demo(ExampleObject *self, PyObject *args)
{
    PyObject *o = NULL;
    if (!PyArg_ParseTuple(args, "|O:demo", &o))
        return NULL;
    if (o != NULL && PyUnicode_Check(o)) {
        Py_INCREF(o);
        return o;
    }
    Py_RETURN_NONE;
}

static PyMethodDef Example_methods[] = {
    {"demo",            (PyCFunction)Example_demo,  METH_VARARGS,
        PyDoc_STR("demo() -> None")},
    {NULL,              NULL}           /* sentinel */
};

static PyObject *
Example_getattro(ExampleObject *self, PyObject *name)
{
    if (self->x_attr != NULL) {
        PyObject *v = PyDict_GetItemWithError(self->x_attr, name);
        if (v != NULL) {
            Py_INCREF(v);
            return v;
        }
        else if (PyErr_Occurred()) {
            return NULL;
        }
    }
    return PyObject_GenericGetAttr((PyObject *)self, name);
}

static int
Example_setattr(ExampleObject *self, const char *name, PyObject *v)
{
    if (self->x_attr == NULL) {
        self->x_attr = PyDict_New();
        if (self->x_attr == NULL)
            return -1;
    }
    if (v == NULL) {
        int rv = PyDict_DelItemString(self->x_attr, name);
        if (rv < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
            PyErr_SetString(PyExc_AttributeError,
                "delete non-existing Example attribute");
        return rv;
    }
    else
        return PyDict_SetItemString(self->x_attr, name, v);
}

static PyType_Slot Example_Type_slots[] = {
    {Py_tp_doc, "The Example type"},
    {Py_tp_finalize, Example_finalize},
    {Py_tp_traverse, Example_traverse},
    {Py_tp_getattro, Example_getattro},
    {Py_tp_setattr, Example_setattr},
    {Py_tp_methods, Example_methods},
    {0, 0},
};

static PyType_Spec Example_Type_spec = {
    "_testimportexec.Example",
    sizeof(ExampleObject),
    0,
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
    Example_Type_slots
};

/* Function of two integers returning integer */

PyDoc_STRVAR(testexport_foo_doc,
"foo(i,j)\n\
\n\
Return the sum of i and j.");

static PyObject *
testexport_foo(PyObject *self, PyObject *args)
{
    long i, j;
    long res;
    if (!PyArg_ParseTuple(args, "ll:foo", &i, &j))
        return NULL;
    res = i + j;
    return PyLong_FromLong(res);
}

/* Test that PyState registration fails  */

PyDoc_STRVAR(call_state_registration_func_doc,
"register_state(0): call PyState_FindModule()\n\
register_state(1): call PyState_AddModule()\n\
register_state(2): call PyState_RemoveModule()");

static PyObject *
call_state_registration_func(PyObject *mod, PyObject *args)
{
    int i, ret;
    PyModuleDef *def = PyModule_GetDef(mod);
    if (def == NULL) {
        return NULL;
    }
    if (!PyArg_ParseTuple(args, "i:call_state_registration_func", &i))
        return NULL;
    switch (i) {
        case 0:
            mod = PyState_FindModule(def);
            if (mod == NULL) {
                Py_RETURN_NONE;
            }
            return mod;
        case 1:
            ret = PyState_AddModule(mod, def);
            if (ret != 0) {
                return NULL;
            }
            break;
        case 2:
            ret = PyState_RemoveModule(def);
            if (ret != 0) {
                return NULL;
            }
            break;
    }
    Py_RETURN_NONE;
}

static PyType_Slot Str_Type_slots[] = {
    {Py_tp_base, NULL}, /* filled out in module exec function */
    {0, 0},
};

static PyType_Spec Str_Type_spec = {
    "_testimportexec.Str",
    0,
    0,
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    Str_Type_slots
};

static PyMethodDef testexport_methods[] = {
    {"foo",             testexport_foo,         METH_VARARGS,
        testexport_foo_doc},
    {"call_state_registration_func",  call_state_registration_func,
        METH_VARARGS, call_state_registration_func_doc},
    {NULL,              NULL}           /* sentinel */
};

static int execfunc(PyObject *m)
{
    PyObject *temp = NULL;

    /* Due to cross platform compiler issues the slots must be filled
     * here. It's required for portability to Windows without requiring
     * C++. */
    Str_Type_slots[0].pfunc = &PyUnicode_Type;

    /* Add a custom type */
    temp = PyType_FromSpec(&Example_Type_spec);
    if (temp == NULL)
        goto fail;
    if (PyModule_AddObject(m, "Example", temp) != 0)
        goto fail;

    /* Add an exception type */
    temp = PyErr_NewException("_testimportexec.error", NULL, NULL);
    if (temp == NULL)
        goto fail;
    if (PyModule_AddObject(m, "error", temp) != 0)
        goto fail;

    /* Add Str */
    temp = PyType_FromSpec(&Str_Type_spec);
    if (temp == NULL)
        goto fail;
    if (PyModule_AddObject(m, "Str", temp) != 0)
        goto fail;

    if (PyModule_AddIntConstant(m, "int_const", 1969) != 0)
        goto fail;

    if (PyModule_AddStringConstant(m, "str_const", "something different") != 0)
        goto fail;

    return 0;
 fail:
    return -1;
}

/* Helper for module definitions; there'll be a lot of them */

#define TEST_MODULE_DEF_EX(name, slots, methods, statesize, traversefunc) { \
    PyModuleDef_HEAD_INIT,                      /* m_base */ \
    name,                                       /* m_name */ \
    PyDoc_STR("Test module " name),             /* m_doc */ \
    statesize,                                  /* m_size */ \
    methods,                                    /* m_methods */ \
    slots,                                      /* m_slots */ \
    traversefunc,                               /* m_traverse */ \
    NULL,                                       /* m_clear */ \
    NULL,                                       /* m_free */ \
}

#define TEST_MODULE_DEF(name, slots, methods) TEST_MODULE_DEF_EX(name, slots, methods, 0, NULL)

static PyModuleDef_Slot main_slots[] = {
    {Py_mod_exec, execfunc},
    {0, NULL},
};

static PyModuleDef main_def = TEST_MODULE_DEF("main", main_slots, testexport_methods);

PyMODINIT_FUNC
PyInit__testmultiphase(PyObject *spec)
{
    return PyModuleDef_Init(&main_def);
}

/**** Importing a non-module object ****/

static PyModuleDef def_nonmodule;
static PyModuleDef def_nonmodule_with_methods;

/* Create a SimpleNamespace(three=3) */
static PyObject*
createfunc_nonmodule(PyObject *spec, PyModuleDef *def)
{
    PyObject *dct, *ns, *three;

    if (def != &def_nonmodule && def != &def_nonmodule_with_methods) {
        PyErr_SetString(PyExc_SystemError, "def does not match");
        return NULL;
    }

    dct = PyDict_New();
    if (dct == NULL)
        return NULL;

    three = PyLong_FromLong(3);
    if (three == NULL) {
        Py_DECREF(dct);
        return NULL;
    }
    PyDict_SetItemString(dct, "three", three);
    Py_DECREF(three);

    ns = _PyNamespace_New(dct);
    Py_DECREF(dct);
    return ns;
}

static PyModuleDef_Slot slots_create_nonmodule[] = {
    {Py_mod_create, createfunc_nonmodule},
    {0, NULL},
};

static PyModuleDef def_nonmodule = TEST_MODULE_DEF(
    "_testmultiphase_nonmodule", slots_create_nonmodule, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_nonmodule(PyObject *spec)
{
    return PyModuleDef_Init(&def_nonmodule);
}

PyDoc_STRVAR(nonmodule_bar_doc,
"bar(i,j)\n\
\n\
Return the difference of i - j.");

static PyObject *
nonmodule_bar(PyObject *self, PyObject *args)
{
    long i, j;
    long res;
    if (!PyArg_ParseTuple(args, "ll:bar", &i, &j))
        return NULL;
    res = i - j;
    return PyLong_FromLong(res);
}

static PyMethodDef nonmodule_methods[] = {
    {"bar", nonmodule_bar, METH_VARARGS, nonmodule_bar_doc},
    {NULL, NULL}           /* sentinel */
};

static PyModuleDef def_nonmodule_with_methods = TEST_MODULE_DEF(
    "_testmultiphase_nonmodule_with_methods", slots_create_nonmodule, nonmodule_methods);

PyMODINIT_FUNC
PyInit__testmultiphase_nonmodule_with_methods(PyObject *spec)
{
    return PyModuleDef_Init(&def_nonmodule_with_methods);
}

/**** Non-ASCII-named modules ****/

static PyModuleDef def_nonascii_latin = { \
    PyModuleDef_HEAD_INIT,                      /* m_base */
    "_testmultiphase_nonascii_latin",           /* m_name */
    PyDoc_STR("Module named in Czech"),         /* m_doc */
    0,                                          /* m_size */
    NULL,                                       /* m_methods */
    NULL,                                       /* m_slots */
    NULL,                                       /* m_traverse */
    NULL,                                       /* m_clear */
    NULL,                                       /* m_free */
};

PyMODINIT_FUNC
PyInitU__testmultiphase_zkouka_naten_evc07gi8e(PyObject *spec)
{
    return PyModuleDef_Init(&def_nonascii_latin);
}

static PyModuleDef def_nonascii_kana = { \
    PyModuleDef_HEAD_INIT,                      /* m_base */
    "_testmultiphase_nonascii_kana",            /* m_name */
    PyDoc_STR("Module named in Japanese"),      /* m_doc */
    0,                                          /* m_size */
    NULL,                                       /* m_methods */
    NULL,                                       /* m_slots */
    NULL,                                       /* m_traverse */
    NULL,                                       /* m_clear */
    NULL,                                       /* m_free */
};

PyMODINIT_FUNC
PyInitU_eckzbwbhc6jpgzcx415x(PyObject *spec)
{
    return PyModuleDef_Init(&def_nonascii_kana);
}

/*** Module with a single-character name ***/

PyMODINIT_FUNC
PyInit_x(PyObject *spec)
{
    return PyModuleDef_Init(&main_def);
}

/**** Testing NULL slots ****/

static PyModuleDef null_slots_def = TEST_MODULE_DEF(
    "_testmultiphase_null_slots", NULL, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_null_slots(PyObject *spec)
{
    return PyModuleDef_Init(&null_slots_def);
}

/**** Problematic modules ****/

static PyModuleDef_Slot slots_bad_large[] = {
    {_Py_mod_LAST_SLOT + 1, NULL},
    {0, NULL},
};

static PyModuleDef def_bad_large = TEST_MODULE_DEF(
    "_testmultiphase_bad_slot_large", slots_bad_large, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_bad_slot_large(PyObject *spec)
{
    return PyModuleDef_Init(&def_bad_large);
}

static PyModuleDef_Slot slots_bad_negative[] = {
    {-1, NULL},
    {0, NULL},
};

static PyModuleDef def_bad_negative = TEST_MODULE_DEF(
    "_testmultiphase_bad_slot_negative", slots_bad_negative, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_bad_slot_negative(PyObject *spec)
{
    return PyModuleDef_Init(&def_bad_negative);
}

static PyModuleDef def_create_int_with_state = { \
    PyModuleDef_HEAD_INIT,                      /* m_base */
    "create_with_state",                        /* m_name */
    PyDoc_STR("Not a PyModuleObject object, but requests per-module state"),
    10,                                         /* m_size */
    NULL,                                       /* m_methods */
    slots_create_nonmodule,                     /* m_slots */
    NULL,                                       /* m_traverse */
    NULL,                                       /* m_clear */
    NULL,                                       /* m_free */
};

PyMODINIT_FUNC
PyInit__testmultiphase_create_int_with_state(PyObject *spec)
{
    return PyModuleDef_Init(&def_create_int_with_state);
}

static PyModuleDef def_negative_size = { \
    PyModuleDef_HEAD_INIT,                      /* m_base */
    "negative_size",                            /* m_name */
    PyDoc_STR("PyModuleDef with negative m_size"),
    -1,                                         /* m_size */
    NULL,                                       /* m_methods */
    slots_create_nonmodule,                     /* m_slots */
    NULL,                                       /* m_traverse */
    NULL,                                       /* m_clear */
    NULL,                                       /* m_free */
};

PyMODINIT_FUNC
PyInit__testmultiphase_negative_size(PyObject *spec)
{
    return PyModuleDef_Init(&def_negative_size);
}

static PyModuleDef uninitialized_def = TEST_MODULE_DEF("main", main_slots, testexport_methods);

PyMODINIT_FUNC
PyInit__testmultiphase_export_uninitialized(PyObject *spec)
{
    return (PyObject*) &uninitialized_def;
}

PyMODINIT_FUNC
PyInit__testmultiphase_export_null(PyObject *spec)
{
    return NULL;
}

PyMODINIT_FUNC
PyInit__testmultiphase_export_raise(PyObject *spec)
{
    PyErr_SetString(PyExc_SystemError, "bad export function");
    return NULL;
}

PyMODINIT_FUNC
PyInit__testmultiphase_export_unreported_exception(PyObject *spec)
{
    PyErr_SetString(PyExc_SystemError, "bad export function");
    return PyModuleDef_Init(&main_def);
}

static PyObject*
createfunc_null(PyObject *spec, PyModuleDef *def)
{
    return NULL;
}

static PyModuleDef_Slot slots_create_null[] = {
    {Py_mod_create, createfunc_null},
    {0, NULL},
};

static PyModuleDef def_create_null = TEST_MODULE_DEF(
    "_testmultiphase_create_null", slots_create_null, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_create_null(PyObject *spec)
{
    return PyModuleDef_Init(&def_create_null);
}

static PyObject*
createfunc_raise(PyObject *spec, PyModuleDef *def)
{
    PyErr_SetString(PyExc_SystemError, "bad create function");
    return NULL;
}

static PyModuleDef_Slot slots_create_raise[] = {
    {Py_mod_create, createfunc_raise},
    {0, NULL},
};

static PyModuleDef def_create_raise = TEST_MODULE_DEF(
    "_testmultiphase_create_null", slots_create_raise, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_create_raise(PyObject *spec)
{
    return PyModuleDef_Init(&def_create_raise);
}

static PyObject*
createfunc_unreported_exception(PyObject *spec, PyModuleDef *def)
{
    PyErr_SetString(PyExc_SystemError, "bad create function");
    return PyModule_New("foo");
}

static PyModuleDef_Slot slots_create_unreported_exception[] = {
    {Py_mod_create, createfunc_unreported_exception},
    {0, NULL},
};

static PyModuleDef def_create_unreported_exception = TEST_MODULE_DEF(
    "_testmultiphase_create_unreported_exception", slots_create_unreported_exception, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_create_unreported_exception(PyObject *spec)
{
    return PyModuleDef_Init(&def_create_unreported_exception);
}

static PyModuleDef_Slot slots_nonmodule_with_exec_slots[] = {
    {Py_mod_create, createfunc_nonmodule},
    {Py_mod_exec, execfunc},
    {0, NULL},
};

static PyModuleDef def_nonmodule_with_exec_slots = TEST_MODULE_DEF(
    "_testmultiphase_nonmodule_with_exec_slots", slots_nonmodule_with_exec_slots, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_nonmodule_with_exec_slots(PyObject *spec)
{
    return PyModuleDef_Init(&def_nonmodule_with_exec_slots);
}

static int
execfunc_err(PyObject *mod)
{
    return -1;
}

static PyModuleDef_Slot slots_exec_err[] = {
    {Py_mod_exec, execfunc_err},
    {0, NULL},
};

static PyModuleDef def_exec_err = TEST_MODULE_DEF(
    "_testmultiphase_exec_err", slots_exec_err, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_exec_err(PyObject *spec)
{
    return PyModuleDef_Init(&def_exec_err);
}

static int
execfunc_raise(PyObject *spec)
{
    PyErr_SetString(PyExc_SystemError, "bad exec function");
    return -1;
}

static PyModuleDef_Slot slots_exec_raise[] = {
    {Py_mod_exec, execfunc_raise},
    {0, NULL},
};

static PyModuleDef def_exec_raise = TEST_MODULE_DEF(
    "_testmultiphase_exec_raise", slots_exec_raise, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_exec_raise(PyObject *mod)
{
    return PyModuleDef_Init(&def_exec_raise);
}

static int
execfunc_unreported_exception(PyObject *mod)
{
    PyErr_SetString(PyExc_SystemError, "bad exec function");
    return 0;
}

static PyModuleDef_Slot slots_exec_unreported_exception[] = {
    {Py_mod_exec, execfunc_unreported_exception},
    {0, NULL},
};

static PyModuleDef def_exec_unreported_exception = TEST_MODULE_DEF(
    "_testmultiphase_exec_unreported_exception", slots_exec_unreported_exception, NULL);

PyMODINIT_FUNC
PyInit__testmultiphase_exec_unreported_exception(PyObject *spec)
{
    return PyModuleDef_Init(&def_exec_unreported_exception);
}

static int
bad_traverse(PyObject *self, visitproc visit, void *arg) {
    testmultiphase_state *m_state;

    m_state = PyModule_GetState(self);

    /* The following assertion mimics any traversal function that doesn't correctly handle
     * the case during module creation where the module state hasn't been created yet.
     *
     * The check that it is used to test only runs in debug mode, so it is OK that the
     * assert() will get compiled out in fully optimised release builds.
     */
    assert(m_state != NULL);
    Py_VISIT(m_state->integer);
    return 0;
}

static int
execfunc_with_bad_traverse(PyObject *mod) {
    testmultiphase_state *m_state;

    m_state = PyModule_GetState(mod);
    if (m_state == NULL) {
        return -1;
    }

    m_state->integer = PyLong_FromLong(0x7fffffff);
    Py_INCREF(m_state->integer);

    return 0;
}

static PyModuleDef_Slot slots_with_bad_traverse[] = {
    {Py_mod_exec, execfunc_with_bad_traverse},
    {0, NULL}
};

static PyModuleDef def_with_bad_traverse = TEST_MODULE_DEF_EX(
       "_testmultiphase_with_bad_traverse", slots_with_bad_traverse, NULL,
       sizeof(testmultiphase_state), bad_traverse);

PyMODINIT_FUNC
PyInit__testmultiphase_with_bad_traverse(PyObject *spec) {
    return PyModuleDef_Init(&def_with_bad_traverse);
}

/*** Helper for imp test ***/

static PyModuleDef imp_dummy_def = TEST_MODULE_DEF("imp_dummy", main_slots, testexport_methods);

PyMODINIT_FUNC
PyInit_imp_dummy(PyObject *spec)
{
    return PyModuleDef_Init(&imp_dummy_def);
}


text:
using UnityEngine;
using System.Collections;

public class EveryplayEarlyInitializer : MonoBehaviour
{
    #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7)
    void Start()
    {
        EveryplaySettings settings = (EveryplaySettings) Resources.Load("EveryplaySettings");

        if (settings != null)
        {
            if (settings.earlyInitializerEnabled && settings.IsEnabled && settings.IsValid)
            {
                StartCoroutine(InitializeEveryplay());
            }
        }
    }

    IEnumerator InitializeEveryplay()
    {
        yield return 0;
        Everyplay.Initialize();
        Destroy(gameObject);
    }

    #else
    [RuntimeInitializeOnLoadMethod]
    static void InitializeEveryplayOnStartup()
    {
        EveryplaySettings settings = (EveryplaySettings) Resources.Load("EveryplaySettings");

        if (settings != null)
        {
            if (settings.earlyInitializerEnabled && settings.IsEnabled && settings.IsValid)
            {
                Everyplay.Initialize();
            }
        }
    }

    #endif
}