text:
package io.novaordis.gld.api.mock.load;

import io.novaordis.gld.api.KeyProvider;
import io.novaordis.gld.api.service.Service;
import io.novaordis.gld.api.configuration.LoadConfiguration;
import io.novaordis.gld.api.LoadStrategy;
import io.novaordis.gld.api.Operation;
import io.novaordis.gld.api.configuration.ServiceConfiguration;
import io.novaordis.gld.api.service.ServiceType;
import io.novaordis.gld.api.mock.MockKeyProvider;
import io.novaordis.gld.api.mock.MockOperation;
import io.novaordis.gld.api.mock.configuration.MockLoadConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.fail;

/**
 * Named MockLdLoadStrategy instead of MockLoadStrategy to avoid non-obviously clashes with the API MockLoadStrategy.
 * Ran into problems at times when debugging the modules together.
 *
 * @author Ovidiu Feodorov <ovidiu@novaordis.com>
 * @since 12/4/16
 */
public class MockLdLoadStrategy implements LoadStrategy {

    // Constants -------------------------------------------------------------------------------------------------------

    private static final Logger log = LoggerFactory.getLogger(MockLdLoadStrategy.class);

    public static final int SERVICE_STATE_INDEX = 0;
    public static final int SAMPLER_STATE_INDEX = 1;
    public static final int KEY_STORE_STATE_INDEX = 2;
    public static final int LOAD_STRATEGY_STATE_INDEX = 3;
    public static final int KEY_PROVIDER_STATE_INDEX = 4;

    // Static ----------------------------------------------------------------------------------------------------------

    // Attributes ------------------------------------------------------------------------------------------------------

    private boolean verbose;
    private volatile boolean started;
    private volatile boolean initialized;
    private AtomicInteger remainingOperations;

    private volatile boolean recordLifecycleComponentState;

    // Service, Sampler, KeyStore, LoadStrategy, KeyProvider
    private boolean[] componentStarted = new boolean[5];

    private Service service;

    private KeyProvider keyProvider;

    private CountDownLatch nextFirstInvocationLatch;
    private CountDownLatch nextBlockLatch;

    // Constructors ----------------------------------------------------------------------------------------------------

    /**
     * Will generate an unlimited number of operations.
     */
    public MockLdLoadStrategy() {
        this(-1);
    }

    /**
     * @param operationCount the number of operations to generate.
     */
    public MockLdLoadStrategy(int operationCount) {

        if (operationCount >= 0) {
            remainingOperations = new AtomicInteger(operationCount);
        }

        //
        // we create an internal key provider
        //
        keyProvider = new MockKeyProvider();

        nextFirstInvocationLatch = new CountDownLatch(1);
    }

    // LoadStrategy implementation -------------------------------------------------------------------------------------

    @Override
    public ServiceType getServiceType() {

        return ServiceType.mock;
    }

    @Override
    public Service getService() {

        return service;
    }

    @Override
    public void setService(Service s) throws IllegalArgumentException {

        //
        // we don't perform any validation, we're a mock. The real implementations should, though ...
        //
        this.service = s;
    }

    @Override
    public String getName() {
        throw new RuntimeException("getName() NOT YET IMPLEMENTED");
    }

    @Override
    public void init(ServiceConfiguration sc, LoadConfiguration lc) throws Exception {

        //
        // because init() is usually NOT idempotent, fail this if we call it twice
        //

        if (initialized) {

            fail(this + ".init(...) called twice");
        }

        MockLoadConfiguration mlc = (MockLoadConfiguration)lc;
        Long operations = mlc.getOperations();
        if (operations != null) {
            remainingOperations = new AtomicInteger(operations.intValue());
        }

        this.initialized = true;

        log.info(this + " init()");
    }

    @Override
    public void start() throws Exception {

        //
        // we need to start internal lifecycle components
        //

        if (keyProvider != null) {

            keyProvider.start();
        }

        started = true;

        log.info(this + " started");
    }

    @Override
    public boolean isStarted() {

        return started;
    }

    @Override
    public void stop() {

        started = false;

        //
        // we need to start internal lifecycle components
        //

        if (keyProvider != null) {

            keyProvider.stop();
        }
    }

    @Override
    public Operation next(Operation last, String lastWrittenKey, boolean runtimeShuttingDown) throws Exception {

        if (recordLifecycleComponentState) {

            //
            // record the state on the first operation
            //

            recordLifecycleComponentState = false;

            componentStarted[SERVICE_STATE_INDEX] = getService().isStarted();
            componentStarted[SAMPLER_STATE_INDEX] = getService().getLoadDriver().getSampler().isStarted();
            componentStarted[KEY_STORE_STATE_INDEX] = getService().getLoadDriver().getKeyStore().isStarted();
            componentStarted[LOAD_STRATEGY_STATE_INDEX] = isStarted();
            componentStarted[KEY_PROVIDER_STATE_INDEX] = getKeyProvider().isStarted();
        }

        //
        // if the runtime is shutting down, comply and return null; tests rely on this behavior
        //
        if (runtimeShuttingDown) {

            log.info(this + " has been notified that the runtime is shutting down, stopping building operations ...");
            return null;
        }

        if (remainingOperations != null) {

            if (remainingOperations.getAndDecrement() <= 0) {
                return null;
            }
        }

        nextFirstInvocationLatch.countDown();

        if (nextBlockLatch != null) {

            log.info("blocking on latch ...");
            nextBlockLatch.await();
        }

        MockOperation mo = new MockOperation();

        if (verbose) {
            mo.setVerbose(true);
        }

        return mo;
    }

    @Override
    public Set<Class<? extends Operation>> getOperationTypes() {

        HashSet<Class<? extends Operation>> result = new HashSet<>();
        result.add(MockOperation.class);
        return result;
    }

    @Override
    public KeyProvider getKeyProvider() {

        return keyProvider;
    }

    @Override
    public void setKeyProvider(KeyProvider keyProvider) {

        this.keyProvider = keyProvider;
    }

    @Override
    public Long getRemainingOperations() {
        throw new RuntimeException("getRemainingOperations() NOT YET IMPLEMENTED");
    }

    @Override
    public String getReusedValue() {
        throw new RuntimeException("getReusedValue() NOT YET IMPLEMENTED");
    }

    @Override
    public boolean isReuseValue() {
        throw new RuntimeException("isReuseValue() NOT YET IMPLEMENTED");
    }

    @Override
    public String computeValue() {
        throw new RuntimeException("computeValue() NOT YET IMPLEMENTED");
    }

    // Public ----------------------------------------------------------------------------------------------------------

//    public int getRemainingOperations() {
//
//        int i = remainingOperations.get();
//
//        // the counter is decremented under 0, and that has "0" semantics
//
//        if (i < 0) {
//
//            i = 0;
//        }
//
//        return i;
//    }

    @Override
    public String toString() {

        return "load-driver MockLoadStrategy";
    }

    /**
     * We need to explicitly set the instance as verbose in order to next log.info(), otherwise the high concurrency
     * tests are too noisy. If this load strategy is verbose, then the MockOperations it builds will be verbose.
     */
    public void setVerbose(boolean b) {
        this.verbose = b;
    }

    public void recordLifecycleComponentState() {

        this.recordLifecycleComponentState = true;

        log.info(this + " was configured to record lifecycle component state");
    }

    public boolean[] getComponentStarted() {

        return componentStarted;
    }

    /**
     * Do not block right now, when the method is invoked, but later, during the next() invocation.
     */
    public void blockIndefinitelyDuringTheInvocationOfNext() {

        this.nextBlockLatch = new CountDownLatch(1);

        log.info(this + " was configured to block indefinitely during next() invocation");

    }

    public void waitUntilFirstInvocationOfNext() throws InterruptedException {

        log.info("waiting for the first invocation of next() ...");

        nextFirstInvocationLatch.await();
    }

    // Package protected -----------------------------------------------------------------------------------------------

    // Protected -------------------------------------------------------------------------------------------------------

    // Private ---------------------------------------------------------------------------------------------------------

    // Inner classes ---------------------------------------------------------------------------------------------------

}


text:
'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var  MessageSchema = new Schema({

    message: {
      type: String,
      default: ''
    },

    emailAddress: {
      type: String,
      default: ''
    },

    created: {
      type: Date,
      default: Date.now
    }
});

var SentMessageSchema = new Schema({

    to: {
      type: String,
      default: ''
    },
    message: [MessageSchema]
});

var InboxMessageSchema = new Schema({

    from: {
      type: String,
      default: ''
    },
    message: [MessageSchema]
});

mongoose.model('Message', MessageSchema);
mongoose.model('SentMessage', SentMessageSchema);
mongoose.model('InboxMessage', InboxMessageSchema);

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<labels>
	Проект
	Признан
	Назначен участнику
	Назначен роли
	Владелец - участник
	Владелец - роль
	Владелец - я
	Создан участником
	Создан ролью
	Родительская задача
	Публтчная
	Тип оплаты
	Название
	Полный текст
	Тип
	Тип работы
	Управление временем
	Срок
	Срок (динамичный)
	Начальная дата
	Начальная дата (динамичная)
	Конечная дата
	Конечная дата (динамическая)
	Последний раз редактировано
	Последний раз редактировалось (динамически)
	Создано
	Создано (динамически)
	Статус проекта
	Полнотекстовый заголовок
	клиента
	Роль проекта
	Лидер проекта
	Супервизор проекта
	Управление временем
	Дата начала проекта
	Дата конца проекта
	Срок проекта
	Создан
	Создан (динамически)
	Изменён
	Изменён (динамически)
	Задача из фильтра задач
</labels>


text:
// @flow
/* eslint-env mocha */

import assert from 'power-assert'
import endOfDecade from '.'

describe('endOfDecade', function() {
  it('returns the date with the time set to 23:59:59.999 and the date set to the last millisecond of a decade', function() {
    var date = new Date(2017, 3 /* Apr */, 10, 0, 0, 0)
    var result = endOfDecade(date)
    assert.deepEqual(result, new Date(2019, 11 /* Dec */, 31, 23, 59, 59, 999))
  })

  it('accepts a timestamp', function() {
    var date = new Date(2007, 9 /* Oct */, 10, 0, 0, 0).getTime()
    var result = endOfDecade(date)
    assert.deepEqual(result, new Date(2009, 11 /* Dec */, 31, 23, 59, 59, 999))
  })

  it('does not mutate the original date', function() {
    var date = new Date(2038, 0 /* Jan */, 19, 3, 14, 8)
    endOfDecade(date)
    assert.deepEqual(date, new Date(2038, 0 /* Jan */, 19, 3, 14, 8))
  })

  it('returns `Invalid Date` if the given date is invalid', function() {
    var result = endOfDecade(new Date(NaN))
    assert(result instanceof Date && isNaN(result))
  })

  it('throws TypeError exception if passed less than 1 argument', function() {
    assert.throws(endOfDecade.bind(null), TypeError)
  })
})


text:
package com.vaadin.tests.components;

import java.util.Arrays;

import com.vaadin.annotations.Theme;
import com.vaadin.server.AbstractErrorMessage;
import com.vaadin.server.ErrorMessage;
import com.vaadin.server.ExternalResource;
import com.vaadin.server.UserError;
import com.vaadin.server.VaadinRequest;
import com.vaadin.shared.ui.ErrorLevel;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.DateField;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TextField;
import com.vaadin.ui.TwinColSelect;
import com.vaadin.ui.themes.ValoTheme;

@Theme("valo")
public class ErrorLevels extends AbstractTestUI {

    private ComboBox<ErrorLevel> errorLevels;
    private Button button;
    private Button borderlessButton;
    private Link link;
    private ComboBox<String> comboBox;
    private TextField textField;
    private TextField textFieldBorderless;
    private TabSheet tabSheet;
    private Accordion accordion;
    private CheckBox checkBox;
    private NativeButton nativeButton;
    private FormLayout formLayout;
    private TextField formLayoutTextField;
    private Panel panel;
    private DateField dateField;
    private TwinColSelect twinColSelect;

    private com.vaadin.v7.ui.ComboBox comboBoxCompat;
    private com.vaadin.v7.ui.TextField textFieldCompat;
    private com.vaadin.v7.ui.CheckBox checkBoxCompat;
    private com.vaadin.v7.ui.DateField dateFieldCompat;
    private com.vaadin.v7.ui.TwinColSelect twinColSelectCompat;

    @Override
    protected void setup(VaadinRequest request) {

        errorLevels = new ComboBox<>("Error level",
                Arrays.asList(ErrorLevel.values()));
        errorLevels.setEmptySelectionAllowed(false);
        errorLevels.setValue(ErrorLevel.ERROR);
        errorLevels.addValueChangeListener(event -> setErrorMessages());
        addComponent(errorLevels);

        Label subtitle = new Label("Components");
        subtitle.setStyleName(ValoTheme.LABEL_H3);
        addComponent(subtitle);

        // Button
        button = new Button("Button");

        borderlessButton = new Button("Borderless button");
        borderlessButton.setStyleName(ValoTheme.BUTTON_BORDERLESS);

        addComponent(new HorizontalLayout(button, borderlessButton));

        // Native button
        nativeButton = new NativeButton("Native button");
        addComponent(nativeButton);

        // Link
        link = new Link("Link", new ExternalResource("#"));
        addComponent(link);

        // Combo box
        comboBox = new ComboBox<>("Combo box");
        addComponent(comboBox);

        // Text field
        textField = new TextField("Text field");
        textField.setValue("text");

        textFieldBorderless = new TextField("Borderless text field");
        textFieldBorderless.setStyleName(ValoTheme.TEXTFIELD_BORDERLESS);
        textFieldBorderless.setValue("text");

        addComponent(new HorizontalLayout(textField, textFieldBorderless));

        // Date field
        dateField = new DateField("Date field");
        addComponent(dateField);

        // Check box
        checkBox = new CheckBox("Check box");
        addComponent(checkBox);

        // Tab sheet
        tabSheet = new TabSheet();
        tabSheet.addTab(new Label("Label1"), "Tab1");
        tabSheet.addTab(new Label("Label2"), "Tab2");
        tabSheet.setWidth("400px");
        addComponent(tabSheet);

        // Accordion
        accordion = new Accordion();
        accordion.addTab(new Label("Label1"), "Tab1");
        accordion.addTab(new Label("Label2"), "Tab2");
        accordion.setWidth("400px");
        addComponent(accordion);

        // Form layout
        formLayout = new FormLayout();
        formLayout.setWidth("400px");

        formLayoutTextField = new TextField("Form layout text field");
        formLayout.addComponent(formLayoutTextField);

        addComponent(formLayout);

        // Panel
        panel = new Panel();
        panel.setContent(new Label("Panel"));
        panel.setWidth("400px");
        addComponent(panel);

        // TwinColSelect
        twinColSelect = new TwinColSelect("Twin col select");
        addComponent(twinColSelect);

        Label subtitleCompat = new Label("Compatibility components");
        subtitleCompat.setStyleName(ValoTheme.LABEL_H3);
        addComponent(subtitleCompat);

        // Compatibility combo box
        comboBoxCompat = new com.vaadin.v7.ui.ComboBox(
                "Compatibility combo box");
        addComponent(comboBoxCompat);

        // Compatibility text field
        textFieldCompat = new com.vaadin.v7.ui.TextField(
                "Compatibility text field");
        textFieldCompat.setValue("text");

        // Compatibility check box
        checkBoxCompat = new com.vaadin.v7.ui.CheckBox("Check box");
        addComponent(checkBoxCompat);

        // Compatibility date field
        dateFieldCompat = new com.vaadin.v7.ui.DateField("Date field");
        addComponent(dateFieldCompat);

        // Compatibility twin col select
        twinColSelectCompat = new com.vaadin.v7.ui.TwinColSelect(
                "Twin col select");
        addComponent(twinColSelectCompat);

        setErrorMessages();

        getLayout().setSpacing(true);
    }

    private void setErrorMessages() {
        button.setComponentError(createErrorMessage("Button error"));
        borderlessButton.setComponentError(
                createErrorMessage("Borderless button error"));
        link.setComponentError(createErrorMessage("Link error"));
        comboBox.setComponentError(createErrorMessage("ComboBox error"));
        textField.setComponentError(createErrorMessage("Text field error"));
        textFieldBorderless.setComponentError(
                createErrorMessage("Borderless text field error"));
        tabSheet.setComponentError(createErrorMessage("Tab sheet error"));
        tabSheet.getTab(0).setComponentError(createErrorMessage("Tab error"));
        accordion.setComponentError(createErrorMessage("Accordion error"));
        accordion.getTab(0).setComponentError(createErrorMessage("Tab error"));
        checkBox.setComponentError(createErrorMessage("Check box error"));
        nativeButton
                .setComponentError(createErrorMessage("Native button error"));
        formLayout.setComponentError(createErrorMessage("Form layout error"));
        formLayoutTextField.setComponentError(
                createErrorMessage("Form layout text field error"));
        panel.setComponentError(createErrorMessage("Panel error"));
        dateField.setComponentError(createErrorMessage("Date field error"));
        twinColSelect
                .setComponentError(createErrorMessage("Twin col select error"));
        comboBoxCompat.setComponentError(
                createErrorMessage("Compatibility combo box error"));
        textFieldCompat.setComponentError(
                createErrorMessage("Compatibility text field error"));
        checkBoxCompat.setComponentError(
                createErrorMessage("Compatibility check box error"));
        dateFieldCompat.setComponentError(
                createErrorMessage("Compatibility date field error"));
        twinColSelectCompat.setComponentError(
                createErrorMessage("Compatibility twin col select error"));
    }

    private ErrorMessage createErrorMessage(String text) {
        return new UserError(text, AbstractErrorMessage.ContentMode.TEXT,
                errorLevels.getValue());
    }
}


text:
.blockquote {
  composes: db from 'tachyons';
  composes: f4 from 'tachyons';
  composes: lh-copy from 'tachyons';
  composes: mb4 from 'tachyons';
  composes: mt2 from 'tachyons';
  composes: pt0 from 'tachyons';
  composes: tc from 'tachyons';
}

.paragraph {
  composes: di from 'tachyons';
  composes: fw3 from 'tachyons';
  composes: i from 'tachyons';
}

.footer {
  composes: di from 'tachyons';
}

.dash {
  composes: fs-normal from 'tachyons';
  composes: ml3 from 'tachyons';
  composes: moon-gray from 'tachyons';
}

.cite {
  composes: silver from 'tachyons';
}


text:
import { computed } from '@ember/object';
import Component from '@ember/component';
import layout from '../templates/components/slds-box';

const sizeMap = {
  default: '',
  small: 'slds-box_small',
  'x-small': 'slds-box_x-small',
  'xx-small': 'slds-box_xx-small'
};

export default Component.extend({
  layout,
  classNames: 'slds-box',
  classNameBindings: ['sizeClass'],

  size: 'default',
  sizeClass: computed('size', function() {
    return sizeMap[this.get('size')];
  })
});


text:
Pycharm defaults to using unittest as the testrunner. To change it to pytest:

1. In the menu, navigate to File:Settings:Tools:PythonIntegratedTools
2. In the 'Default test runner' field, select 'py.test'
3. Click 'OK' to save the change
4. Select the drop down in the top right of the editor pane, adjacent to the green arrow
5. Select 'Edit configurations...' in the dropdown
6. In the left pane, navigate to Defaults:PythonTests:py.test
7. Check the box to enable the options field and enter '--tb=line' (without quotes)
8. Click 'OK' to save the change

## Pytest Overview ##
For a great overview of unit testing with pytest, see https://github.com/2achary/guest_list/blob/master/TestDrivingPytest.pdf

## Basics ##
Pytest will find all test functions that start with test_, and all test classes that start with Test.

```python
import pytest

def test_uppercase():
    assert 'JIM' == 'jim'.upper()

def test_uppercase_number():
    assert 'J1M' == 'j1m'.upper(), 'expected number to remain, other letters to be uppercase'
```

## Expected Exceptions ##
```python
import pytest

def test_uppercase_wrong_type():
    with pytest.raises(AttributeError):
        x = 10
        x.upper()
```

## Parametrized Tests ##
```python
import pytest

good_words = ['jim', 'Jim', 'j_m', 'j1m']
expected = ['JIM', 'JIM', 'J_M', 'J1M']

@pytest.mark.parametrize('word, expected', zip(good_words, expected))
def test_uppercase(word, expected):
    assert expected == word.upper()
```

```python
import pytest

params = [
  pytest.param('jim', 'JIM', id='lower to upper'),
  pytest.param('Jim', 'JIM', id='proper to upper'),
  pytest.param('j_m', 'J_M', id='symbol to upper'),
  pytest.param('j1m', 'J1M', id='number to upper')
]

@pytest.mark.parametrize('word, expected', params)
def test_uppercase(word, expected):
    assert expected == word.upper()
```

## Basic Fixtures ##
```python
import pytest

@pytest.fixture
def book():
    Book = collections.namedtuple('Book', 'pages, add_stamp')
    return Book(20, lambda x: True)

def test_library(book):
    assert library.checkout_book(book)
```

## Setup/Teardown Fixtures ##
Your fixtures can include a teardown method to be called after the test is called:
```python
import pytest

@pytest.fixture
def book(request):                  ## must have request argument
    Book = collections.namedtuple('Book', 'pages, add_stamp')
    def teardown():                 ## define your teardown code
        Book.close()
    request.addfinalizer(teardown)  ## add the teardown method to the request object
    return Book(20, lambda x: True)

def test_library(book):
    assert library.checkout_book(book)
```

## Mocks ##
Mocks can be used to make dummy objects. You can verify method calls on those objects or just use them so the real (heavier) objects are not used.

```python
import pytest
from unittest.mock import Mock

def test_library():
    mock_book = Mock()
    mock_book.add_stamp.return_value = True
    library.checkout_book(mock_book)
    assert mock_book.add_stamp.call_count == 1
```

Sometimes when testing, you want different method inputs to return different values on your mocks. Just make sure your `dic` keys are tuples (or change the lambda to accept non-tuples):
```python
def return_values(dic):
    return lambda *args: dic[args]

def test_find_mock():
    x = Mock()
    x.find = return_values({
        (4, 5): 'called 4, 5',
        ('a', 'b'): 'called a, b'
    })

    assert x.find(4, 5) == "called 4, 5"
    assert x.find('a', 'b') == 'called a, b'
    assert x.find() == None #throws exception if it's not mapped
```

## MonkeyPatch ##
If you want to change what's returned from an object, but don't have control over the object's creation, you can monkeypatch the method you want to change.
```python
import pytest
@pytest.fixture
def no_db(monkeypatch):
    monkeypatch.setattr(library.dbservice.BookService, 'find_all_books', lambda: {'Book A': {'pages': 90}})

def test_library(no_db):
    books = library.show_books()   # behind the scenes this calls BookService.find_all_books()
    assert books == {'Book A': {'pages': 90}}
```

Or you can use the `mock.patch` method, which may be easier when you're not just calling a static method:
```python
import pytest

@pytest.fixture
def mock_book_service(pages=100):
    book_service = MagicMock()
    book_service.find_all_books.return_value = {'Book A': {'pages': pages}}
    return book_service

@mock.patch('npr.library.BookService', return_value=mock_book_service())
def test_library():
    books = library.show_books()   # behind the scenes this would create a BookService and call find_all_books() on it
    assert books == {'Book A': {'pages': 100}}
```

You can also mock context managers with your monkeypatch:
```python

@pytest.fixture
def mock_connection():
    mock = MagicMock(spec=kombu.Connection)

    # Connection is a context_manager, so its __enter__ will be called
    # and since __enter__ should return `self`, that's where we set the return value to our mock
    mock.return_value.__enter__.return_value = mock
    return mock

def test_make_a_connection(monkeypatch, mock_connection):
    monkeypatch.setattr('rabbitmqservice.Connection', mock_connection)
    rabbitmqservice.make_a_connection()
    assert 1 == mock_connection.call_count
```

## Logging ##
You can use the `caplog` magic parameter to test log-related code:
```python
def test_custom_log_formatter(caplog):
    # generate a test log record
    with caplog.at_level(logging.INFO):
        logging.getLogger('test').error('Test info', extra={'size': 'small'})
    record = caplog.records[0]
```

You can also use `caplog` to verify the contents of a log message:
```python
def test_loud_function(caplog):
    my_service.generate_data()
    assert 'Data Created' == caplog.records[0].message
    assert 'Data Saved' == caplog.records[1].message
```


text:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <!--android:src="@drawable/ic_menu_info_details"-->
    <ImageView
        android:layout_width="42dp"
        android:layout_height="42dp"
        android:padding="6dp"
        android:layout_marginTop="2dp"
        android:layout_marginBottom="2dp"
        android:background="@color/button_background"
        android:src="@android:drawable/ic_dialog_info"
        android:id="@+id/imageView"
        android:visibility="visible"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:id="@+id/objectid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12dp"
        android:textStyle="bold"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:text="Object id"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/imageView"
        android:layout_toEndOf="@+id/imageView" />
    <TextView
        android:id="@+id/distance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12dp"
        android:textStyle="italic"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="Distance"
        android:layout_below="@+id/objectid"
        android:layout_toRightOf="@+id/imageView"
        android:layout_toEndOf="@+id/imageView" />
    <!--<TextView-->
    <!--android:id="@+id/address"-->
    <!--android:layout_width="wrap_content"-->
    <!--android:layout_height="wrap_content"-->
    <!--android:textSize="12dp"-->
    <!--android:textStyle="italic"-->
    <!--android:paddingLeft="10dp"-->
    <!--android:paddingRight="10dp"-->
    <!--android:text="Address"-->
    <!--android:layout_below="@+id/distance"-->
    <!--android:layout_toRightOf="@+id/imageView"-->
    <!--android:layout_toEndOf="@+id/imageView" />-->
</RelativeLayout>


text:
__author__ = 'jjauhiainen'
import serial
import time
import traceback
class SerialDataAdapter(object):
    port = None
    baudrate = None
    serial_connection = None

    def __init__(self, port, baudrate=9600):
        self.port = port
        self.baudrate = baudrate

    def open_connection(self, retry_times=3, timeout=1):
        if self.check_connection_status():
            return False
        else:
            for i in range(retry_times):
                try:
                    self.serial_connection = serial.Serial(self.port, self.baudrate)
                    return True
                except serial.SerialException:
                    time.sleep(timeout)
            msg = "Could not open connection to {} with baudrate {} after trying {} times. Check debug level message."
            raise serial.SerialException(msg.format(self.port, self.baudrate, retry_times))

    def check_connection_status(self):
        try:
            return self.serial_connection.isOpen()
        except (AttributeError, serial.SerialException) as e:
            return False

    def read_int(self):
        value = self.serial_connection.readline()
        try:
            return int(value)
        except:
            raise ValueError("Could not read integer value")

    def disconnect(self):
        try:
            if self.serial_connection.isOpen():
                self.serial_connection.close()
                self.serial_connection = None
        except:
            pass


text:
"""
Catch built-ins: superclass option 1
"""

traceMe = False
def trace(*args):
    if traceMe: print('[' + ' '.join(map(str, args)) + ']')

class BuiltinsMixin:
    def reroute(self, attr, *args, **kargs):
        return self.__class__.__getattr__(self, attr)(*args, **kargs)

    def __add__(self, other):
        return self.reroute('__add__', other)
    def __str__(self):
        return self.reroute('__str__')
    def __getitem__(self, index):
        return self.reroute('__getitem__', index)
    def __call__(self, *args, **kargs):
        return self.reroute('__call__', *args, **kargs)

def accessControl(failIf):
    def onDecorator(aClass):
        class onInstance(BuiltinsMixin):                                  # <===
            def __init__(self, *args, **kargs):
                self.__wrapped = aClass(*args, **kargs)
            def __getattr__(self, attr):
                trace('get:', attr)
                if failIf(attr):
                    raise TypeError('private attribute fetch: ' + attr)
                else:
                    return getattr(self.__wrapped, attr)
            def __setattr__(self, attr, value):
                trace('set:', attr, value)
                if attr == '_onInstance__wrapped':
                    self.__dict__[attr] = value
                elif failIf(attr):
                    raise TypeError('private attribute change: ' + attr)
                else:
                    setattr(self.__wrapped, attr, value)
        return onInstance
    return onDecorator

def Private(*attributes):
    return accessControl(failIf=(lambda attr: attr in attributes))

def Public(*attributes):
    return accessControl(failIf=(lambda attr: attr not in attributes))

#------------------------------------------------------------------------------

@Private('age')
class Person:
    def __init__(self, name):
        self.age = 42
        self.name = name
    def __str__(self):
        return 'Person: ' + str(self.age)
    def __add__(self, yrs):
        self.age += yrs

X = Person('bob')
try:   X.age
except Exception as E: print(E)
print(X.name)
print(X)       # __str__
X + 10         # __add__
print(X)       # __str__

@Public('seq', '__getitem__', '__call__', '__getslice__')   # probably want Private here
class Person:                                               # or allow __X__ to pass always
    def __init__(self):
        self.seq = 'spam'
    def __getitem__(self, ix): return self.seq[ix]
    def __call__(self, *args): return ('call',) + args

X = Person()
try:   X.age
except Exception as E: print(E)
print(X.seq)
print(X[1:3])  # __getitem__
print(X(9))    # __call__

"""
c:\code>py -3 access2_builtins1.py
private attribute fetch: age
bob
Person: 42
Person: 52
private attribute fetch: age
spam
pa
('call', 9)
"""


text:
<?php
    /*
     * This file cleans up the user input from the search form and passes it to
     * the Google Books API. The outputs are then added to an associative array
     * and passes to a view to enable the user to select one of the results.
     */

    // configuration
    require("../includes/config.php");

    // if form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        // clean up inputs to prevent html insertion
        $_POST["title"] = htmlspecialchars($_POST["title"]);
        $_POST["author"] = htmlspecialchars($_POST["author"]);
        $_POST["isbn"] = htmlspecialchars($_POST["isbn"]);

        // check that at least one field is filled out
        if (empty($_POST["title"])
            && empty($_POST["author"])
            && empty($_POST["isbn"]))
        {
            apologize("You must fill in at least one field.");
        }
        // check that ISBN is number
        else if (!is_numeric($_POST["isbn"]) && !empty($_POST["isbn"]))
        {
            apologize("Please only use numbers in the ISBN.");
        }
        // check that ISBN has proper format
        else if (strlen($_POST["isbn"]) != 10
            && strlen($_POST["isbn"]) != 13
            && !empty($_POST["isbn"]))
        {
            apologize("An ISBN number should be 10 or 13 digits long.");
        }
        // format parameters for API call
        else
        {
            // use correct prefix for ISBN
            $isbn = "isbn:" . $_POST["isbn"] . "+";
            // if no ISBN given, pass empty string
            if (empty($_POST["isbn"]))
            {
                $isbn = "";
            }

            // remove leading and trailing spaces, replace spaces with '+'
            $_POST["author"] = preg_replace(
                '/\s+/', '+', trim($_POST["author"]));
            // use correct prefix for author
            $author = "inauthor:" . $_POST["author"] . "+";
            // if no author given, pass empty string
            if (empty($_POST["author"]))
            {
                $author = "";
            }

            // remove leading and trailing spaces, replace spaces with '+'
            $_POST["title"] = preg_replace(
                '/\s+/', '+', trim($_POST["title"]));
            // use correct prefix for title
            $title = "intitle:" . $_POST["title"] . "+";
            // if no title given, pass empty string
            if (empty($_POST["title"]))
            {
                $title = "";
            }

            // add fixed parameters to ensure only books are returned
            $type = "&printType=books";
            // and number of results does not exceed 20
            $number = "&maxResults=20";

            // concatenate parameters
            $parameters = $isbn . $author . $title . $type . $number;

            // if too few parameters were be gathered prompt retry
            if ($parameters == $type . $number)
            {
                apologize("Your search does not have enough parameters.");
            }

            // make API request
            $page = file_get_contents(
                "https://www.googleapis.com/books/v1/volumes?q=" .
                $parameters);

            // decode API response
            $data = json_decode($page, true);

            // if no results are returned
            if ($data["totalItems"] == 0)
            {
                apologize("No resuts were found. Please modify your search.");
            }

            // initiate array and add results that have ISBN_13 (UID in DB)
            $results = [];
            $counter = 0;

            // store all the results where ISBN_13 is given for display
            foreach ($data["items"] as $book)
            {
                // store title and subtitle (if it exists)
                $results[$counter]["title"] = $book["volumeInfo"]["title"];
                if (!empty($book["volumeInfo"]["subtitle"]))
                {
                    $results[$counter]["title"] = $results[$counter]["title"] .
                    ": " . $book["volumeInfo"]["subtitle"];
                }

                // store author(s)
                $results[$counter]["author"] = @implode(
                    ",", $book["volumeInfo"]["authors"]);

                // store ISBN_13 (can be in different keys of the data array)
                $results[$counter]["isbn"] = "";
                if (!empty($book["volumeInfo"]["industryIdentifiers"][1]["type"])
                    && $book["volumeInfo"]["industryIdentifiers"][1]["type"] == "ISBN_13")
                {
                    $results[$counter]["isbn"] = $book["volumeInfo"]["industryIdentifiers"][1]["identifier"];
                }
                else if (!empty($book["volumeInfo"]["industryIdentifiers"][0]["type"])
                    && $book["volumeInfo"]["industryIdentifiers"][0]["type"] == "ISBN_13")
                {
                    $results[$counter]["isbn"] = $book["volumeInfo"]["industryIdentifiers"][0]["identifier"];
                }
                // if ISBN_13 not returned in response, use user input
                else if (strlen($_POST["isbn"]) == 13)
                {
                    $results[$counter]["isbn"] = $_POST["isbn"];
                }

                // if book has no picture, use default
                $results[$counter]["img"] = "/img/bookcovers/default.jpg";
                if (!empty($book["volumeInfo"]["imageLinks"]["thumbnail"]))
                {
                    $results[$counter]["img"] = $book["volumeInfo"]["imageLinks"]["thumbnail"];
                }

                // overwrite with next result if book does not have ISBN
                if ($results[$counter]["isbn"] != "")
                {
                    $counter++;
                }
            }
            // render results
            render("findbooks.php", [
                "title" => "Books Found",
                "results" => $results,
                "counter" =>$counter]);
        }
    }
    else
    {
        // else render form
        render("findbooks_form.php", ["title" => "Find Book"]);
    }

?>


text:
@implementation ISNetworkingLogger

+ (void)logDebugInfoWithRequest:(NSURLRequest *)request apiName:(NSString *)apiName service:(ISNetworkingBaseServiceProvider *)service requestParams:(id)requestParams httpMethod:(NSString *)httpMethod{

#ifdef DEBUG
    NSMutableString *logString = [NSMutableString stringWithString:@"\n\n**************************************************************\n*                       Request Start                        *\n**************************************************************\n\n"];
    [logString appendFormat:@"API Name:\t\t%@\n", [apiName IS_defaultValue:@"N/A"]];
    [logString appendFormat:@"Method:\t\t\t%@\n", [httpMethod IS_defaultValue:@"N/A"]];
    [logString appendFormat:@"Version:\t\t%@\n", [service.serviceVersion IS_defaultValue:@"N/A"]];
    [logString appendFormat:@"Service:\t\t%@\n", [service class]];
    [logString appendFormat:@"Params:\n%@", requestParams];

    [logString appendFormat:@"\n\nHTTP URL:\n\t%@", request.URL];
    [logString appendFormat:@"\n\nHTTP Header:\n%@", request.allHTTPHeaderFields ? request.allHTTPHeaderFields : @"\t\t\t\t\tN/A"];
    [logString appendFormat:@"\n\nHTTP Body:\n\t%@", [[[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding] IS_defaultValue:@"\t\t\t\tN/A"]];
    [logString appendFormat:@"\n\n**************************************************************\n*                         Request End                        *\n**************************************************************\n\n\n\n"];
    NSLog(@"%@", logString);
#endif

}

+ (void)logDebugInfoWithResponse:(NSHTTPURLResponse *)response resposeString:(NSString *)responseString request:(NSURLRequest *)request error:(NSError *)error{

#ifdef DEBUG
    BOOL shouldLogError = error ? YES : NO;
    NSMutableString *logString = [NSMutableString stringWithString:@"\n\n==============================================================\n=                        API Response                        =\n==============================================================\n\n"];

    [logString appendFormat:@"Status:\t%ld\t(%@)\n\n", (long)response.statusCode, [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode]];
    [logString appendFormat:@"Content:\n\t%@\n\n", responseString];

    if (shouldLogError) {
        [logString appendFormat:@"Error Domain:\t\t\t\t\t\t\t%@\n", error.domain];
        [logString appendFormat:@"Error Domain Code:\t\t\t\t\t\t%ld\n", (long)error.code];
        [logString appendFormat:@"Error Localized Description:\t\t\t%@\n", error.localizedDescription];
        [logString appendFormat:@"Error Localized Failure Reason:\t\t\t%@\n", error.localizedFailureReason];
        [logString appendFormat:@"Error Localized Recovery Suggestion:\t%@\n\n", error.localizedRecoverySuggestion];
    }

    [logString appendString:@"\n---------------  Related Request Content  --------------\n"];
    [logString appendFormat:@"\n\nHTTP URL:\n\t%@", request.URL];
    [logString appendFormat:@"\n\nHTTP Header:\n%@", request.allHTTPHeaderFields ? request.allHTTPHeaderFields : @"\t\t\t\t\tN/A"];
    [logString appendFormat:@"\n\nHTTP Body:\n\t%@", [[[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding] IS_defaultValue:@"\t\t\t\tN/A"]];

    [logString appendFormat:@"\n\n==============================================================\n=                        Response End                        =\n==============================================================\n\n\n\n"];

    NSLog(@"%@", logString);
#endif

}

+ (void)logDebugInfoWithCachedResponse:(ISNetworkingResponse *)response methodName:(NSString *)methodName serviceIdentifier:(ISNetworkingBaseServiceProvider *)service{

#ifdef DEBUG
    NSMutableString *logString = [NSMutableString stringWithString:@"\n\n==============================================================\n=                      Cached Response                       =\n==============================================================\n\n"];
    [logString appendFormat:@"API Name:\t\t%@\n", [methodName IS_defaultValue:@"N/A"]];
    [logString appendFormat:@"Version:\t\t%@\n", [service.serviceVersion IS_defaultValue:@"N/A"]];
    [logString appendFormat:@"Service:\t\t%@\n", [service class]];
    [logString appendFormat:@"Method Name:\t%@\n", methodName];
    [logString appendFormat:@"\n\n==============================================================\n=                        Response End                        =\n==============================================================\n\n\n\n"];
    NSLog(@"%@", logString);
#endif

}

@end


text:
@class USBoolean ;
@class NSNumber ;
@class NSNumber ;
@class NSNumber ;
@class NSNumber ;
@class NSNumber ;
@class NSNumber ;
@class NSNumber ;
@class NSNumber ;
@class NSNumber ;
@class NSNumber ;
@class NSNumber ;
@class NSDate ;
@class NSDate ;
@class NSDate ;
@class NSDate ;
@class NSData ;
@class NSNumber ;
@class NSString ;
@class NSString ;
@class NSString ;
@class NSString ;
@class NSString ;
@class NSString ;
@class NSString ;
@class NSString ;
@class NSString ;
@class NSString ;
@class NSString ;
@class NSString ;


text:
package com.intellij.refactoring.changeSignature.inCallers;

import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.ide.highlighter.HighlighterFactory;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Splitter;
import com.intellij.psi.*;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.ui.CheckboxTree;
import com.intellij.ui.CheckedTreeNode;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.Alarm;
import com.intellij.util.containers.HashSet;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.*;
import java.util.Enumeration;
import java.util.Set;

/**
 * @author ven
 */
public abstract class CallerChooser extends DialogWrapper {
  PsiMethod myMethod;
  private final Alarm myAlarm = new Alarm();
  private MethodNode myRoot;
  private final Project myProject;
  private Tree myTree;
  private TreeSelectionListener myTreeSelectionListener;
  private Editor myCallerEditor;
  private Editor myCalleeEditor;

  public Tree getTree() {
    return myTree;
  }

  public CallerChooser(final PsiMethod method, String title, Tree previousTree) {
    super(true);
    myMethod = method;
    myProject = myMethod.getProject();
    myTree = previousTree;
    setTitle(title);
    init();
  }

  protected JComponent createCenterPanel() {
    Splitter splitter = new Splitter(false, (float)0.6);
    JPanel result = new JPanel(new BorderLayout());
    if (myTree == null) {
      myTree = createTree();
    }
    else {
      final CheckedTreeNode root = (CheckedTreeNode)myTree.getModel().getRoot();
      myRoot = (MethodNode)root.getFirstChild();
    }
    myTreeSelectionListener = new TreeSelectionListener() {
      public void valueChanged(TreeSelectionEvent e) {
        final TreePath path = e.getPath();
        if (path != null) {
          final MethodNode node = (MethodNode)path.getLastPathComponent();
          myAlarm.cancelAllRequests();
          myAlarm.addRequest(new Runnable() {
            public void run() {
              updateEditorTexts(node);
            }
          }, 300);
        }
      }
    };
    myTree.getSelectionModel().addTreeSelectionListener(myTreeSelectionListener);

    JScrollPane scrollPane = new JScrollPane(myTree);
    splitter.setFirstComponent(scrollPane);
    final JComponent callSitesViewer = createCallSitesViewer();
    TreePath selectionPath = myTree.getSelectionPath();
    if (selectionPath == null) {
      selectionPath = new TreePath(myRoot.getPath());
      myTree.getSelectionModel().addSelectionPath(selectionPath);
    }

    final MethodNode node = (MethodNode)selectionPath.getLastPathComponent();
    updateEditorTexts(node);

    splitter.setSecondComponent(callSitesViewer);
    result.add(splitter);
    return result;
  }

  private void updateEditorTexts(final MethodNode node) {
    final MethodNode parentNode = (MethodNode)node.getParent();
    final String callerText = node != myRoot ? getText(node.getMethod()) : "";
    final Document callerDocument = myCallerEditor.getDocument();
    final String calleeText = node != myRoot ? getText(parentNode.getMethod()) : "";
    final Document calleeDocument = myCalleeEditor.getDocument();

    ApplicationManager.getApplication().runWriteAction(new Runnable() {
      public void run() {
        callerDocument.setText(callerText);
        calleeDocument.setText(calleeText);
      }
    });

    final PsiMethod caller = node.getMethod();
    final PsiMethod callee = parentNode != null ? parentNode.getMethod() : null;
    if (caller != null && callee != null) {
      HighlightManager highlighter = HighlightManager.getInstance(myProject);
      EditorColorsManager colorManager = EditorColorsManager.getInstance();
      TextAttributes attributes = colorManager.getGlobalScheme().getAttributes(EditorColors.TEXT_SEARCH_RESULT_ATTRIBUTES);
      int start = getStartOffset(caller);
      for (PsiReference ref : ReferencesSearch.search(callee, new LocalSearchScope(caller), false)) {
        final PsiElement element = ref.getElement();
        if (element != null) {
          highlighter.addRangeHighlight(myCallerEditor, element.getTextRange().getStartOffset() - start,
                                        element.getTextRange().getEndOffset() - start, attributes, false, null);
        }
      }
    }
  }

  public void dispose() {
    myTree.removeTreeSelectionListener(myTreeSelectionListener);
    EditorFactory.getInstance().releaseEditor(myCallerEditor);
    EditorFactory.getInstance().releaseEditor(myCalleeEditor);
    super.dispose();
  }

  private String getText(final PsiMethod method) {
    if (method == null) return "";
    final PsiFile file = method.getContainingFile();
    Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
    final int start = document.getLineStartOffset(document.getLineNumber(method.getTextRange().getStartOffset()));
    final int end = document.getLineEndOffset(document.getLineNumber(method.getTextRange().getEndOffset()));
    return document.getText().substring(start, end);
  }

  private int getStartOffset (@NotNull final PsiMethod method) {
    final PsiFile file = method.getContainingFile();
    Document document = PsiDocumentManager.getInstance(myProject).getDocument(file);
    return document.getLineStartOffset(document.getLineNumber(method.getTextRange().getStartOffset()));
  }

  private JComponent createCallSitesViewer() {
    Splitter splitter = new Splitter(true);
    myCallerEditor = createEditor();
    myCalleeEditor = createEditor();
    final JComponent callerComponent = myCallerEditor.getComponent();
    callerComponent.setBorder(IdeBorderFactory.createTitledBorder(RefactoringBundle.message("caller.chooser.caller.method")));
    splitter.setFirstComponent(callerComponent);
    final JComponent calleeComponent = myCalleeEditor.getComponent();
    calleeComponent.setBorder(IdeBorderFactory.createTitledBorder(RefactoringBundle.message("caller.chooser.callee.method")));
    splitter.setSecondComponent(calleeComponent);
    splitter.setBorder(IdeBorderFactory.createBorder());
    return splitter;
  }

  private Editor createEditor() {
    final EditorFactory editorFactory = EditorFactory.getInstance();
    final Document document = editorFactory.createDocument("");
    final Editor editor = editorFactory.createViewer(document, myProject);
    ((EditorEx)editor).setHighlighter(HighlighterFactory.createHighlighter(myProject, StdFileTypes.JAVA));
    return editor;
  }

  private Tree createTree() {
    final CheckedTreeNode root = new MethodNode(null, new HashSet<PsiMethod>());
    myRoot = new MethodNode(myMethod, new HashSet<PsiMethod>());
    root.add(myRoot);
    final CheckboxTree.CheckboxTreeCellRenderer cellRenderer = new CheckboxTree.CheckboxTreeCellRenderer() {
      public void customizeCellRenderer(JTree tree,
                                        Object value,
                                        boolean selected,
                                        boolean expanded,
                                        boolean leaf,
                                        int row,
                                        boolean hasFocus) {
        if (value instanceof MethodNode) {
          ((MethodNode)value).customizeRenderer(getTextRenderer());
        }
      }
    };
    Tree tree = new CheckboxTree(cellRenderer, root);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.getSelectionModel().setSelectionPath(new TreePath(myRoot.getPath()));

    return tree;
  }

  private void getSelectedMethods(Set<PsiMethod> methods) {
    MethodNode node = myRoot;
    getSelectedMethodsInner(node, methods);
    methods.remove(node.getMethod());
  }

  private static void getSelectedMethodsInner(final MethodNode node, final Set<PsiMethod> allMethods) {
    if (node.isChecked()) {
      PsiMethod method = node.getMethod();
      final PsiMethod[] superMethods = method.findDeepestSuperMethods();
      if (superMethods.length == 0) {
        allMethods.add(method);
      } else {
        for (PsiMethod superMethod : superMethods) {
          allMethods.add(superMethod);
        }
      }

      final Enumeration children = node.children();
      while (children.hasMoreElements()) {
        getSelectedMethodsInner((MethodNode)children.nextElement(), allMethods);
      }
    }
  }

  protected void doOKAction() {
    final Set<PsiMethod> selectedMethods = new HashSet<PsiMethod>();
    getSelectedMethods(selectedMethods);
    callersChosen(selectedMethods);
    super.doOKAction();
  }

  abstract protected void callersChosen(Set<PsiMethod> callers);
}


text:
<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Main Command for WooCommere CLI.
 *
 * Since a lot of WC operations can be handled via the REST API, we base our CLI
 * off of Restful to generate commands for each WooCommerce REST API endpoint
 * so most of the logic is shared.
 *
 * Forked from wp-cli/restful (by Daniel Bachhuber, released under the MIT license https://opensource.org/licenses/MIT).
 * https://github.com/wp-cli/restful
 *
 * @version 3.0.0
 * @package WooCommerce
 */
class WC_CLI_REST_Command {
	/**
	 * Endpoints that have a parent ID.
	 * Ex: Product reviews, which has a product ID and a review ID.
	 */
	protected $routes_with_parent_id = array(
		'customer_download',
		'product_review',
		'order_note',
		'shop_order_refund',
	);

	/**
	 * Name of command/endpoint object.
	 */
	private $name;

	/**
	 * Endpoint route.
	 */
	private $route;

	/**
	 * Main resource ID.
	 */
	private $resource_identifier;

	/**
	 * Schema for command.
	 */
	private $schema;

	/**
	 * Nesting level.
	 */
	private $output_nesting_level = 0;

	/**
	 * List of supported IDs and their description (name => desc).
	 */
	private $supported_ids = array();

	/**
	 * Sets up REST Command.
	 *
	 * @param string $name   Name of endpoint object (comes from schema)
	 * @param string $route  Path to route of this endpoint
	 * @param array  $schema Schema object
	 */
	public function __construct( $name, $route, $schema ) {
		$this->name   = $name;

		preg_match_all( '#\([^\)]+\)#', $route, $matches );
		$first_match  = $matches[0];
		$resource_id  = ! empty( $matches[0] ) ? array_pop( $matches[0] ) : null;
		$this->route  = rtrim( $route );
		$this->schema = $schema;

		$this->resource_identifier = $resource_id;
		if ( in_array( $name, $this->routes_with_parent_id ) ) {
			$is_singular = substr( $this->route, - strlen( $resource_id ) ) === $resource_id;
			if ( ! $is_singular ) {
				$this->resource_identifier = $first_match[0];
			}
		}
	}

	/**
	 * Passes supported ID arguments (things like product_id, order_id, etc) that we should look for in addition to id.
	 *
	 * @param array $supported_ids
	 */
	public function set_supported_ids( $supported_ids = array() ) {
		$this->supported_ids = $supported_ids;
	}

	/**
	 * Returns an ID of supported ID arguments (things like product_id, order_id, etc) that we should look for in addition to id.
	 *
	 * @return array
	 */
	public function get_supported_ids() {
		return $this->supported_ids;
	}

	/**
	 * Create a new item.
	 *
	 * @subcommand create
	 *
	 * @param array $args
	 * @param array $assoc_args
	 */
	public function create_item( $args, $assoc_args ) {
		$assoc_args = self::decode_json( $assoc_args );
		list( $status, $body ) = $this->do_request( 'POST', $this->get_filled_route( $args ), $assoc_args );
		if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
			WP_CLI::line( $body['id'] );
		} else {
			WP_CLI::success( "Created {$this->name} {$body['id']}." );
		}
	}

	/**
	 * Delete an existing item.
	 *
	 * @subcommand delete
	 *
	 * @param array $args
	 * @param array $assoc_args
	 */
	public function delete_item( $args, $assoc_args ) {
		list( $status, $body ) = $this->do_request( 'DELETE', $this->get_filled_route( $args ), $assoc_args );
		if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
			WP_CLI::line( $body['id'] );
		} else {
			if ( empty( $assoc_args['force'] ) ) {
				WP_CLI::success( __( 'Trashed', 'woocommerce' ) . " {$this->name} {$body['id']}" );
			} else {
				WP_CLI::success( __( 'Deleted', 'woocommerce' ) . " {$this->name} {$body['id']}." );
			}
		}
	}

	/**
	 * Get a single item.
	 *
	 * @subcommand get
	 *
	 * @param array $args
	 * @param array $assoc_args
	 */
	public function get_item( $args, $assoc_args ) {
		$route = $this->get_filled_route( $args );
		list( $status, $body, $headers ) = $this->do_request( 'GET', $route, $assoc_args );

		if ( ! empty( $assoc_args['fields'] ) ) {
			$body = self::limit_item_to_fields( $body, $assoc_args['fields'] );
		}

		if ( 'headers' === $assoc_args['format'] ) {
			echo json_encode( $headers );
		} elseif ( 'body' === $assoc_args['format'] ) {
			echo json_encode( $body );
		} elseif ( 'envelope' === $assoc_args['format'] ) {
			echo json_encode( array(
				'body'    => $body,
				'headers' => $headers,
				'status'  => $status,
			) );
		} else {
			$formatter = $this->get_formatter( $assoc_args );
			$formatter->display_item( $body );
		}
	}

	/**
	 * List all items.
	 *
	 * @subcommand list
	 *
	 * @param array $args
	 * @param array $assoc_args
	 */
	public function list_items( $args, $assoc_args ) {
		if ( ! empty( $assoc_args['format'] ) && 'count' === $assoc_args['format'] ) {
			$method = 'HEAD';
		} else {
			$method = 'GET';
		}

		list( $status, $body, $headers ) = $this->do_request( $method, $this->get_filled_route( $args ), $assoc_args );
		if ( ! empty( $assoc_args['format'] ) && 'ids' === $assoc_args['format'] ) {
			$items = array_column( $body, 'id' );
		} else {
			$items = $body;
		}

		if ( ! empty( $assoc_args['fields'] ) ) {
			foreach ( $items as $key => $item ) {
				$items[ $key ] = self::limit_item_to_fields( $item, $assoc_args['fields'] );
			}
		}

		if ( ! empty( $assoc_args['format'] ) && 'count' === $assoc_args['format'] ) {
			echo (int) $headers['X-WP-Total'];
		} elseif ( 'headers' === $assoc_args['format'] ) {
			echo json_encode( $headers );
		} elseif ( 'body' === $assoc_args['format'] ) {
			echo json_encode( $body );
		} elseif ( 'envelope' === $assoc_args['format'] ) {
			echo json_encode( array(
				'body'    => $body,
				'headers' => $headers,
				'status'  => $status,
				'api_url' => $this->api_url,
			) );
		} else {
			$formatter = $this->get_formatter( $assoc_args );
			$formatter->display_items( $items );
		}
	}

	/**
	 * Update an existing item.
	 *
	 * @subcommand update
	 *
	 * @param array $args
	 * @param array $assoc_args
	 */
	public function update_item( $args, $assoc_args ) {
		$assoc_args = self::decode_json( $assoc_args );
		list( $status, $body ) = $this->do_request( 'POST', $this->get_filled_route( $args ), $assoc_args );
		if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
			WP_CLI::line( $body['id'] );
		} else {
			WP_CLI::success( __( 'Updated', 'woocommerce' ) . " {$this->name} {$body['id']}." );
		}
	}

	/**
	 * Do a REST Request
	 *
	 * @param string $method
	 * @param string $route
	 * @param array  $assoc_args
	 *
	 * @return array
	 */
	private function do_request( $method, $route, $assoc_args ) {
		wc_maybe_define_constant( 'REST_REQUEST', true );

		$request = new WP_REST_Request( $method, $route );
		if ( in_array( $method, array( 'POST', 'PUT' ) ) ) {
			$request->set_body_params( $assoc_args );
		} else {
			foreach ( $assoc_args as $key => $value ) {
				$request->set_param( $key, $value );
			}
		}
		if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
			$original_queries = is_array( $GLOBALS['wpdb']->queries ) ? array_keys( $GLOBALS['wpdb']->queries ) : array();
		}
		$response = rest_do_request( $request );
		if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
			$performed_queries = array();
			foreach ( (array) $GLOBALS['wpdb']->queries as $key => $query ) {
				if ( in_array( $key, $original_queries ) ) {
					continue;
				}
				$performed_queries[] = $query;
			}
			usort( $performed_queries, function( $a, $b ) {
				if ( $a[1] === $b[1] ) {
					return 0;
				}
				return ( $a[1] > $b[1] ) ? -1 : 1;
			});

			$query_count = count( $performed_queries );
			$query_total_time = 0;
			foreach ( $performed_queries as $query ) {
				$query_total_time += $query[1];
			}
			$slow_query_message = '';
			if ( $performed_queries && 'wc' === WP_CLI::get_config( 'debug' ) ) {
				$slow_query_message .= '. Ordered by slowness, the queries are:' . PHP_EOL;
				foreach ( $performed_queries as $i => $query ) {
					$i++;
					$bits = explode( ', ', $query[2] );
					$backtrace = implode( ', ', array_slice( $bits, 13 ) );
					$seconds = round( $query[1], 6 );
					$slow_query_message .= <<<EOT
{$i}:
- {$seconds} seconds
- {$backtrace}
- {$query[0]}
EOT;
					$slow_query_message .= PHP_EOL;
				}
			} elseif ( 'wc' !== WP_CLI::get_config( 'debug' ) ) {
				$slow_query_message = '. Use --debug=wc to see all queries.';
			}
			$query_total_time = round( $query_total_time, 6 );
			WP_CLI::debug( "wc command executed {$query_count} queries in {$query_total_time} seconds{$slow_query_message}", 'wc' );
		}

		if ( $error = $response->as_error() ) {
			// For authentication errors (status 401), include a reminder to set the --user flag.
			// WP_CLI::error will only return the first message from WP_Error, so we will pass a string containing both instead.
			if ( 401 === $response->get_status() ) {
				$errors   = $error->get_error_messages();
				$errors[] = __( 'Make sure to include the --user flag with an account that has permissions for this action.', 'woocommerce' ) . ' {"status":401}';
				$error    = implode( "\n", $errors );
			}
			WP_CLI::error( $error );
		}
		return array( $response->get_status(), $response->get_data(), $response->get_headers() );
	}

	/**
	 * Get Formatter object based on supplied parameters.
	 *
	 * @param array $assoc_args Parameters passed to command. Determines formatting.
	 * @return \WP_CLI\Formatter
	 */
	protected function get_formatter( &$assoc_args ) {
		if ( ! empty( $assoc_args['fields'] ) ) {
			if ( is_string( $assoc_args['fields'] ) ) {
				$fields = explode( ',', $assoc_args['fields'] );
			} else {
				$fields = $assoc_args['fields'];
			}
		} else {
			if ( ! empty( $assoc_args['context'] ) ) {
				$fields = $this->get_context_fields( $assoc_args['context'] );
			} else {
				$fields = $this->get_context_fields( 'view' );
			}
		}
		return new \WP_CLI\Formatter( $assoc_args, $fields );
	}

	/**
	 * Get a list of fields present in a given context
	 *
	 * @param string $context
	 * @return array
	 */
	private function get_context_fields( $context ) {
		$fields = array();
		foreach ( $this->schema['properties'] as $key => $args ) {
			if ( empty( $args['context'] ) || in_array( $context, $args['context'] ) ) {
				$fields[] = $key;
			}
		}
		return $fields;
	}

	/**
	 * Get the route for this resource
	 *
	 * @param  array $args
	 * @return string
	 */
	private function get_filled_route( $args = array() ) {
		$supported_id_matched = false;
		$route                = $this->route;

		foreach ( $this->get_supported_ids() as $id_name => $id_desc ) {
			if ( strpos( $route, '<' . $id_name . '>' ) !== false && ! empty( $args ) ) {
				$route                = str_replace( '(?P<' . $id_name . '>[\d]+)', $args[0], $route );
				$supported_id_matched = true;
			}
		}

		if ( ! empty( $args ) ) {
			$id_replacement = $supported_id_matched && ! empty( $args[1] ) ? $args[1] : $args[0];
			$route          = str_replace( array( '(?P<id>[\d]+)', '(?P<id>[\w-]+)' ), $id_replacement, $route );
		}

		return rtrim( $route );
	}

	/**
	 * Output a line to be added
	 *
	 * @param string
	 */
	private function add_line( $line ) {
		$this->nested_line( $line, 'add' );
	}

	/**
	 * Output a line to be removed
	 *
	 * @param string
	 */
	private function remove_line( $line ) {
		$this->nested_line( $line, 'remove' );
	}

	/**
	 * Output a line that's appropriately nested
	 *
	 * @param string $line
	 * @param bool|string $change
	 */
	private function nested_line( $line, $change = false ) {
		if ( 'add' == $change ) {
			$label = '+ ';
		} elseif ( 'remove' == $change ) {
			$label = '- ';
		} else {
			$label = false;
		}

		$spaces = ( $this->output_nesting_level * 2 ) + 2;
		if ( $label ) {
			$line = $label . $line;
			$spaces = $spaces - 2;
		}
		WP_CLI::line( str_pad( ' ', $spaces ) . $line );
	}

	/**
	 * Whether or not this is an associative array
	 *
	 * @param array
	 * @return bool
	 */
	private function is_assoc_array( $array ) {
		if ( ! is_array( $array ) ) {
			return false;
		}
		return array_keys( $array ) !== range( 0, count( $array ) - 1 );
	}

	/**
	 * Reduce an item to specific fields.
	 *
	 * @param  array $item
	 * @param  array $fields
	 * @return array
	 */
	private static function limit_item_to_fields( $item, $fields ) {
		if ( empty( $fields ) ) {
			return $item;
		}
		if ( is_string( $fields ) ) {
			$fields = explode( ',', $fields );
		}
		foreach ( $item as $i => $field ) {
			if ( ! in_array( $i, $fields ) ) {
				unset( $item[ $i ] );
			}
		}
		return $item;
	}

	/**
	 * JSON can be passed in some more complicated objects, like the payment gateway settings array.
	 * This function decodes the json (if present) and tries to get it's value.
	 *
	 * @param array $arr
	 *
	 * @return array
	 */
	protected function decode_json( $arr ) {
		foreach ( $arr as $key => $value ) {
			if ( '[' === substr( $value, 0, 1 ) || '{' === substr( $value, 0, 1 ) ) {
				$arr[ $key ] = json_decode( $value, true );
			} else {
				continue;
			}
		}
		return $arr;
	}

}


text:
#ifndef _UTIL_IO_REDIRECTOR_H_
#define _UTIL_IO_REDIRECTOR_H_

#include <fcntl.h>
#include <mutex>
#include <stdio.h>

class IoRedirector {
    enum { bufSize = 1024 };

public:
    void start();

    void stop();

    bool is_active();

    std::string get_output(bool blocking = false);

    static IoRedirector& get() {
        static IoRedirector inst;
        return inst;
    }

private:
    enum PIPES { READ, WRITE };

    IoRedirector();

    int copy_fd(int fd);
    void create_pipes();
    void copy_fd_to(int src_fd, int destfd);
    void close_fd(int& fd);

    int m_pipe[2]{};
    int m_oldStdOut;
    int m_oldStdErr;
    bool m_capturing;
    std::mutex m_mutex;
    std::string m_captured;
};

#endif /* SC_COMPONENTS_INCL_UTIL_IO_REDIRECTOR_H_ */


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// 有关程序集的常规信息通过下列特性集
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Qiniu (Cloud) C# SDK Test - MSTest")]
[assembly: AssemblyDescription("Qiniu (Cloud) C# SDK Test - MSTest")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("QINIU")]
[assembly: AssemblyProduct("Qiniu.MSTest")]
[assembly: AssemblyCopyright("Copyright ©  2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyMetadata("TargetPlatform","UAP")]

// 程序集的版本信息由下面四个值组成:
//
//      主版本
//      次版本
//      生成号
//      修订号
//
// 可以指定所有这些值,也可以使用"生成号"和"修订号"的默认值,
// 方法是按如下所示使用"*":
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("7.2.15")]
[assembly: AssemblyFileVersion("7.2.15")]
[assembly: ComVisible(false)]


text:
<!DOCTYPE html>

    <title>infor deleted</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <link href="resources/css/jquery-ui-themes.css" type="text/css" rel="stylesheet"/>
    <link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet"/>
    <link href="data/styles.css" type="text/css" rel="stylesheet"/>
    <link href="files/infor_deleted_1/styles.css" type="text/css" rel="stylesheet"/>

Office Management System

Suplus Office Management System

Home

Assign project

Employee maintain

Customer maintain

Project maintain

Communication

Information has deleted.


text:
package moe.lymia.mppatch.util

import java.io.{OutputStreamWriter, PrintWriter, Writer}
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.{Date, TimeZone}

object Logger {
  val dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
  dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"))
}

trait Logger {
  protected def dateFormat = Logger.dateFormat
  protected def formatString = "[%s/%5s] %s"

  def logRaw(s: String): Unit
  def logException(t: Throwable): Unit
  def flush(): Unit

  def log(format: String, level: String, vals: Any*): Unit =
    logRaw(formatString.format(dateFormat.format(new Date()), level, format.format(vals: _*)))

  def info (format: String, vals: Any*): Unit = log(format, "INFO" , vals: _*)
  def warn (format: String, vals: Any*): Unit = log(format, "WARN" , vals: _*)
  def error(format: String, vals: Any*): Unit = log(format, "ERROR", vals: _*)

  def info (str: String): Unit = info ("%s", str)
  def warn (str: String): Unit = warn ("%s", str)
  def error(str: String): Unit = error("%s", str)

  def info(format: String, t: Throwable, vals: Any*): Unit = {
    info(format, vals: _*)
    logException(t)
  }
  def warn(format: String, t: Throwable, vals: Any*): Unit = {
    warn(format, vals: _*)
    logException(t)
  }
  def error(format: String, t: Throwable, vals: Any*): Unit = {
    error(format, vals: _*)
    logException(t)
  }

  def info (str: String, t: Throwable): Unit = info ("%s", t, str)
  def warn (str: String, t: Throwable): Unit = warn ("%s", t, str)
  def error(str: String, t: Throwable): Unit = error("%s", t, str)
}

class SimpleLogger(writers: Writer*) extends Logger {
  private val loggers = new scala.collection.mutable.ArrayBuffer[PrintWriter]()
  def addLogger(w: Writer) = loggers.append(w match {
    case p: PrintWriter => p
    case _ => new PrintWriter(w)
  })
  writers.foreach(addLogger)

  def flush() = loggers.foreach(_.flush())
  def logRaw(s: String) = {
    loggers.foreach(_.println(s))
    flush()
  }
  def logException(t: Throwable) = {
    loggers.foreach(t.printStackTrace)
    flush()
  }
}
object SimpleLogger extends SimpleLogger(new OutputStreamWriter(System.out, StandardCharsets.UTF_8))


text:
void foo(int a = 42, int = 42);
void bar(int a, int b = 42, int c = 42);
void baz(int a = 42, ...);
struct S{ S(int a = 42, int = 42) {} };

int main() {
    foo(42, 42);
    bar(42, 42, 42);
    baz(42, 42, 42);
    S s(42, 42);
}

// RUN: c-index-test -code-completion-at=%s:10:9 %s | FileCheck -check-prefix=CHECK-CC1 %s
// CHECK-CC1: OverloadCandidate:{ResultType void}{Text foo}{LeftParen (}{Optional {CurrentParameter int a}{Optional {Comma , }{Placeholder int}}}{RightParen )} (1)
// CHECK-CC1: Completion contexts:
// CHECK-CC1-NEXT: Any type
// CHECK-CC1-NEXT: Any value
// CHECK-CC1-NEXT: Enum tag
// CHECK-CC1-NEXT: Union tag
// CHECK-CC1-NEXT: Struct tag
// CHECK-CC1-NEXT: Class name
// CHECK-CC1-NEXT: Nested name specifier
// CHECK-CC1-NEXT: Objective-C interface

// RUN: c-index-test -code-completion-at=%s:11:9 %s | FileCheck -check-prefix=CHECK-CC2 %s
// CHECK-CC2: OverloadCandidate:{ResultType void}{Text bar}{LeftParen (}{CurrentParameter int a}{Optional {Comma , }{Placeholder int b}{Optional {Comma , }{Placeholder int c}}}{RightParen )} (1)
// CHECK-CC2: Completion contexts:
// CHECK-CC2-NEXT: Any type
// CHECK-CC2-NEXT: Any value
// CHECK-CC2-NEXT: Enum tag
// CHECK-CC2-NEXT: Union tag
// CHECK-CC2-NEXT: Struct tag
// CHECK-CC2-NEXT: Class name
// CHECK-CC2-NEXT: Nested name specifier
// CHECK-CC2-NEXT: Objective-C interface

// RUN: c-index-test -code-completion-at=%s:11:16 %s | FileCheck -check-prefix=CHECK-CC3 %s
// CHECK-CC3: OverloadCandidate:{ResultType void}{Text bar}{LeftParen (}{Placeholder int a}{Optional {Comma , }{Placeholder int b}{Optional {Comma , }{CurrentParameter int c}}}{RightParen )} (1)
// CHECK-CC3: Completion contexts:
// CHECK-CC3-NEXT: Any type
// CHECK-CC3-NEXT: Any value
// CHECK-CC3-NEXT: Enum tag
// CHECK-CC3-NEXT: Union tag
// CHECK-CC3-NEXT: Struct tag
// CHECK-CC3-NEXT: Class name
// CHECK-CC3-NEXT: Nested name specifier
// CHECK-CC3-NEXT: Objective-C interface

// RUN: c-index-test -code-completion-at=%s:12:16 %s | FileCheck -check-prefix=CHECK-CC4 %s
// CHECK-CC4: OverloadCandidate:{ResultType void}{Text baz}{LeftParen (}{Optional {Placeholder int a}{Optional {Comma , }{CurrentParameter ...}}}{RightParen )} (1)
// CHECK-CC4: Completion contexts:
// CHECK-CC4-NEXT: Any type
// CHECK-CC4-NEXT: Any value
// CHECK-CC4-NEXT: Enum tag
// CHECK-CC4-NEXT: Union tag
// CHECK-CC4-NEXT: Struct tag
// CHECK-CC4-NEXT: Class name
// CHECK-CC4-NEXT: Nested name specifier
// CHECK-CC4-NEXT: Objective-C interface

// RUN: c-index-test -code-completion-at=%s:13:9 %s | FileCheck -check-prefix=CHECK-CC5 %s
// CHECK-CC5: OverloadCandidate:{Text S}{LeftParen (}{Optional {CurrentParameter int a}{Optional {Comma , }{Placeholder int}}}{RightParen )} (1)
// CHECK-CC5: OverloadCandidate:{Text S}{LeftParen (}{CurrentParameter const S &}{RightParen )} (1)
// CHECK-CC5: Completion contexts:
// CHECK-CC5-NEXT: Any type
// CHECK-CC5-NEXT: Any value
// CHECK-CC5-NEXT: Enum tag
// CHECK-CC5-NEXT: Union tag
// CHECK-CC5-NEXT: Struct tag
// CHECK-CC5-NEXT: Class name
// CHECK-CC5-NEXT: Nested name specifier
// CHECK-CC5-NEXT: Objective-C interface


text:
<?php

namespace User\Entity;

use Base\Entity\AbstractEntity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping as ORM;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject;
use Zend\Stdlib\Hydrator\ClassMethods;

/**
 * @ORM\Entity
 * @ORM\Table(name="tbUser")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="User\Entity\UserRepository")
 */
class User extends AbstractEntity {

    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @ORM\Column(name="password", type="string", length=255)
     */
    protected $password;

    /**
     * @ORM\Column(name="role", type="string", length=255)
     */
    protected $role;

    /**
     * @ORM\Column(name="name", type="string", length=255)
     */
    protected $name;

    /**
     * @ORM\Column(name="login", type="string", length=255)
     */
    protected $login;

    /**
     * @ORM\Column(name="email", type="string", length=255)
     */
    protected $email;

    /**
     * @ORM\Column(name="updatedAt", type="datetime")
     */
    protected $updatedAt;

    /**
     * @ORM\Column(name="createdAt", type="datetime")
     */
    protected $createdAt;

    /**
     * @ORM\OneToMany(targetEntity="Form\Entity\Form", mappedBy="user")
     */
    protected $forms;

    /**
     * @ORM\OneToMany(targetEntity="Evaluation\Entity\Evaluation", mappedBy="user")
     */
    protected $evaluations;

    public function __construct(array $options = array()) {
        (new ClassMethods)->hydrate($options, $this);
        $this->createdAt = new \DateTime("now");
        $this->updatedAt = new \DateTime("now");
        $this->forms = new ArrayCollection();
        $this->evaluations = new ArrayCollection();
    }

    /** @param int $id */
    public function setId($id) {
        $this->id = $id;
    }

    /** @return int */
    public function getId() {
        return $this->id;
    }

    /** @param mixed $password */
    public function setPassword($password) {
        $this->password = $password;
    }

    /** @return mixed */
    public function getPassword() {
        return $this->password;
    }

    /** @param mixed $role */
    public function setRole($role) {
        $this->role = $role;
    }

    /** @return mixed */
    public function getRole() {
        return $this->role;
    }

    /** @param mixed $name */
    public function setName($name) {
        $this->name = $name;
    }

    /** @return mixed */
    public function getName() {
        return $this->name;
    }

    /** @param mixed $login */
    public function setLogin($login) {
        $this->login = $login;
    }

    /** @return mixed */
    public function getLogin() {
        return $this->login;
    }

    /** @param mixed $email */
    public function setEmail($email) {
        $this->email = $email;
    }

    /** @return mixed */
    public function getEmail() {
        return $this->email;
    }

    /**
     * @ORM\prePersist
     */
    public function setUpdatedAt($updatedAt) {
        $this->updatedAt = new \DateTime("now");
    }

    /** @return mixed */
    public function getUpdatedAt() {
        return $this->updatedAt;
    }

    /**
     *
     */
    public function setCreatedAt($createdAt) {
        $this->createdAt = new \DateTime("now");
    }

    /** @return mixed */
    public function getCreatedAt() {
        return $this->createdAt;
    }

    /** @param mixed $forms */
    public function setForms($forms) {
        $this->forms = $forms;
    }

    /** @return mixed */
    public function getForms() {
        return $this->forms;
    }

    /** @param mixed $evaluations */
    public function setEvaluations($evaluations) {
        $this->evaluations = $evaluations;
    }

    /** @return mixed */
    public function getEvaluations() {
        return $this->evaluations;
    }

    public function addForm($form) {
        $this->forms->add($form);
        $form->setUser($this);
    }

    public function addEvaluation($evaluation) {
        $this->evaluations->add($evaluation);
        $evaluation->setUser($this);
    }

}


text:
use Bio::EnsEMBL::Registry;
Bio::EnsEMBL::Registry->load_registry_from_url('mysql://anonymous@ensembldb.ensembl.org:5306/');


text:
namespace System.Reflection.Emit
{

#if CONFIG_REFLECTION_EMIT

public struct FieldToken
{
	// The empty token.
	public static readonly FieldToken Empty;

	// Internal state.
	private int token;

	// Constructor.
	internal FieldToken(int token)
			{
				this.token = token;
			}

	// Get the token code.
	public int Token
			{
				get
				{
					return token;
				}
			}

	// Determine if this token is identical to another.
	public override bool Equals(Object obj)
			{
				if(obj is FieldToken)
				{
					return (token == ((FieldToken)obj).token);
				}
				else
				{
					return false;
				}
			}

	// Get a hash code for this token.
	public override int GetHashCode()
			{
				return token;
			}

}; // struct FieldToken

#endif // CONFIG_REFLECTION_EMIT

}; // namespace System.Reflection.Emit


text:
public class JavaClass {
    public static void main(String[] args) {
        new one.two.three.Boo.Doo.Foo();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>dblink_send_query</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.6.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="dblink"
HREF="dblink.html"><LINK
REL="PREVIOUS"
TITLE="dblink_error_message"
HREF="contrib-dblink-error-message.html"><LINK
REL="NEXT"
TITLE="dblink_is_busy"
HREF="contrib-dblink-is-busy.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2017-02-06T21:56:32">

PostgreSQL 9.6.2 Documentation

Prev	Up		Next

dblink_send_query

Name
dblink_send_query -- sends an async query to a remote database

Synopsis

dblink_send_query(text connname, text sql) returns int

Description

    dblink_send_query sends a query to be executed
    asynchronously, that is, without immediately waiting for the result.
    There must not be an async query already in progress on the
    connection.

    After successfully dispatching an async query, completion status
    can be checked with dblink_is_busy, and the results
    are ultimately collected with dblink_get_result.
    It is also possible to attempt to cancel an active async query
    using dblink_cancel_query.

Arguments

<TT
CLASS="PARAMETER"
>connname</TT
>

       Name of the connection to use.

<TT
CLASS="PARAMETER"
>sql</TT
>

       The SQL statement that you wish to execute in the remote database,
       for example <TT
CLASS="LITERAL"
>select * from pg_class</TT
>.

Return Value

    Returns 1 if the query was successfully dispatched, 0 otherwise.

Examples

SELECT dblink_send_query('dtest1', 'SELECT * FROM foo WHERE f1 < 3');

Prev	Home	Next

dblink_error_message	Up	dblink_is_busy


text:
<?php

namespace ApiPlatform\Core\Serializer;

/**
 * Creates and manipulates the Serializer context.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
trait ContextTrait
{
    /**
     * Initializes the context.
     *
     * @param string $resourceClass
     * @param array  $context
     *
     * @return array
     */
    private function initContext(string $resourceClass, array $context): array
    {
        if (isset($context['api_sub_level'])) {
            return $context;
        }

        return array_merge($context, [
            'api_sub_level' => true,
            'resource_class' => $resourceClass,
        ]);
    }
}


text:
<?php

namespace Cliente\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Propel;

class EnderecosController extends AbstractActionController
{
    public function indexAction()
    {
        $cliente = \ClienteQuery::create()->find();
        return array('message' => $this->getFlashMessenger(),
                    'aCliente'=>$cliente);
    }
    public function novoAction()
    {
        $idcli = (int) $this->params()->fromRoute('idcli', 0);
        $id = (int) $this->params()->fromRoute('id', 0);

        if($idcli == ""){
            return $this->redirect()->toRoute('clientes');
        }

        $cliente = \ClienteQuery::create()
                ->filterByCoCliente($idcli)
                ->findOne();

                $uf = array("RJ"=>"Rio de Janeiro",
                        "AC"=>"Acre",
                        "AL"=>"Alagoas", "AM"=>"Amazonas",
                        "AP"=>"Amapá","BA"=>"Bahia","CE"=>"Ceará",
                        "DF"=>"Distrito Federal","ES"=>"Espírito Santo",
                        "GO"=>"Goiás","MA"=>"Maranhão","MT"=>"Mato Grosso",
                        "MS"=>"Mato Grosso do Sul","MG"=>"Minas Gerais",
                        "PA"=>"Pará","PB"=>"Paraíba","PR"=>"Paraná",
                        "PE"=>"Pernambuco","PI"=>"Piauí",
                        "RN"=>"Rio Grande do Norte","RO"=>"Rondônia",
                        "RS"=>"Rio Grande do Sul","RR"=>"Roraima",
                        "SC"=>"Santa Catarina","SE"=>"Sergipe",
                        "SP"=>"São Paulo","TO"=>"Tocantins");

        return array('message' => $this->getFlashMessenger(),
                    'cliente'=>$cliente,
                    'uf'=>$uf,
                    'co_pessoa'=>$idcli);
    }
    public function adicionarAction()
    {
        $request = $this->getRequest();

        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();

            $formularioValido = true;

            if ($formularioValido) {
                try{
                    \EnderecoPeer::gravaEndereco($postData);
                }  catch (Exception $e){
                    $this->flashMessenger()->addSuccessMessage($e->getMessage());
                    return $this->redirect()->toRoute('clientes',
                             array('action'=>'detalhes',
                                    'id'=>$postData['co_pessoa']));
                }

                $this->flashMessenger()->addSuccessMessage("Endereço adicionado com sucesso");

                return $this->redirect()->toRoute('clientes',
                             array('action'=>'detalhes',
                                    'id'=>$postData['co_pessoa']));
            } else {
                $this->flashMessenger()->addErrorMessage("Erro ao adicionar endereço");
                return $this->redirect()->toRoute('clientes');
            }
        }
    }
    public function editarAction()
    {
        $co_endereco = (int) $this->params()->fromRoute('id', 0);
        $co_pessoa = (int) $this->params()->fromRoute('idcli', 0);

        if ($co_endereco == "") {
            $this->flashMessenger()->addErrorMessage("Endereço não encotrado");
            return $this->redirect()->toRoute('clientes',
                                      array('action'=>'detalhes',
                                            'id'=>$co_pessoa));
        }
        $cliente = \ClienteQuery::create()
                ->filterByCoCliente($co_pessoa)
                ->findOne();

        $oEndereco = \EnderecoQuery::create()
                ->filterByCoEndereco($co_endereco)
                ->findOne();

           $uf = array("RJ"=>"Rio de Janeiro",
                        "AC"=>"Acre",
                        "AL"=>"Alagoas", "AM"=>"Amazonas",
                        "AP"=>"Amapá","BA"=>"Bahia","CE"=>"Ceará",
                        "DF"=>"Distrito Federal","ES"=>"Espírito Santo",
                        "GO"=>"Goiás","MA"=>"Maranhão","MT"=>"Mato Grosso",
                        "MS"=>"Mato Grosso do Sul","MG"=>"Minas Gerais",
                        "PA"=>"Pará","PB"=>"Paraíba","PR"=>"Paraná",
                        "PE"=>"Pernambuco","PI"=>"Piauí",
                        "RN"=>"Rio Grande do Norte","RO"=>"Rondônia",
                        "RS"=>"Rio Grande do Sul","RR"=>"Roraima",
                        "SC"=>"Santa Catarina","SE"=>"Sergipe",
                        "SP"=>"São Paulo","TO"=>"Tocantins");

        return array('co_telefone' => $co_endereco,
                    'oEndereco' => $oEndereco,
                    'co_endereco' => $co_endereco,
                    'co_pessoa' => $co_pessoa,
                    'cliente' => $cliente,
                    'uf' => $uf,
                    'message' => $this->getFlashMessenger());
    }
    public function atualizarAction()
    {
        $request = $this->getRequest();

        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $formularioValido = true;

            if ($formularioValido) {
                try{
                    \EnderecoPeer::gravaEndereco($postData);
                }  catch (Exception $e){
                    $this->flashMessenger()->addSuccessMessage($e->getMessage());
                    return $this->redirect()->toRoute('clientes');
                }
                $this->flashMessenger()->addSuccessMessage("Endereço editado com sucesso");
                return $this->redirect()->toRoute('clientes',
                                             array('action' => "detalhes",
                                                   'id' => $postData['co_pessoa'],));
            } else {
                $this->flashMessenger()->addErrorMessage("Erro ao editar endereço");
                return $this->redirect()->toRoute('clientes');
            }
        }
    }
    public function deletarAction()
    {
        $co_endereco = $this->params()->fromRoute('id', 0);
        $idcli = $this->params()->fromRoute('idcli', 0);

        if($co_endereco != "" && is_numeric($co_endereco)){
                try{

                    $oEndereco = \EnderecoQuery::create()
                            ->filterByCoEndereco($co_endereco)
                            ->findOne();

                    $oEndereco->delete();

                    $this->flashMessenger()->addSuccessMessage("Endereço deletado com sucesso");

                    return $this->redirect()->toRoute('clientes',
                                array('action'=>'detalhes','id'=>$idcli));

                }  catch (Exception $e){
                    $this->flashMessenger()->addSuccessMessage($e->getMessage());
                    return $this->redirect()->toRoute('clientes',
                             array('action'=>'detalhes',
                                 'id'=>$idcli));
                }
        }else{
             $this->flashMessenger()->addErrorMessage("Endereço não encotrado");
        }
        return $this->redirect()->toRoute('clientes');
    }

    // Filter Flash Messenger
    private function getFlashMessenger()
    {
        $messenger = array();
        $flashMessenger = $this->flashMessenger();

        if ($flashMessenger->hasSuccessMessages())
            $messenger['alert-success'] = array_shift($flashMessenger->getSuccessMessages());

        if ($flashMessenger->hasErrorMessages())
            $messenger['alert-error'] = array_shift($flashMessenger->getErrorMessages());

        if ($flashMessenger->hasInfoMessages())
            $messenger['alert-info'] = array_shift($flashMessenger->getInfoMessages());

        return $messenger;
    }
}


text:
> Super-simple modals in vanilla JavaScript.

## Features

- Define DOM elements on which to trigger show and hide on `click`
- Trigger show and hide programmatically
- Apply a fade effect
- Vertically centre the modal dialog box on the page
- Hide the modal on hitting the `<Esc>` key
- Zero dependencies; 2.3 KB [minified](modal.min.js) or 1.0 KB minified and gzipped

## Usage

> [**Editable demo**](https://jsfiddle.net/ms31msb0/)

```html
<!DOCTYPE html>
<html>
  <head>
    <title>modal</title>
    <meta charset="utf-8">
    <style>
      .modal {background: rgba(0,0,0,.25); }
      .modal__dialog {width: 300px; margin: 25px 0; background: #fff; }
    </style>
  </head>
  <body>

    <button class="js-modal-show">Show</button>
    <div style="height: 1000px;"><!-- page content --></div>

    <div class="modal">
      <div class="modal__dialog">
        <button class="js-modal-hide">Hide</button>
        <div style="height: 1000px;"><!-- modal content --></div>
      </div>
    </div>

    <script src="path/to/modal.min.js"></script>
    <script>
      var elem = document.querySelector('.modal');
      var opts = {
        showSelector: '.js-modal-show',
        hideSelector: '.js-modal-hide',
        dialogSelector: '.modal__dialog',
        fade: {
          duration: '.2s',
          timingFunction: 'ease'
        }
      };
      modal(elem, opts);
    </script>

  </body>
</html>
```

In the browser, the `modal` function is a global variable. In Node, do:

```js
var modal = require('@yuanqing/modal');
```

### var m = modal(elem [, opts])

- `elem` — A DOM element.

- `opts` — An object literal:

  Key | Description | Default
  :--|:--|:--
  `dialogSelector` | Selector for the dialog box DOM element | `.modal__dialog`
  `showSelector` | Clicking on elements that match this selector will show the modal | `.js-modal-show`
  `hideSelector` | Clicking on elements that match this selector will hide the modal | `.js-modal-hide`
  `scrollTop` | Whether to always scroll to the top of the modal when it is shown | `true`
  `fade` | Whether to apply a fade effect | If truthy, `{ duration: .2s, timingFunction: 'ease' }`, else `false`
  `onShow` | Called when the modal is shown | `function() {}`
  `onShowEnd` | Called at the end of the fade-in effect | `function() {}`
  `onHide` | Called when the modal is hidden | `function() {}`
  `onShowEnd` | Called at the end of the fade-out effect | `function() {}`

  - The signature of the `onShow` and `onHide` callbacks is `(elem, triggerElem)`, where `triggerElem` is the particular DOM element that triggered the show or hide.
  - The signature of the `onShowEnd` and `onHideEnd` callbacks is `(elem)`. If `fade` is `false`, these callbacks are invoked immediately after `onShow` and `onHide` respectively.

### m.show()

Shows the modal.

### m.hide()

Hides the modal.

### m.isVisible

Is `true` when the modal is visible, else is `false`.

## Implementation details

- Vertically centering the modal dialog box is achieved using the technique described in the CSS Tricks article [Centering In the Unknown](https://css-tricks.com/centering-in-the-unknown/). The

- These are the initial [inline styles](https://github.com/jonathanong/component-style-guide#inline-css-if-possible) applied on the modal `elem`:

  ```
  display: none;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  overflow: auto;
  text-align: center;
  will-change: transform;
  ```

- When fading in:

  1. Set `overflow: hidden` on `body`
  2. Set `opacity: 0` and `display: block` on the modal `elem`
  3. On the next tick, set `opacity: 1` on `elem`

- When fading out:

  1. Unset `overflow: hidden` on `body`
  2. Set `opacity: 0` on the modal `elem`
  3. At the end of the CSS transition, set `display: none` on `elem`

## Installation

Install via [npm](https://www.npmjs.com):

```
$ npm i --save @yuanqing/modal
```

Install via [bower](http://bower.io):

```
$ bower i --save yuanqing/modal
```

## Changelog

- 0.0.1
  - Initial release

## License

[MIT](LICENSE)