text:
package com.ea.orbit.actors.transactions;

import com.ea.orbit.actors.Actor;
import com.ea.orbit.actors.Stage;
import com.ea.orbit.actors.test.ActorBaseTest;
import com.ea.orbit.concurrent.Task;

import org.junit.Test;

import java.util.concurrent.ExecutionException;

import static com.ea.orbit.actors.transactions.TransactionUtils.transaction;
import static com.ea.orbit.async.Await.await;
import static org.junit.Assert.assertEquals;

/**
 *
 */
public class DisjunctTransactionTest extends ActorBaseTest
{
    public interface Disjunct extends Actor
    {
        Task<Integer> local(int i1, int i2);

        Task<Integer> getBalance();

        Task<Integer> singleLevel(int i1);

        Task<Integer> remote(int i1, Disjunct other, int i2);
    }

    public static class DisjunctActor extends EventSourcedActor<DisjunctActor.State> implements Disjunct
    {
        public static class State extends TransactionalState
        {
            int balance;

            @TransactionalEvent
            void incrementBalance(int amount)
            {
                balance += amount;
            }
        }

        @Override
        public Task<Integer> local(int i1, int i2)
        {
            // Start Transaction
            await(transaction(() ->
            {
                state().incrementBalance(i1);
                if (i1 < 0)
                {
                    throw new IllegalArgumentException("i1: " + i1);
                }
                return Task.done();
            }));
            await(transaction(() ->
            {
                state().incrementBalance(i2);
                if (i2 < 0)
                {
                    throw new IllegalArgumentException("i2: " + i2);
                }
                return Task.done();
            }));
            return Task.fromValue(state().balance);
            // End Transaction
        }

        @Override
        public Task<Integer> remote(int i1, Disjunct other, int i2)
        {

            // Start Transaction
            await(transaction(() ->
            {
                state().incrementBalance(i1);
                if (i1 < 0)
                {
                    // the nested transaction was completed
                    // this will force the parent to cancel the nested
                    throw new IllegalArgumentException("i1: " + i1);
                }
                return Task.done();
            }));
            final int r1 = await(other.singleLevel(i2));
            return Task.fromValue(state().balance + r1);
            // End Transaction
        }

        @Override
        public Task<Integer> singleLevel(int i)
        {
            return transaction(() ->
            {
                state().incrementBalance(i);
                if (i < 0)
                {
                    throw new IllegalArgumentException("i: " + i);
                }
                return Task.fromValue(state().balance);
            });
        }

        @Override
        public Task<Integer> getBalance()
        {
            return Task.fromValue(state().balance);
        }

        @Override
        public Task<?> activateAsync()
        {
            getLogger().info("activate");
            return super.activateAsync();
        }
    }

    @Test
    public void disjuntSuccessful() throws ExecutionException, InterruptedException
    {
        Stage stage = createStage();

        Disjunct jimmy = Actor.getReference(Disjunct.class, "1");
        assertEquals(3, (int) jimmy.local(1, 2).join());
    }

    @Test(timeout = 10_000L)
    public void localFailureInTheSecond() throws ExecutionException, InterruptedException
    {
        Stage stage = createStage();

        Disjunct jimmy = Actor.getReference(Disjunct.class, "1");
        assertEquals(6, (int) jimmy.local(1, 5).join());

        assertEquals("i2: -20", expectException(() -> jimmy.local(10, -20).join()).getCause().getMessage());

        // the first transaction is not cancelled
        eventually(() -> assertEquals(16, (int) jimmy.getBalance().join()));
    }

    @Test(timeout = 10_000L)
    public void localFailureInTheFirst() throws ExecutionException, InterruptedException
    {
        Stage stage = createStage();

        Disjunct jimmy = Actor.getReference(Disjunct.class, "1");
        assertEquals(3, (int) jimmy.local(1, 2).join());

        assertEquals("i1: -1", expectException(() -> jimmy.local(-1, 2).join()).getCause().getMessage());
        // the second transaction never happens
        eventually(() -> assertEquals(3, (int) jimmy.getBalance().join()));
    }

    @Test
    public void remote() throws ExecutionException, InterruptedException
    {
        Stage stage = createStage();

        Disjunct jimmy = Actor.getReference(Disjunct.class, "1");
        Disjunct other = Actor.getReference(Disjunct.class, "other");
        assertEquals(3, (int) jimmy.remote(1, other, 2).join());
        assertEquals(1, (int) jimmy.getBalance().join());
        assertEquals(2, (int) other.getBalance().join());
    }

    @Test
    public void remoteFailureInTheSecond() throws ExecutionException, InterruptedException
    {
        Stage stage = createStage();

        Disjunct jimmy = Actor.getReference(Disjunct.class, "1");
        Disjunct other = Actor.getReference(Disjunct.class, "other");
        assertEquals(3, (int) jimmy.remote(1, other, 2).join());
        assertEquals(1, (int) jimmy.getBalance().join());
        assertEquals(2, (int) other.getBalance().join());

        assertEquals("i: -2", expectException(() -> jimmy.remote(1, other, -2).join()).getCause().getMessage());

        // the first transaction is not canceled
        eventually(() -> assertEquals(2, (int) jimmy.getBalance().join()));
        // the second transaction was reverted
        eventually(() -> assertEquals(2, (int) other.getBalance().join()));
    }

    @Test
    public void remoteFailureInTheFirst() throws ExecutionException, InterruptedException
    {
        Stage stage = createStage();

        Disjunct jimmy = Actor.getReference(Disjunct.class, "1");
        Disjunct other = Actor.getReference(Disjunct.class, "other");
        // a successful transaction
        assertEquals(3, (int) jimmy.remote(1, other, 2).join());

        // the failure
        assertEquals("i1: -1", expectException(() -> jimmy.remote(-1, other, 2).join()).getCause().getMessage());

        eventually(() -> assertEquals(1, (int) jimmy.getBalance().join()));
        assertEquals(2, (int) other.getBalance().join());
        dumpMessages();
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.polyglotted.attributerepo.git.common;

public abstract class GitConstants {

    public static final String HTTP_SCHEME = "http";
    public static final String HTTPS_SCHEME = "https";

    public static final String HEADER_USER_AGENT = "User-Agent";
    public static final String HEADER_ACCEPT = "Accept";
    public static final String HEADER_CONTENT_TYPE = "Content-Type";
    public static final String HEADER_CONTENT_LENGTH = "Content-Length";
    public static final String HEADER_AUTHORIZATION = "Authorization";

    public static final String USER_AGENT = "AttribRepo/1.0.0";
    public static final String CONTENT_TYPE_JSON = "application/json";
    public static final String DEFAULT_CONTENT_TYPE = CONTENT_TYPE_JSON + "; charset=UTF-8";
    public static final String CHARSET_ISO_8859_1 = "ISO-8859-1";
    public static final String AUTH_TOKEN = "token ";
    public static final String BASIC_AUTH = "Basic ";

    public static final String CREDENTIALS = "credentials";
    public static final String URL_PREFIX = "urlPrefix";

    public static final String DEFAULT_FILE = ".properties";
    public static final String FILE_PREFIX = "-";
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/ly_system_parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#282d31">

        <LinearLayout
            android:id="@+id/ly_system_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:visibility="gone" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            >
            <ImageView
                android:id="@+id/iv_back"
                android:layout_width="100px"
                android:layout_height="100px"
                android:padding="18px"
                android:layout_centerVertical="true"
                android:visibility="invisible"/>
            <TextView
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:layout_marginLeft="100dp"
                android:layout_marginRight="100dp"
                android:textColor="#ffffff"
                android:layout_centerInParent="true"
                android:textSize="54px"
                android:singleLine="true"
                android:text="图片选择"
                />

            <TextView
                android:id="@+id/tv_right"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:paddingLeft="12dp"
                android:paddingRight="12dp"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:layout_marginRight="12dp"
                android:text="(5/10)"
                android:textColor="#ffffff"
                android:textSize="18sp"
                android:gravity="center"
                android:background="@drawable/blue_item_r"
                android:layout_centerVertical="true"
                android:layout_alignParentRight="true"/>
        </RelativeLayout>
    </LinearLayout>
</LinearLayout>


text:
package net.spy.memcached.vbucket;

import net.spy.memcached.vbucket.config.Bucket;

public class ReconfigurableMock implements Reconfigurable {
    public void reconfigure(Bucket bucket) {
    }
}


text:
"""Entity tests for mobile_app."""
from http import HTTPStatus

from homeassistant.const import STATE_OFF
from homeassistant.helpers import device_registry as dr

async def test_sensor(hass, create_registrations, webhook_client):
    """Test that sensors can be registered and updated."""
    webhook_id = create_registrations[1]["webhook_id"]
    webhook_url = f"/api/webhook/{webhook_id}"

    reg_resp = await webhook_client.post(
        webhook_url,
        json={
            "type": "register_sensor",
            "data": {
                "attributes": {"foo": "bar"},
                "device_class": "plug",
                "icon": "mdi:power-plug",
                "name": "Is Charging",
                "state": True,
                "type": "binary_sensor",
                "unique_id": "is_charging",
            },
        },
    )

    assert reg_resp.status == HTTPStatus.CREATED

    json = await reg_resp.json()
    assert json == {"success": True}
    await hass.async_block_till_done()

    entity = hass.states.get("binary_sensor.test_1_is_charging")
    assert entity is not None

    assert entity.attributes["device_class"] == "plug"
    assert entity.attributes["icon"] == "mdi:power-plug"
    assert entity.attributes["foo"] == "bar"
    assert entity.domain == "binary_sensor"
    assert entity.name == "Test 1 Is Charging"
    assert entity.state == "on"

    update_resp = await webhook_client.post(
        webhook_url,
        json={
            "type": "update_sensor_states",
            "data": [
                {
                    "icon": "mdi:battery-unknown",
                    "state": False,
                    "type": "binary_sensor",
                    "unique_id": "is_charging",
                },
                # This invalid data should not invalidate whole request
                {
                    "type": "binary_sensor",
                    "unique_id": "invalid_state",
                    "invalid": "data",
                },
            ],
        },
    )

    assert update_resp.status == HTTPStatus.OK

    json = await update_resp.json()
    assert json["invalid_state"]["success"] is False

    updated_entity = hass.states.get("binary_sensor.test_1_is_charging")
    assert updated_entity.state == "off"
    assert "foo" not in updated_entity.attributes

    dev_reg = dr.async_get(hass)
    assert len(dev_reg.devices) == len(create_registrations)

    # Reload to verify state is restored
    config_entry = hass.config_entries.async_entries("mobile_app")[1]
    await hass.config_entries.async_unload(config_entry.entry_id)
    await hass.async_block_till_done()
    unloaded_entity = hass.states.get("binary_sensor.test_1_is_charging")
    assert unloaded_entity.state == "unavailable"

    await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()
    restored_entity = hass.states.get("binary_sensor.test_1_is_charging")
    assert restored_entity.state == updated_entity.state
    assert restored_entity.attributes == updated_entity.attributes

async def test_sensor_must_register(hass, create_registrations, webhook_client):
    """Test that sensors must be registered before updating."""
    webhook_id = create_registrations[1]["webhook_id"]
    webhook_url = f"/api/webhook/{webhook_id}"
    resp = await webhook_client.post(
        webhook_url,
        json={
            "type": "update_sensor_states",
            "data": [
                {"state": True, "type": "binary_sensor", "unique_id": "battery_state"}
            ],
        },
    )

    assert resp.status == HTTPStatus.OK

    json = await resp.json()
    assert json["battery_state"]["success"] is False
    assert json["battery_state"]["error"]["code"] == "not_registered"

async def test_sensor_id_no_dupes(hass, create_registrations, webhook_client, caplog):
    """Test that a duplicate unique ID in registration updates the sensor."""
    webhook_id = create_registrations[1]["webhook_id"]
    webhook_url = f"/api/webhook/{webhook_id}"

    payload = {
        "type": "register_sensor",
        "data": {
            "attributes": {"foo": "bar"},
            "device_class": "plug",
            "icon": "mdi:power-plug",
            "name": "Is Charging",
            "state": True,
            "type": "binary_sensor",
            "unique_id": "is_charging",
        },
    }

    reg_resp = await webhook_client.post(webhook_url, json=payload)

    assert reg_resp.status == HTTPStatus.CREATED

    reg_json = await reg_resp.json()
    assert reg_json == {"success": True}
    await hass.async_block_till_done()

    assert "Re-register" not in caplog.text

    entity = hass.states.get("binary_sensor.test_1_is_charging")
    assert entity is not None

    assert entity.attributes["device_class"] == "plug"
    assert entity.attributes["icon"] == "mdi:power-plug"
    assert entity.attributes["foo"] == "bar"
    assert entity.domain == "binary_sensor"
    assert entity.name == "Test 1 Is Charging"
    assert entity.state == "on"

    payload["data"]["state"] = False
    dupe_resp = await webhook_client.post(webhook_url, json=payload)

    assert dupe_resp.status == HTTPStatus.CREATED
    dupe_reg_json = await dupe_resp.json()
    assert dupe_reg_json == {"success": True}
    await hass.async_block_till_done()

    assert "Re-register" in caplog.text

    entity = hass.states.get("binary_sensor.test_1_is_charging")
    assert entity is not None

    assert entity.attributes["device_class"] == "plug"
    assert entity.attributes["icon"] == "mdi:power-plug"
    assert entity.attributes["foo"] == "bar"
    assert entity.domain == "binary_sensor"
    assert entity.name == "Test 1 Is Charging"
    assert entity.state == "off"

async def test_register_sensor_no_state(hass, create_registrations, webhook_client):
    """Test that sensors can be registered, when there is no (unknown) state."""
    webhook_id = create_registrations[1]["webhook_id"]
    webhook_url = f"/api/webhook/{webhook_id}"

    reg_resp = await webhook_client.post(
        webhook_url,
        json={
            "type": "register_sensor",
            "data": {
                "name": "Is Charging",
                "state": None,
                "type": "binary_sensor",
                "unique_id": "is_charging",
            },
        },
    )

    assert reg_resp.status == HTTPStatus.CREATED

    json = await reg_resp.json()
    assert json == {"success": True}
    await hass.async_block_till_done()

    entity = hass.states.get("binary_sensor.test_1_is_charging")
    assert entity is not None

    assert entity.domain == "binary_sensor"
    assert entity.name == "Test 1 Is Charging"
    assert entity.state == STATE_OFF  # Binary sensor defaults to off

    reg_resp = await webhook_client.post(
        webhook_url,
        json={
            "type": "register_sensor",
            "data": {
                "name": "Backup Is Charging",
                "type": "binary_sensor",
                "unique_id": "backup_is_charging",
            },
        },
    )

    assert reg_resp.status == HTTPStatus.CREATED

    json = await reg_resp.json()
    assert json == {"success": True}
    await hass.async_block_till_done()

    entity = hass.states.get("binary_sensor.test_1_backup_is_charging")
    assert entity

    assert entity.domain == "binary_sensor"
    assert entity.name == "Test 1 Backup Is Charging"
    assert entity.state == STATE_OFF  # Binary sensor defaults to off

async def test_update_sensor_no_state(hass, create_registrations, webhook_client):
    """Test that sensors can be updated, when there is no (unknown) state."""
    webhook_id = create_registrations[1]["webhook_id"]
    webhook_url = f"/api/webhook/{webhook_id}"

    reg_resp = await webhook_client.post(
        webhook_url,
        json={
            "type": "register_sensor",
            "data": {
                "name": "Is Charging",
                "state": True,
                "type": "binary_sensor",
                "unique_id": "is_charging",
            },
        },
    )

    assert reg_resp.status == HTTPStatus.CREATED

    json = await reg_resp.json()
    assert json == {"success": True}
    await hass.async_block_till_done()

    entity = hass.states.get("binary_sensor.test_1_is_charging")
    assert entity is not None
    assert entity.state == "on"

    update_resp = await webhook_client.post(
        webhook_url,
        json={
            "type": "update_sensor_states",
            "data": [
                {"state": None, "type": "binary_sensor", "unique_id": "is_charging"}
            ],
        },
    )

    assert update_resp.status == HTTPStatus.OK

    json = await update_resp.json()
    assert json == {"is_charging": {"success": True}}

    updated_entity = hass.states.get("binary_sensor.test_1_is_charging")
    assert updated_entity.state == STATE_OFF  # Binary sensor defaults to off


text:
var program = require('commander')

var pkg = require('./package.json')
  , common = require('./common.js')
  , plugins = require('./plugins.js')

program
  .version(pkg.version)
  .description(pkg.description)

program
  .option('--debug', 'output debbuging messages')

program
  .command('plugins')
  .description('list proxyvator plugins installed')
  .action(function () {
    plugins.list()
  })

program
  .command('setup')
  .description('setup configuration for developing behind the proxy')
  .option('--http <url>', 'set url for http proxy (e.g. http://myproxy.com:8080)', common.urlValidator)
  .option('--https <url>', 'set url for https proxy (e.g. https://me:mypass@myproxy.com:443', common.urlValidator)
  .option('--same', 'use the same http proxy for https')
  .option('--save', 'save settings')
  .action(function (options) {
    var self = this

    common.setHelpFn(function () {
      self.outputHelp()
    })
    common.setDebug(options.parent.debug)

    if (options.http === false) common.error(1, 'Bad http proxy url defined')
    if (options.https === false) common.error(1, 'Bad https proxy url defined')

    if (options.save === true && options.http === undefined && options.https === undefined) common.error(2, 'Cannot save without http or https definition')
    if (options.http === undefined && options.https === undefined) {
      var opts = common.loadSettings(options)
      if (opts === false) common.error(3, 'No configuration saved previously')
      common.debug('Options loaded:', opts)
    } else if(options.save) {
      common.saveSettings(options)
    }

    if (options.same === true) {
      if (options.http !== undefined && options.https === undefined) {
        options.https = options.http
      } else {
        common.error(4, 'Cannot use the same http proxy for https if http is not defined')
      }
    }

    options.home = process.env.HOME
    common.debug('HOME=', options.home)

    console.log('Setting up...')
    plugins.setup(options)
  })

program
  .command('clear')
  .description('clear configuration for developing behind the proxy')
  .action(function (options) {
    var self = this

    common.setHelpFn(function () {
      self.outputHelp()
    })
    if (options !== undefined) common.setDebug(options.parent.debug)

    options.home = process.env.HOME
    common.debug('HOME=', options.home)

    console.log('Clearing...')
    plugins.clear(options)
  })

program.parse(process.argv)

if (!program.args.length) {
  program.help()
  process.exit()
}


text:
class Statement;
class Exp;
class LocationSet;
class RTL;
class Range;
class RangeMap;
class Type;

class Log
{
public:
	Log() { }
	virtual Log &operator<<(const char *str) = 0;
	virtual Log &operator<<(Statement *s);
	virtual Log &operator<<(Exp *e);
	virtual Log &operator<<(Type *ty);
	virtual Log &operator<<(RTL *r);
	virtual Log &operator<<(Range *r);
	virtual Log &operator<<(Range &r);
	virtual Log &operator<<(RangeMap &r);
	virtual Log &operator<<(int i);
	virtual Log &operator<<(char c);
	virtual Log &operator<<(double d);
	virtual Log &operator<<(ADDRESS a);
	virtual Log &operator<<(LocationSet *l);
			Log &operator<<(std::string& s) {return operator<<(s.c_str());}
	virtual ~Log() {};
	virtual void tail();
};

class FileLogger : public Log {
protected:
	std::ofstream out;
public:
			FileLogger();		// Implemented in boomerang.cpp
	void	tail();
	virtual Log &operator<<(const char *str) {
		out << str << std::flush;
		return *this;
	}
	virtual ~FileLogger() {};
};

// For older MSVC compilers
#if defined(_MSC_VER) && (_MSC_VER <= 1200)
static std::ostream& operator<<(std::ostream& s, QWord val)
{
	char szTmp[42]; // overkill, but who counts
	sprintf(szTmp, "%I64u", val);
	s << szTmp;
	return s;
}
#endif

#endif


text:
import os
import glob
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

def fill_corr_matrices(files):

    # Generate empty matrices to fill
    corr = np.zeros((len(files),24,24,5))
    zcorr = np.zeros((len(files),24,24,5))
    avgcorr = np.zeros((24,24,5))

    # Loop through subjects, generating correlation matrices for each condition
    subj = 0
    for f in files:
        data = np.loadtxt(f)
        x, y = data.shape
        seeds = y//8
        data = data.reshape(x,seeds,8)

        for c in range(data.shape[0]):
            corr[subj,:,:,c] = np.corrcoef(data[c])
            zcorr[subj,:,:,c] = np.arctanh(corr[subj,:,:,c].round(3))
        subj += 1

    avgcorr = zcorr.mean(axis = 0)
    return avgcorr

def plot_corr_matrices(avgcorr,group):
    # Average matrices and project correlation matrices for each condition
    transcorr = np.tanh(avgcorr)
    condNames = ['Control', 'Null', 'Past', 'Future', 'Other']
    for cond in range(5):
        sns.set(style = "white") # set seaborn style
        f, ax = plt.subplots(figsize = (11, 9)) # generate empty figure
        sns.heatmap(transcorr[:,:,cond], cmap = "RdBu_r", center = 0, square = True,
                    xticklabels=['PFCdp','IPL','STS','MPFC','pHG','PCC','FEF', 'IPS', 'SPL7a', 'MT+', 'SPL7p','PrCv'],
                    yticklabels=['PFCdp','IPL','STS','MPFC','pHG','PCC','FEF', 'IPS', 'SPL7a', 'MT+', 'SPL7p','PrCv'])
        plt.axvline(6, color='k', lw = 1.5)
        plt.axhline(6, color='k', lw = 1.5)
        plt.savefig("corrMatrix_%s_%s.png" % (group, condNames[cond]))

if __name__ == '__main__':

    # Select files
    Youngfiles = glob.glob('YeoCogNets_nbhd1_fMRI_grp1_subj*_voxeldata.txt')
    Olderfiles = glob.glob('YeoCogNets_nbhd1_fMRI_grp2_subj*_voxeldata.txt')

    # Calculate corr matrices
    YoungAvgCorr = fill_corr_matrices(Youngfiles)
    OldAvgCorr = fill_corr_matrices(Olderfiles)
    DiffAvgCorr = YoungAvgCorr - OldAvgCorr

    # Plot all matrices
    plot_corr_matrices(YoungAvgCorr, 'Young')
    plot_corr_matrices(OldAvgCorr, 'Older')
    plot_corr_matrices(DiffAvgCorr, 'YoungvOld')

# DN region labels: ['PFCdp','IPL','STS','MPFC','pHG','PCC']
# DAN region labels: ['FEF', 'IPS', 'SPL7a', 'MT+', 'SPL7p','PrCv']


text:
ALTER TABLE mooshell_shell ADD panel_html INTEGER DEFAULT NULL;
ALTER TABLE mooshell_shell ADD panel_css INTEGER DEFAULT NULL;
ALTER TABLE mooshell_shell ADD panel_js INTEGER DEFAULT NULL;


text:
<?php

namespace Zimbra\Admin\Request;

use Zimbra\Enum\CertType;
use Zimbra\Enum\CSRType;

/**
 * GetCert request class
 * Get Certificate.
 *
 * @package    Zimbra
 * @subpackage Admin
 * @category   Request
 * @author     Nguyen Van Nguyen - nguyennv1981@gmail.com
 * @copyright  Copyright © 2013 by Nguyen Van Nguyen.
 */
class GetCert extends Base
{
    /**
     * Constructor method for GetCert
     * @param  string $server The server's ID whose cert is to be got
     * @param  CertType $type Certificate type
     * @param  CSRType $option Required only when type is "staged". Could be "self" (self-signed cert) or "comm" (commerical cert).
     * @return self
     */
    public function __construct($server, CertType $type, CSRType $option = null)
    {
        parent::__construct();
        $this->setProperty('server', trim($server));
        $this->setProperty('type', $type);
        if($option instanceof CSRType)
        {
            $this->setProperty('option', $option);
        }
    }

    /**
     * Gets server
     *
     * @return string
     */
    public function getServer()
    {
        return $this->getProperty('server');
    }

    /**
     * Sets server
     *
     * @param  string $server
     * @return self
     */
    public function setServer($server)
    {
        return $this->setProperty('server', trim($server));
    }

    /**
     * Gets type
     *
     * @return CertType
     */
    public function getType()
    {
        return $this->getProperty('type');
    }

    /**
     * Sets type
     *
     * @param  CertType $type
     * @return self
     */
    public function setType(CertType $type)
    {
        return $this->setProperty('type', $type);
    }

    /**
     * Gets option
     *
     * @return CSRType
     */
    public function getOption()
    {
        return $this->getProperty('option');
    }

    /**
     * Sets option
     *
     * @param  CSRType $option
     * @return self
     */
    public function setOption(CSRType $option)
    {
        return $this->setProperty('option', $option);
    }
}


text:
package com.siyeh.ig.style;

import com.intellij.codeInspection.CleanupLocalInspectionTool;
import com.intellij.psi.*;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.fixes.AddThisQualifierFix;
import org.jetbrains.annotations.NotNull;

public class UnqualifiedFieldAccessInspection extends BaseInspection implements CleanupLocalInspectionTool {

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new UnqualifiedFieldAccessVisitor();
  }

  @Override
  @NotNull
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message("unqualified.field.access.problem.descriptor");
  }

  @Override
  public InspectionGadgetsFix buildFix(Object... infos) {
    final PsiReferenceExpression expressionToQualify = (PsiReferenceExpression)infos[0];
    final PsiField fieldAccessed = (PsiField)infos[1];
    return AddThisQualifierFix.buildFix(expressionToQualify, fieldAccessed);
  }

  private static class UnqualifiedFieldAccessVisitor extends BaseInspectionVisitor {

    @Override
    public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) {
      super.visitReferenceExpression(expression);
      final PsiExpression qualifierExpression = expression.getQualifierExpression();
      if (qualifierExpression != null) {
        return;
      }
      final PsiReferenceParameterList parameterList = expression.getParameterList();
      if (parameterList == null) {
        return;
      }
      final PsiElement element = expression.resolve();
      if (!(element instanceof PsiField)) {
        return;
      }
      final PsiField field = (PsiField)element;
      if (field.hasModifierProperty(PsiModifier.STATIC)) {
        return;
      }
      registerError(expression, expression, field);
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea sublurida Nyl.

### Remarks
null


text:
#ifndef WEBRTC_SYSTEM_WRAPPERS_SOURCE_TRACE_POSIX_H_
#define WEBRTC_SYSTEM_WRAPPERS_SOURCE_TRACE_POSIX_H_

#include "critical_section_wrapper.h"
#include "trace_impl.h"

namespace webrtc {
class TracePosix : public TraceImpl
{
public:
    TracePosix();
    virtual ~TracePosix();

    virtual WebRtc_Word32 AddTime(char* traceMessage,
                                  const TraceLevel level) const;

    virtual WebRtc_Word32 AddBuildInfo(char* traceMessage) const;
    virtual WebRtc_Word32 AddDateTimeInfo(char* traceMessage) const;

private:
    volatile mutable WebRtc_UWord32  _prevAPITickCount;
    volatile mutable WebRtc_UWord32  _prevTickCount;
};
} // namespace webrtc

#endif // WEBRTC_SYSTEM_WRAPPERS_SOURCE_TRACE_POSIX_H_


text:
from __future__ import unicode_literals

import re
import sys
import time
import random
import logging
import platform
import mimetypes
from hashlib import md5

import lxml
import lxml.html
import lxml.etree
# import html5lib
import iso8601

from .compat import text, text_types, binary, urequest, PY2, BaseCookie

#: Логгер tabun_api.
logger = logging.getLogger('tabun_api')

#: Месяцы, для парсинга даты.
mons = ('января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря')

#: Блочные элементы, для красивого вывода в htmlToString (устарело, используйте HTMLFormatter.block_elems)
block_elems = ("div", "p", "blockquote", "section", "ul", "li", "h1", "h2", "h3", "h4", "h5", "h6")

#: Регулярка для парсинга ютуба для выдирания превьюшки.
youtube_regex = re.compile(r'youtube.com\/embed\/(.{10,15})((\?)|($))')

#: Регулярка для парсинга ссылки на аватарку — из неё можно узнать много полезного!
ava_regex = re.compile(r"\/((images)|(storage))\/([0-9]+)\/([0-9]+)\/([0-9]+)\/([0-9]+)\/([0-9]+)\/([0-9]+)\/avatar_([0-9]+)x([0-9]+)\.(...)(\?([0-9]+))?")

#: Регулярка для расшифровки почты, которую шифрует CloudFlare.
cf_email = re.compile(r'<[A-Za-z]+( href="/cdn-cgi/l/email-protection")? class="__cf_email__".*? data-cfemail="([0-9a-f]+)".+?</[A-Za-z]+>', re.DOTALL)

cf_email_b = re.compile(r'<[A-Za-z]+( href="/cdn-cgi/l/email-protection")? class="__cf_email__".*? data-cfemail="([0-9a-f]+)".+?</[A-Za-z]+>'.encode('utf-8'), re.DOTALL)

#: Тоже регулярка для расшифровки почты, которую шифрует CloudFlare, но для ссылок.
cf_email_a = re.compile(r'<[Aa]\s([^>]*)href="/cdn-cgi/l/email-protection#([0-9a-f]+)"(\s[^>]*)?>', re.DOTALL)

cf_email_a_b = re.compile(r'<[Aa]\s([^>]*)href="/cdn-cgi/l/email-protection#([0-9a-f]+)"(\s[^>]*)?>'.encode('utf-8'), re.DOTALL)

#: Регулярка, убирающая скрипты расшифровки почты от CloudFlare.
cf_email_s = re.compile(r'', re.DOTALL)

cf_email_s_b = re.compile(r''.encode('utf-8'), re.DOTALL)

def parse_html(data, encoding='utf-8'):
    """Парсит HTML-код и возвращает lxml.etree-элемент."""
    # if isinstance(data, text): encoding = None
    # doc = html5lib.parse(data, treebuilder="lxml", namespaceHTMLElements=False, encoding=encoding)
    if isinstance(data, binary):
        data = data.decode(encoding, "replace")
    doc = lxml.html.fromstring(data)
    return doc

def parse_html_fragment(data, encoding='utf-8'):
    """Парсит кусок HTML-кода и возвращает список lxml.etree-элементов и строк."""
    # if isinstance(data, text): encoding = None
    # doc = html5lib.parseFragment(data, treebuilder="lxml", namespaceHTMLElements=False, encoding=encoding)
    if isinstance(data, binary):
        data = data.decode(encoding, "replace")
    doc = lxml.html.fragments_fromstring(data)
    return doc

class HTMLFormatter(object):
    """Гибкий и расширяемый конвертер lxml-элементов в красивые строки
    подобно браузеру links и родственным ему.

    В словаре ``params`` можно указать следующие параметры:

    * ``fancy`` (True/False, по умолчанию True) — грамотно форматирует спойлеры
      и убирает кнопку ката при наличии
    * ``strike_mode`` (``unicode`` (по умолчанию) или ``html``) — как форматировать
      зачёркивания
    * ``vk_links`` (True/False, по умолчанию False) — преобразует ссылки вида
      ``https://vk.com/foo`` в ``@foo (текст ссылки)`` для отправки во ВКонтакте
    * ``disable_links`` (True/False, по умолчанию False) — удаляет ссылки, если
      текст ссылки совпадает с самой ссылкой (примитивный антиспам)

    Пример использования::

        node = parse_html_fragment('
a <s>bc</s>
 d   ef
gcut
')[0]
        HTMLFormatter({'strike_mode': 'html'}).format(node, with_cutted=False)

    Результат::

        a <s>bc</s>
        =====
        d ef
        g
    """

    NEWLINE = -1
    block_elems = ("div", "p", "blockquote", "section", "ul", "li", "h1", "h2", "h3", "h4", "h5", "h6")

    fancy = True
    strike_mode = 'unicode'
    vk_links = False
    disable_links = False

    def __init__(self, params=None):
        for k in ('fancy', 'strike_mode', 'vk_links', 'disable_links'):
            if params and k in params:
                setattr(self, k, params[k])

    def format(self, node, with_cutted=True):
        """Форматирует lxml-элемент.

        :param node: сам lxml-элемент
        :param bool with_cutted: если False, обработка будет прекращена после
          натыкания на тег-кат (когда :func:`~tabun_api.utils.is_cut` вернёт True)
        :rtype: строка
        """

        return self.format_part(node, with_cutted)[1]

    def format_part(self, node, with_cutted=True):
        if isinstance(node, text_types):
            return False, text(node)

        if node.text:
            data = [self.format_text(self.escape(node.text), [])]
        else:
            data = ['']

        depth = [node]  # for

: [
,
]
        full_queue = [list(node.getchildren())]  # for

: [[div children after current ul], [ul children after current li]]
        full_queue[0].reverse()

        # Самые часто используемые функции вытащим заранее (говорят, так слегка быстрее)
        process_br = getattr(self, 'process_br', None)
        process_a = getattr(self, 'process_a', None)
        process_span = getattr(self, 'process_span', None)
        default_process = self.default_process
        format_item_tail = self.format_item_tail

        cut_stop = False

        while True:
            # Проверяем, что очередь не пуста
            while full_queue and not full_queue[-1]:
                full_queue.pop()
                depth.pop()
            if not full_queue or not depth:
                assert not depth
                assert not full_queue
                break

            # Берём следующий элемент (может быть любой вложенности — избегаем рекурсии зазря)
            item = full_queue[-1].pop()

            # С помощью специального значения избегаем лишних переносов на границах блоков
            if item == self.NEWLINE:
                sdata = data[-1].rstrip(' ')
                if not sdata.endswith('\n'):
                    data[-1] = sdata
                    data.append('\n')
                continue

            # Это может быть просто текст между элементами (добавляется ниже в format_item_tail)
            if isinstance(item, text_types):
                ntext = self.format_text(item, data)
                if ntext:
                    data.append(ntext)
                continue

            # Это может быть кат в полном посте — тогда сразу закругляемся
            if not with_cutted and is_cut(item):
                cut_stop = True
                break

            format_item_tail(item, data, depth, full_queue)

            children = []

            # Обрабатываем элемент
            tag = item.tag.lower().replace('-', '_')
            if tag == 'br':
                process_func = process_br
            elif tag == 'a':
                process_func = process_a
            elif tag == 'span':
                process_func = process_span
            else:
                process_func = getattr(self, 'process_' + tag, None)

            if process_func is None:
                process_func = default_process
            children = process_func(item, data, depth, with_cutted=with_cutted)

            if children is None:
                # None означает, что надо закругляться
                break

            elif children:
                # Обрабатываем потомков в следующей итерации
                children.reverse()
                full_queue.append(children)
                depth.append(item)

        return cut_stop, ''.join(data).strip()

    def element_children(self, item, noblock=False):
        children = []
        is_block = not noblock and item.tag in self.block_elems

        # Начало элемента-блока
        if is_block:
            children.append(self.NEWLINE)

        # Содержимое элемента
        if item.text:
            children.append(self.escape(item.text))

        ch = list(item.getchildren())
        if ch:
            children.extend(ch)

        # Конец элемента-блока (есть смысл только при непустом блоке)
        if is_block and (item.text or ch):
            children.append(self.NEWLINE)

        return children

    def process_br(self, item, data, depth, with_cutted):
        # Не более одной пустой строчки при нескольких
 подряд
        if data[-1].rstrip(' ').endswith('\n\n'):
            pass
        elif len(data) > 1 and data[-1].rstrip(' ') == '\n' and data[-2].rstrip(' ').endswith('\n'):
            pass
        else:
            data[-1] = data[-1].rstrip(' ')
            data.append('\n')
        return []

    def default_process(self, item, data, depth, with_cutted):
        return self.element_children(item)

    def format_item_tail(self, item, data, depth, full_queue):
        # Текст после тега не относится к самому тегу и добавится после обработки потомков
        if item.tail:
            full_queue[-1].append(self.escape(item.tail))

    def format_text(self, ntext, data=None):
        # Форматирует текст подобно HTML — не более одного пробела подряд
        if '\n' in ntext:
            ntext = ntext.replace('\n', ' ')
        if '\r' in ntext:
            ntext = ntext.replace('\r', ' ')
        if '\t' in ntext:
            ntext = ntext.replace('\t', ' ')
        if data and (data[-1].endswith('\n') or data[-1].endswith(' ')):
            ntext = ntext.lstrip(' ')
        elif ntext.startswith('  '):
            ntext = ' ' + ntext.lstrip(' ')
        if ntext.endswith('  '):
            ntext = ntext.rstrip(' ') + ' '
        if '  ' in ntext:
            ntext = re.sub(r'  +', ' ', ntext)
        return ntext

    def escape(self, ntext):
        if not self.vk_links:
            return ntext
        return ntext.replace('@', '@').replace('(', '(').replace(')', ')').replace('*', '*').replace('[', '[').replace(']', ']')

    def process_a(self, item, data, depth, with_cutted):
        if self.fancy and item.get('title') == "Читать дальше":
            # Кнопку ката пропускаем (её можно сделать фейковой, поэтому can_next = True)
            return []

        href = item.get('href')
        if self.vk_links and href and 'vk.com/' in href:
            # Заменяем ссылки на vk.com на ссылки в специальном формате ВК
            g = re.match(r'^(https?:)?//([\.A-z0-9_-]+\.)?vk\.com/([\.A-z0-9_-]+)$', href)
            path = g.groups()[2] if g else None
            for stopword in ("wall", "photo", "page", "board", "video", "videos", "audio", "audios", "topic", "app", "album", "note"):
                # ссылки вида «чтотоНОМЕР» специального формата о ВК не имеют, поэтому пропускаем их
                if not path or (
                    len(path) > len(stopword) and
                    path.startswith(stopword) and
                    (path[len(stopword)].isdigit() or path[len(stopword)] == '-')
                ):
                    return self.element_children(item, noblock=True)

            stop_cut, tmp = self.format_part(item, with_cutted)
            if not tmp.strip():
                return self.element_children(item, noblock=True)

            data.append(' @' + path + ' (')
            data.append(self.escape(tmp))
            data.append(') ')
            return None if stop_cut else []

        stop_cut, tmp = self.format_part(item, with_cutted)
        if self.disable_links and (
            tmp == href or
            href.find('://') < 7 and tmp == href[href.find('://') + 3:] or
            href.startswith('//') and tmp == href[2:]
        ):
            return None if stop_cut else []

        return self.element_children(item, noblock=True)

    def process_span(self, item, data, depth, with_cutted):
        if not self.fancy:
            return self.element_children(item, noblock=True)

        if item.get('class') == 'spoiler-title':
            # Заголовок спойлера опускаем всегда
            return []

        if item.get('class') == 'spoiler-body':
            # Тело спойлера опускаем, только если оно фейковое
            if depth[-1].tag != 'span' or depth[-1].get('class') != 'spoiler':
                return []
            ch = self.element_children(item, noblock=True)
            if ch:
                # Имитируем display: block
                ch.insert(0, self.NEWLINE)
                ch.append(self.NEWLINE)
            else:
                ch.append(self.NEWLINE)
            return ch
        return self.element_children(item, noblock=True)

    def process_li(self, item, data, depth, with_cutted):
        ch = [self.NEWLINE, '• ']
        ch.extend(self.element_children(item, noblock=True))
        ch.append(self.NEWLINE)
        return ch

    def process_blockquote(self, item, data, depth, with_cutted):
        ch = [self.NEWLINE, '«']
        ch.extend(self.element_children(item, noblock=True))
        ch.append('»')
        ch.append(self.NEWLINE)
        return ch

    def process_hr(self, item, data, depth, with_cutted):
        return [self.NEWLINE, '=====', self.NEWLINE]

    def process_s(self, item, data, depth, with_cutted):
        if self.strike_mode == 'unicode':
            # Без рекурсии никак :(
            stop_cut, tmp = self.format_part(item, with_cutted)
            tmp2 = []
            for x in tmp:
                tmp2.append(x)
                tmp2.append('\u0336')
            result = ''.join(tmp2)
            data.append(result)
            return None if stop_cut else []

        elif self.strike_mode == 'html':
            result = ['<s>']
            result.extend(self.element_children(item, noblock=True))
            result.append('</s>')
            return result

        else:
            return self.element_children(item, noblock=True)

def htmlToString(node, with_cutted=True, fancy=True, vk_links=False, hr_lines=True, disable_links=False):
    import warnings
    warnings.warn('utils.htmlToString is deprecated; use utils.HTMLFormatter instead of it', FutureWarning, stacklevel=2)

    if isinstance(node, text_types):
        return text(node)

    data = ""
    newlines = 0

    if node.text:
        ndata = node.text.replace("\n", " ")
        if newlines:
            ndata = ndata.lstrip()
        data += ndata
        if ndata:
            newlines = 0

    prev_text = None
    prev_after = None
    for item in node.iterchildren():
        if prev_text:
            ndata = prev_text.replace("\n", " ")
            if newlines:
                ndata = ndata.lstrip()
            data += ndata
            if ndata:
                newlines = 0
        if prev_after:
            ndata = prev_after.replace("\n", " ")
            if newlines:
                ndata = ndata.lstrip()
            data += ndata
            if ndata:
                newlines = 0

        if item.tail:
            prev_after = item.tail
        else:
            prev_after = None
        prev_text = item.text

        if item.tag == "br":
            if newlines < 2:
                data += "\n"
                newlines += 1
        elif item.tag == "hr":
            if hr_lines:
                data += "\n=====\n"
            else:
                data += "\n"
            newlines = 1
        elif fancy and item.get('class') == 'spoiler-title':
            prev_text = None
            continue
        elif fancy and item.tag == 'a' and item.get('title') == "Читать дальше":
            prev_text = None
            continue
        elif not with_cutted and is_cut(item):
            return data.strip()
        elif item.tag in ("img",):
            continue

        elif vk_links and item.tag == "a" and item.get('href', '').find("://vk.com/") > 0 and item.text_content().strip():
            href = item.get('href')
            addr = href[href.find("com/") + 4:]
            if addr and addr[-1] in (".", ")"):
                addr = addr[:-1]

            stop = False
            for c in ("/", "?", "&", "(", ",", ")", "|"):
                if c in addr:
                    stop = True
                    break
            if stop:
                data += item.text_content()
                prev_text = None
                continue

            for typ in ("wall", "photo", "page", "video", "topic", "app", "album", "note"):
                if addr.find(typ) == 0:
                    stop = True
                    break
            if stop:
                data += item.text_content()
                prev_text = None
                continue

            ndata = item.text_content().replace("[", " ").replace("|", " ").replace("]", " ")
            data += " [" + addr + "|" + ndata + "] "
            prev_text = None

        elif disable_links and item.tag == "a" and item.get('href', '').endswith(item.text_content().strip()) and abs(len(item.get('href', '')) - len(item.text_content().strip())) < 10:
            prev_text = None
            continue

        else:
            if item.tag in ("li", ):
                data += "• "
            elif data and item.tag in block_elems and not newlines:
                data += "\n"
                newlines = 1

            if prev_text:
                prev_text = None

            tmp = htmlToString(item, with_cutted=with_cutted, fancy=fancy, vk_links=vk_links, hr_lines=hr_lines)
            newlines = 0

            if item.tag == "s":  # зачёркивание
                tmp1 = ""
                for x in tmp:
                    tmp1 += x + '\u0336'
                # tmp1 = "<s>" + tmp1 + "</s>"
            elif item.tag == "blockquote":  # цитата
                tmp1 = " «" + tmp + "»\n"
                newlines = 1
            else:
                tmp1 = tmp

            data += tmp1

            if not with_cutted:
                for item2 in item.iterchildren():
                    if is_cut(item2):
                        return data.strip()

            if item.tag in block_elems and not newlines:
                data += "\n"
                newlines = 1

    if prev_text:
        ndata = prev_text.replace("\n", " ")
        if newlines:
            ndata = ndata.lstrip()
        data += ndata
        if ndata:
            newlines = 0
    if prev_after:
        ndata = prev_after.replace("\n", " ")
        if newlines:
            ndata = ndata.lstrip()
        data += ndata
        if ndata:
            newlines = 0

    return data.strip()

def node2string(node, encoding="utf-8"):
    """Переводит html-элемент в байтовую строку."""
    return lxml.etree.tostring(node, method="html", encoding=encoding)  # pylint: disable=no-member

def mon2num(s):
    """Переводит названия месяцев в числа, чтобы строку можно было скормить в strftime."""
    for i in range(len(mons)):
        s = s.replace(mons[i], text(i + 1))
    return s

def is_cut(item):
    """Возвращает True, если тег похож на кат (на момент написания это
    ```` (новый) или ```` (старый)).
    """

    return item.tag == "a" and not item.get("href") and not item.text_content() and not item.getchildren()

def find_images(body, spoiler_title=True, no_other=False):
    """Ищет картинки в lxml-элементе и возвращает их список в виде
    [[ссылки до ката], [ссылки после ката]].

    :param bool spoiler_title: включать ли картинки с заголовков спойлеров
    :param bool no_other: исключать ли всякий мусор. Фильтрация простейшая:
      по наличию "smile" или "gif" в ссылке, также убираются табунские аватарки
      и навигация АльтерБРЕДаций.
    :rtype: [list, list]
    """

    imgs = [[], []]
    links = [[], []]

    start = False
    for item in body.iterchildren():
        # FIXME: не работает, если кат внутри другого тега
        if not start and is_cut(item):
            start = True
            continue

        if item.tag == "img":
            imgs[1 if start else 0].append(item)
        else:
            limgs = item.xpath('.//img')
            if not limgs:
                limgs = item.xpath('.//a')
            imgs[1 if start else 0].extend(limgs)

    for i in (0, 1):
        tags = imgs[i]
        if not tags:
            continue
        for img in tags:
            src = img.get("src")
            if not src:
                src = img.get("href")
                if not src:
                    continue
                if src[-4:].lower() not in ('jpeg', '.jpg', '.png'):
                    continue
            if "<" in src:
                continue
            if no_other and (
                ".gif" in src.lower() or
                "smile" in src.lower() or
                ("/avatar_" in src and '/images/' in src) or
                src.endswith('1_Prev.png') or src.endswith('2_Clear.png') or
                src.endswith('3_VK.png') or src.endswith('4_New.png') or
                src.endswith('5_Next.png')  # АБД
            ):
                continue

            if not spoiler_title and img.getparent() is not None and img.getparent().get("class") == "spoiler-title":
                # Hint: если вы пишете пост и хотите, чтобы картика бралась даже из заголовка спойлера,
                # достаточно лишь положить её внутрь какого-нибудь ещё тега, например .
                continue

            links[i].append(src)

    if not links[0] and not links[1]:
        videos = body.xpath('.//iframe')
        for video in videos:
            match = youtube_regex.search(video.get('src', ''))
            if not match:
                continue
            if match.groups()[0]:
                links[1].append('http://i4.ytimg.com/vi/%s/sddefault.jpg' % match.groups()[0])

    return links

# copypasted from:
# https://github.com/ActiveState/code/tree/5cf284892339de263d760babf6a15a9675843d94/recipes/Python/146306_Http_client_POST_using
# and modified by andreymal
def encode_multipart_formdata(fields, files, boundary=None):
    """Возвращает кортеж (content_type, body), готовый для отправки HTTP POST--запроса.

    Значения полей и файлов могут быть строками (закодируются в utf-8),
    bytes или числами (будут преобразованы в строку).

    :param fields: простые поля запроса
    :type fields: коллекция кортежей (название, значение) или словарь
    :param fields: файлы запроса (MIME-тип будет выбран по расширению)
    :type fields: коллекция кортежей (название, имя файла, значение)
    :param boundary: boundary (по умолчанию генерируется случайные)
    :type boundary: строка или bytes
    :rtype: (строка, bytes)
    """

    if isinstance(fields, dict):
        fields = fields.items()
    if boundary is None:
        boundary = b'----------' + md5((text(int(time.time())) + text(random.randrange(1000))).encode('utf-8')).hexdigest().encode('utf-8')
    elif isinstance(boundary, text):
        boundary = boundary.encode('utf-8')
    L = []

    for (key, value) in fields:
        key = text(key).encode('utf-8')
        if isinstance(value, text):
            value = value.encode('utf-8')
        elif isinstance(value, (int, float, complex)):
            value = text(value).encode('utf-8')
        elif not isinstance(value, binary):
            raise ValueError('Value should be bytes, not %s' % type(value))
        L.append(b'--' + boundary)
        L.append(('Content-Disposition: form-data; name="%s"' % key.decode('utf-8')).encode('utf-8'))
        L.append(b'')
        L.append(value)

    for (key, filename, value) in files:
        key = text(key).encode('utf-8')
        filename = text(filename).encode('utf-8')
        if isinstance(value, text):
            value = value.encode('utf-8')
        elif not isinstance(value, binary):
            raise ValueError('Value should be bytes, not %s' % type(value))
        L.append(b'--' + boundary)
        L.append((
            'Content-Disposition: form-data; name="%s"; filename="%s"' % (key.decode('utf-8'), filename.decode('utf-8'))
        ).encode('utf-8'))
        L.append(('Content-Type: %s' % get_content_type(filename.decode('utf-8'))).encode('utf-8'))
        L.append(b'')
        L.append(value)

    L.append(b'--' + boundary + b'--')
    L.append(b'')
    body = b'\r\n'.join(L)
    content_type = 'multipart/form-data; boundary=%s' % boundary.decode('utf-8')
    return content_type, body

def get_content_type(filename):
    """return mimetypes.guess_type(filename)[0] or 'application/octet-stream'"""
    return text(mimetypes.guess_type(filename)[0] or 'application/octet-stream')

def send_form(url, fields, files, timeout=None, headers=None):
    """Отправляет форму, пользуясь функцией :func:`~tabun_api.utils.encode_multipart_formdata`.

    Значения полей и файлов могут быть строками (закодируются в utf-8),
    bytes или числами (будут преобразованы в строку).

    :param fields: простые поля запроса
    :type fields: коллекция кортежей (название, значение)
    :param fields: файлы запроса (MIME-тип будет выбран по расширению)
    :type fields: коллекция кортежей (название, имя файла, значение)
    :param float timeout: сколько ожидать ответа, не дождётся - кидается исключением urllib
    :param headers: дополнительные HTTP-заголовки (повторяться не могут)
    :type headers: кортежи из двух строк/bytes или словарь
    :rtype: ``urllib.addinfourl`` / ``urllib.response.addinfourl``
    """

    content_type, data = encode_multipart_formdata(fields, files)

    if not isinstance(url, urequest.Request):
        if PY2 and isinstance(url, text):
            url = url.encode('utf-8')
        url = urequest.Request(url)

    if isinstance(headers, dict):
        headers = headers.items()
    if headers:
        for header, value in headers:
            if not isinstance(header, str):  # py2 and py3
                header = str(header)
            if isinstance(value, text):
                value = value.encode('utf-8')
            url.add_header(header, value)
    url.add_unredirected_header(str('Content-type'), content_type.encode('utf-8'))
    url.data = data

    if timeout is None:
        return urequest.urlopen(url)
    else:
        return urequest.urlopen(url, timeout=timeout)

def find_substring(s, start, end, extend=False, with_start=True, with_end=True):
    """Возвращает подстроку, находящуюся между кусками строки ``start`` и ``end``,
    или ``None``, если не нашлось.

    При ``extend=True`` кусок строки end ищется с конца (``rfind``).
    """

    f1 = s.find(start)
    if f1 < 0:
        return
    f2 = (s.rfind if extend else s.find)(end, f1 + len(start))
    if f2 < 0:
        return
    return s[f1 + (0 if with_start else len(start)):f2 + (len(end) if with_end else 0)]

def download(url, maxmem=20 * 1024 * 1024, timeout=5, waitout=15, headers=None):
    """Скачивает данные по ссылке. Имеет защиту от переполнения памяти
    и слишком долгого ожидания, чтобы всякие боты тут не висли.
    В случае чего кидает ``IOError``.

    :param url: ссылка, которую скачать
    :type url: строка
    :param int maxmem: допустимый максимальный размер скачиваемых данных
    :param float timeout: как долго можно ждать ответа
    :param float waitout: как долго можно скачивать данные
      (простенькая защита от Slow TCP DoS Attack — timeout тут не поможет)
    :rtype: bytes
    """

    # TODO: non-ASCII URL

    from tabun_api import http_headers

    url = text(url)
    if url.startswith('//'):
        url = 'http:' + url

    req = urequest.Request(url.encode("utf-8") if PY2 else url)

    request_headers = http_headers.copy()
    if headers:
        request_headers.update({k.title(): v for k, v in headers.items()})
    for header, value in request_headers.items():
        if not isinstance(header, str):  # py2 and py3
            header = str(header)
        if isinstance(value, text):
            value = value.encode('utf-8')
        req.add_header(header, value)

    resp = urequest.urlopen(req, timeout=timeout)

    size = resp.headers.get('content-length')
    if size and size.isdigit() and int(size) > maxmem:
        raise IOError("Too big")

    data = b''
    start_dwnl = time.time()

    while 1:
        if len(data) > maxmem:
            raise IOError("Too big")
        tmp = resp.read(64 * 1024)
        if not tmp:
            break
        data += tmp
        if time.time() - start_dwnl >= waitout:
            raise IOError("Too long")
    resp.close()

    return data

def find_good_image(urls, maxmem=20 * 1024 * 1024):
    """Ищет годную картинку из предложенного списка ссылок и возвращает ссылку
    и скачанные данные картинки (файл, bytes).
    Такой простенький фильтр смайликов и элементов оформления поста по размеру.

    Требует PIL или Pillow.

    Не грузит картинки размером больше maxmem байт, дабы не вылететь от
    нехватки памяти.
    """

    try:
        from PIL import Image
    except ImportError:
        import Image
    from io import BytesIO

    good_image = None, None
    for url in urls:
        url = text(url)
        if url.find('//dl.dropboxusercontent.com/') in (5, 6):
            waitout = 60
        elif url.find('//dl.dropbox.com/') in (5, 6):
            waitout = 60
        else:
            waitout = 15
        try:
            data = download(url, maxmem, waitout=waitout)
        except IOError:
            continue

        try:
            img = Image.open(BytesIO(data))
        except:
            continue

        if img.size[0] < 100 or img.size[1] < 100:
            continue
        good_image = url, data
        break

    return good_image

def generate_comments_tree(comms):
    """Строит дерево комментариев из словаря, возвращаемого функциями get_comments[_from].

    Формат элемента: [(комментарий, элемент), (комментарий, элемент), ...]

    Возвращает само такое дерево и список номеров комментариев-сирот
    (по идее должен быть пустой, но мало ли).

    :param comms: словарь комментариев
    :type comms: {id: :func:`~tabun_api.Comment`}
    :rtype: (list, list)
    """

    tree_dict = {}
    tree = []
    orphans = []
    for comment in sorted(comms.values(), key=lambda x: x.comment_id):
        item = (comment, [])
        tree_dict[comment.comment_id] = item
        if not comment.parent_id:
            tree.append(item)
            continue
        parent = tree_dict.get(comment.parent_id)
        if not parent:
            tree.append(item)
            orphans.append(comment.comment_id)
        else:
            parent[1].append(item)
    return tree, orphans

def parse_avatar_url(url):
    """Парсит ссылку на аватарку и возвращает id пользователя,
    дату отправки, размер, расширение и какой-то номер с конца ссылки.
    Если не удалось распарсить, то всё ``None``.

    :param url: ссылка
    :type url: строка
    :rtype: (int, "YYYY-MM-DD", (int, int), строка, int или None)
    """

    match = ava_regex.search(url)
    if not match:
        return None, None, None, None, None
    g = match.groups()
    user_id = int(g[3] + g[4] + g[5])
    date = g[6] + "-" + g[7] + "-" + g[8]
    size = (int(g[9]), int(g[10]))
    ext = g[11]
    num = int(g[13]) if g[13] is not None else None

    return user_id, date, size, ext, num

def decode_cf_email(data):
    key = int(data[0:2], 16)
    use_bytes = not isinstance(data, text)
    result = b''
    for i in range(1, len(data) // 2):
        b = int(data[i * 2:i * 2 + 2], 16) ^ key
        if PY2:
            result += chr(b)
        else:
            result += bytes([b])
    return result if use_bytes else result.decode('utf-8')

def decode_cf_email_for_link(m):
    left, data, right = m.groups()

    mail = decode_cf_email(data)

    if isinstance(data, text):
        result = ''.format(left or '', mail, right or '')
    else:
        result = b''.join((
            b'',
        ))

    return result

def replace_cloudflare_emails(data):
    """Декодирует почты, которые зашифровал CloudFlare, в html-странице."""

    is_text = isinstance(data, text)

    # В текстах
    r = cf_email if is_text else cf_email_b
    result = r.sub(lambda x: decode_cf_email(x.groups()[1]), data)

    # В ссылках
    ra = cf_email_a if is_text else cf_email_a_b
    result = ra.sub(decode_cf_email_for_link, result)

    # Убираем


text:
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_settings')


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/keyline_minus_16">

    <ListView
        android:id="@+android:id/list"
        style="@style/DefaultPadding.List"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fastScrollEnabled="true" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</FrameLayout>


text:
package gov.nih.nci.ccts.grid.smoketest.service.globus.resource;

import gov.nih.nci.cagrid.common.Utils;

import gov.nih.nci.cagrid.advertisement.AdvertisementClient;
import gov.nih.nci.cagrid.advertisement.exceptions.UnregistrationException;

import gov.nih.nci.ccts.grid.smoketest.common.SmokeTestServiceConstants;
import gov.nih.nci.ccts.grid.smoketest.stubs.SmokeTestServiceResourceProperties;
import gov.nih.nci.ccts.grid.smoketest.service.SmokeTestServiceConfiguration;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.xml.namespace.QName;

import gov.nih.nci.cagrid.introduce.servicetools.FilePersistenceHelper;
import gov.nih.nci.cagrid.introduce.servicetools.PersistenceHelper;
import gov.nih.nci.cagrid.introduce.servicetools.ReflectionResource;

import org.apache.axis.MessageContext;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.mds.aggregator.types.AggregatorConfig;
import org.globus.mds.aggregator.types.AggregatorContent;
import org.globus.mds.aggregator.types.GetMultipleResourcePropertiesPollType;
import org.globus.mds.servicegroup.client.ServiceGroupRegistrationParameters;
import org.globus.wsrf.InvalidResourceKeyException;
import org.globus.wsrf.NoSuchResourceException;
import org.globus.wsrf.Constants;
import org.globus.wsrf.Resource;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.RemoveCallback;
import org.globus.wsrf.PersistenceCallback;
import org.globus.wsrf.ResourceContext;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.ResourceContextException;
import org.globus.wsrf.ResourceIdentifier;
import org.globus.wsrf.ResourceKey;
import org.globus.wsrf.ResourceLifetime;
import org.globus.wsrf.ResourceProperties;
import org.globus.wsrf.ResourceProperty;
import org.globus.wsrf.ResourcePropertySet;
import org.globus.wsrf.config.ContainerConfig;
import org.globus.wsrf.container.ServiceHost;
import org.globus.wsrf.encoding.DeserializationException;
import org.globus.wsrf.encoding.ObjectDeserializer;
import org.globus.wsrf.impl.ReflectionResourceProperty;
import org.globus.wsrf.impl.SimpleResourceProperty;
import org.globus.wsrf.impl.SimpleResourcePropertyMetaData;
import org.globus.wsrf.impl.SimpleResourcePropertySet;
import org.globus.wsrf.impl.security.descriptor.ResourceSecurityDescriptor;
import org.globus.wsrf.impl.servicegroup.client.ServiceGroupRegistrationClient;
import org.globus.wsrf.jndi.Initializable;
import org.globus.wsrf.security.SecureResource;
import org.globus.wsrf.utils.AddressingUtils;

import org.globus.wsrf.Topic;
import org.globus.wsrf.TopicList;
import org.globus.wsrf.TopicListAccessor;
import org.globus.wsrf.utils.SubscriptionPersistenceUtils;

import org.globus.wsrf.impl.ResourcePropertyTopic;
import org.globus.wsrf.impl.SimpleTopicList;
import org.oasis.wsrf.lifetime.TerminationNotification;

/**
 * DO NOT EDIT:  This class is autogenerated!
 *
 * This class is the base class of the resource type created for this service.
 * It contains accessor and utility methods for managing any resource properties
 * of these resource as well as code for registering any properties selected
 * to the index service.
 *
 * @created by Introduce Toolkit version 1.4
 *
 */
public abstract class SmokeTestServiceResourceBase extends ReflectionResource implements Resource
                                                  {

	static final Log logger = LogFactory.getLog(SmokeTestServiceResourceBase.class);

	private SmokeTestServiceResourceConfiguration configuration;

	// this can be used to cancel the registration renewal
    private AdvertisementClient registrationClient;

    private URL baseURL;
    private boolean beingLoaded = false;

    public SmokeTestServiceResourceBase() {
    }

	/**
	 * @see org.globus.wsrf.jndi.Initializable#initialize()
	 */
	public void initialize(Object resourceBean,
                           QName resourceElementQName,
                           Object id) throws ResourceException {

        // Call the super initialize on the ReflectionResource
	    super.initialize(resourceBean,resourceElementQName,id);

		// register the service to the index service
		refreshRegistration(true);

	}

	public SmokeTestServiceResourceConfiguration getConfiguration() {
		if (this.configuration != null) {
			return this.configuration;
		}
		MessageContext ctx = MessageContext.getCurrentContext();

		String servicePath = ctx.getTargetService();
		servicePath = servicePath.substring(0,servicePath.lastIndexOf("/"));
		servicePath+="/SmokeTestService";

		String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
		logger.debug("Will read configuration from jndi name: " + jndiName);
		try {
			Context initialContext = new InitialContext();
			this.configuration = (SmokeTestServiceResourceConfiguration) initialContext.lookup(jndiName);
		} catch (Exception e) {
			logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
		}

		return this.configuration;
	}

    /**
     * This checks the configuration file, and attempts to register to the
     * IndexService if shouldPerformRegistration==true. It will first read the
     * current container URL, and compare it against the saved value. If the
     * value exists, it will only try to reregister if the values are different.
     * This exists to handle fixing the registration URL which may be incorrect
     * during initialization, then later corrected during invocation. The
     * existence of baseURL does not imply successful registration (a non-null
     * registrationClient does). We will only attempt to reregister when the URL
     * changes (to prevent attempting registration with each invocation if there
     * is a configuration problem).
     */
    public void refreshRegistration(boolean forceRefresh) {
        if (getConfiguration().shouldPerformRegistration()) {

            // first check to see if there are any resource properties that
            // require registration
            ResourceContext ctx;
            try {
                MessageContext msgContext = MessageContext.getCurrentContext();
                if (msgContext == null) {
                    logger.error("Unable to determine message context!");
                    return;
                }

                ctx = ResourceContext.getResourceContext(msgContext);
            } catch (ResourceContextException e) {
                logger.error("Could not get ResourceContext: " + e, e);
                return;
            }
            EndpointReferenceType epr;
            try {
                // since this is a singleton, pretty sure we dont't want to
                // register the key (allows multiple instances of same service
                // on successive restarts)
                epr = AddressingUtils.createEndpointReference(ctx, null);
            } catch (Exception e) {
                logger.error("Could not form EPR: " + e, e);
                return;
            }

            ServiceGroupRegistrationParameters params = null;

            File registrationFile = new File(ContainerConfig.getBaseDirectory() + File.separator
                + getConfiguration().getRegistrationTemplateFile());

            if (registrationFile.exists() && registrationFile.canRead()) {
                logger.debug("Loading registration arguments from:" + registrationFile);

                try {
                    params = ServiceGroupRegistrationClient.readParams(registrationFile.getAbsolutePath());
                } catch (Exception e) {
                    logger.error("Unable to read registration file:" + registrationFile, e);
                }

                // set our service's EPR as the registrant, or use the specified
                // value
                EndpointReferenceType registrantEpr = params.getRegistrantEPR();
                if (registrantEpr == null) {
                    params.setRegistrantEPR(epr);
                }

            } else {
                logger.error("Unable to read registration file:" + registrationFile);
            }

            if (params != null) {

                AggregatorContent content = (AggregatorContent) params.getContent();
                AggregatorConfig config = content.getAggregatorConfig();
                MessageElement[] elements = config.get_any();
                GetMultipleResourcePropertiesPollType pollType = null;
                try {
                    pollType = (GetMultipleResourcePropertiesPollType) ObjectDeserializer.toObject(elements[0],
                        GetMultipleResourcePropertiesPollType.class);
                } catch (DeserializationException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                if (pollType != null) {

                    // if there are properties names that need to be registered then
                    // register them to the index service
                    if (pollType.getResourcePropertyNames()!=null && pollType.getResourcePropertyNames().length != 0) {

                        URL currentContainerURL = null;
                        try {
                            currentContainerURL = ServiceHost.getBaseURL();
                        } catch (IOException e) {
                            logger.error("Unable to determine container's URL!  Skipping registration.", e);
                            return;
                        }

                        if (this.baseURL != null) {
                            // we've tried to register before (or we are being
                            // forced to
                            // retry)
                            // do a string comparison as we don't want to do DNS
                            // lookups
                            // for comparison
                            if (forceRefresh || !this.baseURL.equals(currentContainerURL)) {
                                // we've tried to register before, and we have a
                                // different
                                // URL now.. so cancel the old registration (if
                                // it
                                // exists),
                                // and try to redo it.
                                if (registrationClient != null) {
                                    try {
                                        this.registrationClient.unregister();
                                    } catch (UnregistrationException e) {
                                        logger
                                            .error("Problem unregistering existing registration:" + e.getMessage(), e);
                                    }
                                }

                                // save the new value
                                this.baseURL = currentContainerURL;
                                logger.info("Refreshing existing registration [container URL=" + this.baseURL + "].");
                            } else {
                                // URLs are the same (and we weren't forced), so
                                // don't
                                // try
                                // to reregister
                                return;
                            }

                        } else {
                            // we've never saved the baseURL (and therefore
                            // haven't
                            // tried to
                            // register)
                            this.baseURL = currentContainerURL;
                            logger.info("Attempting registration for the first time[container URL=" + this.baseURL
                                + "].");
                        }

                        try {
                            // perform the registration for this service
                            this.registrationClient = new AdvertisementClient(params);
                            this.registrationClient.register();

                        } catch (Exception e) {
                            logger.error("Exception when trying to register service (" + epr + "): " + e, e);
                        }
                    } else {
                        logger.info("No resource properties to register for service (" + epr + ")");
                    }
                } else {
                    logger.warn("Registration file deserialized with no poll type (" + epr + ")");
                }
            } else {
                logger.warn("Registration file deserialized with returned null SeviceGroupParams");
            }
        } else {
            logger.info("Skipping registration.");
        }
    }

}


text:
<?php

  /**
   * blog_post actions.
   *
   * @package    playground
   * @subpackage blog_post
   */
  class blog_postActions extends sfActions
  {
    /**
     * Handling call the action Run
     *
     * @var $request sfWebRequest
     */
    public function executeRun (sfWebRequest $request)
    {

    }

    /**
     * Handling call the action UnknownMethodTest
     *
     * @var $request sfWebRequest
     */
    public function executeUnknownMethodTest (sfWebRequest $request)
    {
      $this->callSomeUnknownMethod();
    }

    /**
     * Handling call the action ValidMethodTest
     *
     * @var $request sfWebRequest
     */
    public function executeValidMethodTest (sfWebRequest $request)
    {
      $this->tags = $this->getContentTags();
    }

    public function executeCallDoctrineRecordMethodTest (sfWebRequest $request)
    {
      $post = BlogPostTable::getInstance()->createQuery()->limit(1)->fetchOne();

      $method = $request->getParameter('method');

      if ($params = $request->getParameter('args'))
      {
        call_user_func_array(array($post, $method), $params);
      }
      else
      {
        call_user_func(array($post, $method));
      }

      $this->method = $method;

      $this->className = 'Doctrine_Record';

      $this->setTemplate('callMethod');
    }

    public function executeCallDoctrineCollectionMethodTest (sfWebRequest $request)
    {
      $posts = BlogPostTable::getInstance()->findAll();

      $method = $request->getParameter('method');

      if ($params = $request->getParameter('args'))
      {
        call_user_func_array(array($posts, $method), $params);
      }
      else
      {
        call_user_func(array($posts, $method));
      }

      $this->method = $method;

      $this->className = 'Doctrine_Collection';

      $this->setTemplate('callMethod');
    }
  }


text:
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Tests.Visual;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.Drawings.Components;
using osu.Game.Tournament.Screens.Gameplay.Components;
using osu.Game.Tournament.Screens.Ladder.Components;

namespace osu.Game.Tournament.Tests.Components
{
    public class TestSceneDrawableTournamentTeam : OsuGridTestScene
    {
        public TestSceneDrawableTournamentTeam()
            : base(4, 3)
        {
            var team = new TournamentTeam
            {
                FlagName = { Value = "AU" },
                FullName = { Value = "Australia" },
                Players =
                {
                    new APIUser { Username = "ASecretBox" },
                    new APIUser { Username = "Dereban" },
                    new APIUser { Username = "mReKk" },
                    new APIUser { Username = "uyghti" },
                    new APIUser { Username = "Parkes" },
                    new APIUser { Username = "Shiroha" },
                    new APIUser { Username = "Jordan The Bear" },
                }
            };

            var match = new TournamentMatch { Team1 = { Value = team } };

            int i = 0;

            Cell(i++).AddRange(new Drawable[]
            {
                new TournamentSpriteText { Text = "DrawableTeamFlag" },
                new DrawableTeamFlag(team)
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                }
            });

            Cell(i++).AddRange(new Drawable[]
            {
                new TournamentSpriteText { Text = "DrawableTeamTitle" },
                new DrawableTeamTitle(team)
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                }
            });

            Cell(i++).AddRange(new Drawable[]
            {
                new TournamentSpriteText { Text = "DrawableTeamTitleWithHeader" },
                new DrawableTeamTitleWithHeader(team, TeamColour.Red)
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                }
            });

            Cell(i++).AddRange(new Drawable[]
            {
                new TournamentSpriteText { Text = "DrawableMatchTeam" },
                new DrawableMatchTeam(team, match, false)
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                }
            });

            Cell(i++).AddRange(new Drawable[]
            {
                new TournamentSpriteText { Text = "TeamWithPlayers" },
                new DrawableTeamWithPlayers(team, TeamColour.Blue)
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                }
            });

            Cell(i++).AddRange(new Drawable[]
            {
                new TournamentSpriteText { Text = "GroupTeam" },
                new GroupTeam(team)
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                }
            });

            Cell(i).AddRange(new Drawable[]
            {
                new TournamentSpriteText { Text = "TeamDisplay" },
                new TeamDisplay(team, TeamColour.Red, new Bindable<int?>(2), 6)
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                }
            });
        }
    }
}


text:
<?php
/**
 * @var \yii\db\ActiveRecord $model
 * @var ActiveForm $form
 * @var \DevGroup\DataStructure\models\Property $property
 * @var yii\web\View $this
 */

use DevGroup\DataStructure\assets\Select2SortableBundle;
use yii\helpers\Html;
use yii\web\View;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;

$dataQuery = $property->getStaticValues();

if ((int)$property->allow_multiple_values === 1 && !empty($model->{$property->key}) && is_array($model->{$property->key})) {
    $dataQuery->orderBy([
        new \yii\db\Expression('FIELD(id, ' . implode(',', $model->{$property->key}) . '), sort_order')
    ]);
}

echo Html::tag(
    'div',
    $form->field($model, $property->key)
        ->label($property->name)
        ->widget(
            Select2::className(),
            [
                'data' => ArrayHelper::map($dataQuery->all(), 'id', 'name'),
                'options' => [
                    'placeholder' => 'Select a value ...',
                ],
                'pluginOptions' => [
                    'allowClear' => true,
                    'multiple' => (int)$property->allow_multiple_values === 1
                ],
            ]
        ),
    [
        'style' => 'overflow: auto;'
    ]
);

if ((int)$property->allow_multiple_values === 1) {
    Select2SortableBundle::register($this);
    $id = \yii\helpers\Html::getInputId($model, $property->key);
    $this->registerJs(<<<js
    $('#$id').select2Sortable({'bindOrder':"sortableStop"});
js
    );

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 1: 320 (1882)

#### Original name
Xylaria telfairii var. telfairii

### Remarks
null


text:
package pl.biltech.httpshare.server;

import java.io.File;
import java.io.IOException;

public interface HttpShareServer {

	public void start() throws IOException;

	public void stop();

	public boolean isServerRunning();

	void addFileToDownload(File file) throws IOException;

	public String getFileToDownloadUrl();

}


text:
import collections
import logging

from django.conf import settings
from django.forms import ValidationError
from django import http
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables

from horizon import exceptions
from horizon import forms
from horizon import messages
from horizon.utils import functions as utils
from horizon.utils import validators

from openstack_dashboard import api

LOG = logging.getLogger(__name__)
PROJECT_REQUIRED = api.keystone.VERSIONS.active < 3

class PasswordMixin(forms.SelfHandlingForm):
    password = forms.RegexField(
        label=_("Password"),
        widget=forms.PasswordInput(render_value=False),
        regex=validators.password_validator(),
        error_messages={'invalid': validators.password_validator_msg()})
    confirm_password = forms.CharField(
        label=_("Confirm Password"),
        widget=forms.PasswordInput(render_value=False))
    no_autocomplete = True

    def clean(self):
        '''Check to make sure password fields match.'''
        data = super(forms.Form, self).clean()
        if 'password' in data and 'confirm_password' in data:
            if data['password'] != data['confirm_password']:
                raise ValidationError(_('Passwords do not match.'))
        return data

class BaseUserForm(forms.SelfHandlingForm):
    def __init__(self, request, *args, **kwargs):
        super(BaseUserForm, self).__init__(request, *args, **kwargs)

        # Populate project choices
        project_choices = []

        # If the user is already set (update action), list only projects which
        # the user has access to.
        user_id = kwargs['initial'].get('id', None)
        domain_id = kwargs['initial'].get('domain_id', None)
        default_project_id = kwargs['initial'].get('project', None)

        try:
            if api.keystone.VERSIONS.active >= 3:
                projects, has_more = api.keystone.tenant_list(
                    request, domain=domain_id)
            else:
                projects, has_more = api.keystone.tenant_list(
                    request, user=user_id)

            for project in sorted(projects, key=lambda p: p.name.lower()):
                if project.enabled:
                    project_choices.append((project.id, project.name))
            if not project_choices:
                project_choices.insert(0, ('', _("No available projects")))
            # TODO(david-lyle): if keystoneclient is fixed to allow unsetting
            # the default project, then this condition should be removed.
            elif default_project_id is None:
                project_choices.insert(0, ('', _("Select a project")))
            self.fields['project'].choices = project_choices

        except Exception:
            LOG.debug("User: %s has no projects", user_id)

class AddExtraColumnMixIn(object):
    def add_extra_fields(self, ordering=None):
        if api.keystone.VERSIONS.active >= 3:
            # add extra column defined by setting
            EXTRA_INFO = getattr(settings, 'USER_TABLE_EXTRA_INFO', {})
            for key, value in EXTRA_INFO.items():
                self.fields[key] = forms.CharField(label=value,
                                                   required=False)
                if ordering:
                    ordering.append(key)

ADD_PROJECT_URL = "horizon:identity:projects:create"

class CreateUserForm(PasswordMixin, BaseUserForm, AddExtraColumnMixIn):
    # Hide the domain_id and domain_name by default
    domain_id = forms.CharField(label=_("Domain ID"),
                                required=False,
                                widget=forms.HiddenInput())
    domain_name = forms.CharField(label=_("Domain Name"),
                                  required=False,
                                  widget=forms.HiddenInput())
    name = forms.CharField(max_length=255, label=_("User Name"))
    description = forms.CharField(widget=forms.widgets.Textarea(
                                  attrs={'rows': 4}),
                                  label=_("Description"),
                                  required=False)
    email = forms.EmailField(
        label=_("Email"),
        required=False)
    project = forms.ThemableDynamicChoiceField(label=_("Primary Project"),
                                               required=PROJECT_REQUIRED,
                                               add_item_link=ADD_PROJECT_URL)
    role_id = forms.ThemableChoiceField(label=_("Role"),
                                        required=PROJECT_REQUIRED)
    enabled = forms.BooleanField(label=_("Enabled"),
                                 required=False,
                                 initial=True)

    def __init__(self, *args, **kwargs):
        roles = kwargs.pop('roles')
        super(CreateUserForm, self).__init__(*args, **kwargs)
        # Reorder form fields from multiple inheritance
        ordering = ["domain_id", "domain_name", "name",
                    "description", "email", "password",
                    "confirm_password", "project", "role_id",
                    "enabled"]
        self.add_extra_fields(ordering)
        self.fields = collections.OrderedDict(
            (key, self.fields[key]) for key in ordering)
        role_choices = [
            (role.id, role.name) for role in
            sorted(roles, key=lambda r: r.name.lower())
        ]
        self.fields['role_id'].choices = role_choices

        # For keystone V3, display the two fields in read-only
        if api.keystone.VERSIONS.active >= 3:
            readonlyInput = forms.TextInput(attrs={'readonly': 'readonly'})
            self.fields["domain_id"].widget = readonlyInput
            self.fields["domain_name"].widget = readonlyInput
        # For keystone V2.0, hide description field
        else:
            self.fields["description"].widget = forms.HiddenInput()

    # We have to protect the entire "data" dict because it contains the
    # password and confirm_password strings.
    @sensitive_variables('data')
    def handle(self, request, data):
        domain = api.keystone.get_default_domain(self.request, False)
        try:
            LOG.info('Creating user with name "%s"', data['name'])
            desc = data["description"]
            if "email" in data:
                data['email'] = data['email'] or None

            # add extra information
            if api.keystone.VERSIONS.active >= 3:
                EXTRA_INFO = getattr(settings, 'USER_TABLE_EXTRA_INFO', {})
                kwargs = dict((key, data.get(key)) for key in EXTRA_INFO)
            else:
                kwargs = {}

            new_user = \
                api.keystone.user_create(request,
                                         name=data['name'],
                                         email=data['email'],
                                         description=desc or None,
                                         password=data['password'],
                                         project=data['project'] or None,
                                         enabled=data['enabled'],
                                         domain=domain.id,
                                         **kwargs)
            messages.success(request,
                             _('User "%s" was successfully created.')
                             % data['name'])
            if data['project'] and data['role_id']:
                roles = api.keystone.roles_for_user(request,
                                                    new_user.id,
                                                    data['project']) or []
                assigned = [role for role in roles if role.id == str(
                    data['role_id'])]
                if not assigned:
                    try:
                        api.keystone.add_tenant_user_role(request,
                                                          data['project'],
                                                          new_user.id,
                                                          data['role_id'])
                    except Exception:
                        exceptions.handle(request,
                                          _('Unable to add user '
                                            'to primary project.'))
            return new_user
        except exceptions.Conflict:
            msg = _('User name "%s" is already used.') % data['name']
            messages.error(request, msg)
        except Exception:
            exceptions.handle(request, _('Unable to create user.'))

class UpdateUserForm(BaseUserForm, AddExtraColumnMixIn):
    # Hide the domain_id and domain_name by default
    domain_id = forms.CharField(label=_("Domain ID"),
                                required=False,
                                widget=forms.HiddenInput())
    domain_name = forms.CharField(label=_("Domain Name"),
                                  required=False,
                                  widget=forms.HiddenInput())
    id = forms.CharField(label=_("ID"), widget=forms.HiddenInput)
    name = forms.CharField(max_length=255, label=_("User Name"))
    description = forms.CharField(widget=forms.widgets.Textarea(
                                  attrs={'rows': 4}),
                                  label=_("Description"),
                                  required=False)
    email = forms.EmailField(
        label=_("Email"),
        required=False)
    project = forms.ThemableChoiceField(label=_("Primary Project"),
                                        required=PROJECT_REQUIRED)

    def __init__(self, request, *args, **kwargs):
        super(UpdateUserForm, self).__init__(request, *args, **kwargs)
        self.add_extra_fields()
        if api.keystone.keystone_can_edit_user() is False:
            for field in ('name', 'email'):
                self.fields.pop(field)
        # For keystone V3, display the two fields in read-only
        if api.keystone.VERSIONS.active >= 3:
            readonlyInput = forms.TextInput(attrs={'readonly': 'readonly'})
            self.fields["domain_id"].widget = readonlyInput
            self.fields["domain_name"].widget = readonlyInput
        # For keystone V2.0, hide description field
        else:
            self.fields["description"].widget = forms.HiddenInput()

    def handle(self, request, data):
        user = data.pop('id')

        data.pop('domain_id')
        data.pop('domain_name')

        if not PROJECT_REQUIRED and 'project' not in self.changed_data:
            data.pop('project')

        if 'description' not in self.changed_data:
            data.pop('description')
        try:
            if "email" in data:
                data['email'] = data['email']
            response = api.keystone.user_update(request, user, **data)
            messages.success(request,
                             _('User has been updated successfully.'))
        except exceptions.Conflict:
            msg = _('User name "%s" is already used.') % data['name']
            messages.error(request, msg)
            return False
        except Exception:
            response = exceptions.handle(request, ignore=True)
            messages.error(request, _('Unable to update the user.'))

        if isinstance(response, http.HttpResponse):
            return response
        else:
            return True

class ChangePasswordForm(PasswordMixin, forms.SelfHandlingForm):
    id = forms.CharField(widget=forms.HiddenInput)
    name = forms.CharField(
        label=_("User Name"),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}),
        required=False)

    def __init__(self, request, *args, **kwargs):
        super(ChangePasswordForm, self).__init__(request, *args, **kwargs)

        if getattr(settings, 'ENFORCE_PASSWORD_CHECK', False):
            self.fields["admin_password"] = forms.CharField(
                label=_("Admin Password"),
                widget=forms.PasswordInput(render_value=False))
            # Reorder form fields from multiple inheritance
            self.fields.keyOrder = ["id", "name", "admin_password",
                                    "password", "confirm_password"]

    @sensitive_variables('data', 'password', 'admin_password')
    def handle(self, request, data):
        user_id = data.pop('id')
        password = data.pop('password')
        admin_password = None

        # Throw away the password confirmation, we're done with it.
        data.pop('confirm_password', None)

        # Verify admin password before changing user password
        if getattr(settings, 'ENFORCE_PASSWORD_CHECK', False):
            admin_password = data.pop('admin_password')
            if not api.keystone.user_verify_admin_password(request,
                                                           admin_password):
                self.api_error(_('The admin password is incorrect.'))
                return False

        try:
            response = api.keystone.user_update_password(
                request, user_id, password, admin=False)
            if user_id == request.user.id:
                return utils.logout_with_message(
                    request,
                    _('Password changed. Please log in to continue.'),
                    redirect=False)
            messages.success(request,
                             _('User password has been updated successfully.'))
        except Exception:
            response = exceptions.handle(request, ignore=True)
            messages.error(request, _('Unable to update the user password.'))

        if isinstance(response, http.HttpResponse):
            return response
        else:
            return True


text:
title: "Statistical Framework for the mpRCT of Therapeutic Anticoagulation in Covid-19"
collection: talks
type: "Livestream of trial results"
permalink: /talks/2021-08-04-ccr
venue: "Critical Care Reviews"
date: 2021-08-04
location: "Virtual"
---

Livestream of the results of the mpRCT trial of therapeutic anticoagulation in Covid-19 hosted by Critical Care Reviews corresponding with publications released in NEJM.

[Download slides here](http://lindsayberry.github.io/files/CCR-slides-mpRCT.pdf)


text:
using System.Windows;
using DictaDotNet;
using System;

namespace InterestSample
{
    public partial class MainWindow : Window
    {
        private DictaWPF dictaWpf;

        public MainWindow()
        {
            InitializeComponent();
            dictaWpf = new DictaWPF();
            dictaWpf.Init(this);
        }
    }
}