text:
from __future__ import unicode_literals

from django.apps import apps
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.core import checks
from django.db import models, DEFAULT_DB_ALIAS
from django.db.models import signals
from django.test import TestCase, override_settings

from .models import (MyPerson, Person, StatusPerson, LowerStatusPerson,
    MyPersonProxy, Abstract, OtherPerson, User, UserProxy, UserProxyProxy,
    Country, State, StateProxy, TrackerUser, BaseUser, Bug, ProxyTrackerUser,
    Improvement, ProxyProxyBug, ProxyBug, ProxyImprovement, Issue)
from .admin import admin as force_admin_model_registration  # NOQA

class ProxyModelTests(TestCase):
    def test_same_manager_queries(self):
        """
        The MyPerson model should be generating the same database queries as
        the Person model (when the same manager is used in each case).
        """
        my_person_sql = MyPerson.other.all().query.get_compiler(
            DEFAULT_DB_ALIAS).as_sql()
        person_sql = Person.objects.order_by("name").query.get_compiler(
            DEFAULT_DB_ALIAS).as_sql()
        self.assertEqual(my_person_sql, person_sql)

    def test_inheretance_new_table(self):
        """
        The StatusPerson models should have its own table (it's using ORM-level
        inheritance).
        """
        sp_sql = StatusPerson.objects.all().query.get_compiler(
            DEFAULT_DB_ALIAS).as_sql()
        p_sql = Person.objects.all().query.get_compiler(
            DEFAULT_DB_ALIAS).as_sql()
        self.assertNotEqual(sp_sql, p_sql)

    def test_basic_proxy(self):
        """
        Creating a Person makes them accessible through the MyPerson proxy.
        """
        person = Person.objects.create(name="Foo McBar")
        self.assertEqual(len(Person.objects.all()), 1)
        self.assertEqual(len(MyPerson.objects.all()), 1)
        self.assertEqual(MyPerson.objects.get(name="Foo McBar").id, person.id)
        self.assertFalse(MyPerson.objects.get(id=person.id).has_special_name())

    def test_no_proxy(self):
        """
        Person is not proxied by StatusPerson subclass.
        """
        Person.objects.create(name="Foo McBar")
        self.assertEqual(list(StatusPerson.objects.all()), [])

    def test_basic_proxy_reverse(self):
        """
        A new MyPerson also shows up as a standard Person.
        """
        MyPerson.objects.create(name="Bazza del Frob")
        self.assertEqual(len(MyPerson.objects.all()), 1)
        self.assertEqual(len(Person.objects.all()), 1)

        LowerStatusPerson.objects.create(status="low", name="homer")
        lsps = [lsp.name for lsp in LowerStatusPerson.objects.all()]
        self.assertEqual(lsps, ["homer"])

    def test_correct_type_proxy_of_proxy(self):
        """
        Correct type when querying a proxy of proxy
        """
        Person.objects.create(name="Foo McBar")
        MyPerson.objects.create(name="Bazza del Frob")
        LowerStatusPerson.objects.create(status="low", name="homer")
        pp = sorted(mpp.name for mpp in MyPersonProxy.objects.all())
        self.assertEqual(pp, ['Bazza del Frob', 'Foo McBar', 'homer'])

    def test_proxy_included_in_ancestors(self):
        """
        Proxy models are included in the ancestors for a model's DoesNotExist
        and MultipleObjectsReturned
        """
        Person.objects.create(name="Foo McBar")
        MyPerson.objects.create(name="Bazza del Frob")
        LowerStatusPerson.objects.create(status="low", name="homer")
        max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id']

        self.assertRaises(
            Person.DoesNotExist,
            MyPersonProxy.objects.get,
            name='Zathras'
        )
        self.assertRaises(
            Person.MultipleObjectsReturned,
            MyPersonProxy.objects.get,
            id__lt=max_id + 1
        )
        self.assertRaises(
            Person.DoesNotExist,
            StatusPerson.objects.get,
            name='Zathras'
        )

        StatusPerson.objects.create(name='Bazza Jr.')
        StatusPerson.objects.create(name='Foo Jr.')
        max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id']

        self.assertRaises(
            Person.MultipleObjectsReturned,
            StatusPerson.objects.get,
            id__lt=max_id + 1
        )

    def test_abc(self):
        """
        All base classes must be non-abstract
        """
        def build_abc():
            class NoAbstract(Abstract):
                class Meta:
                    proxy = True
        self.assertRaises(TypeError, build_abc)

    def test_no_cbc(self):
        """
        The proxy must actually have one concrete base class
        """
        def build_no_cbc():
            class TooManyBases(Person, Abstract):
                class Meta:
                    proxy = True
        self.assertRaises(TypeError, build_no_cbc)

    def test_no_base_classes(self):
        def build_no_base_classes():
            class NoBaseClasses(models.Model):
                class Meta:
                    proxy = True
        self.assertRaises(TypeError, build_no_base_classes)

    def test_new_fields(self):
        class NoNewFields(Person):
            newfield = models.BooleanField()

            class Meta:
                proxy = True
                # don't register this model in the app_cache for the current app,
                # otherwise the check fails when other tests are being run.
                app_label = 'no_such_app'

        errors = NoNewFields.check()
        expected = [
            checks.Error(
                "Proxy model 'NoNewFields' contains model fields.",
                hint=None,
                obj=None,
                id='models.E017',
            )
        ]
        self.assertEqual(errors, expected)

    @override_settings(TEST_SWAPPABLE_MODEL='proxy_models.AlternateModel')
    def test_swappable(self):
        # The models need to be removed after the test in order to prevent bad
        # interactions with the flush operation in other tests.
        _old_models = apps.app_configs['proxy_models'].models.copy()

        try:
            class SwappableModel(models.Model):

                class Meta:
                    swappable = 'TEST_SWAPPABLE_MODEL'

            class AlternateModel(models.Model):
                pass

            # You can't proxy a swapped model
            with self.assertRaises(TypeError):
                class ProxyModel(SwappableModel):

                    class Meta:
                        proxy = True
        finally:
            apps.app_configs['proxy_models'].models = _old_models
            apps.all_models['proxy_models'] = _old_models
            apps.clear_cache()

    def test_myperson_manager(self):
        Person.objects.create(name="fred")
        Person.objects.create(name="wilma")
        Person.objects.create(name="barney")

        resp = [p.name for p in MyPerson.objects.all()]
        self.assertEqual(resp, ['barney', 'fred'])

        resp = [p.name for p in MyPerson._default_manager.all()]
        self.assertEqual(resp, ['barney', 'fred'])

    def test_otherperson_manager(self):
        Person.objects.create(name="fred")
        Person.objects.create(name="wilma")
        Person.objects.create(name="barney")

        resp = [p.name for p in OtherPerson.objects.all()]
        self.assertEqual(resp, ['barney', 'wilma'])

        resp = [p.name for p in OtherPerson.excluder.all()]
        self.assertEqual(resp, ['barney', 'fred'])

        resp = [p.name for p in OtherPerson._default_manager.all()]
        self.assertEqual(resp, ['barney', 'wilma'])

    def test_permissions_created(self):
        from django.contrib.auth.models import Permission
        try:
            Permission.objects.get(name="May display users information")
        except Permission.DoesNotExist:
            self.fail("The permission 'May display users information' has not been created")

    def test_proxy_model_signals(self):
        """
        Test save signals for proxy models
        """
        output = []

        def make_handler(model, event):
            def _handler(*args, **kwargs):
                output.append('%s %s save' % (model, event))
            return _handler

        h1 = make_handler('MyPerson', 'pre')
        h2 = make_handler('MyPerson', 'post')
        h3 = make_handler('Person', 'pre')
        h4 = make_handler('Person', 'post')

        signals.pre_save.connect(h1, sender=MyPerson)
        signals.post_save.connect(h2, sender=MyPerson)
        signals.pre_save.connect(h3, sender=Person)
        signals.post_save.connect(h4, sender=Person)

        MyPerson.objects.create(name="dino")
        self.assertEqual(output, [
            'MyPerson pre save',
            'MyPerson post save'
        ])

        output = []

        h5 = make_handler('MyPersonProxy', 'pre')
        h6 = make_handler('MyPersonProxy', 'post')

        signals.pre_save.connect(h5, sender=MyPersonProxy)
        signals.post_save.connect(h6, sender=MyPersonProxy)

        MyPersonProxy.objects.create(name="pebbles")

        self.assertEqual(output, [
            'MyPersonProxy pre save',
            'MyPersonProxy post save'
        ])

        signals.pre_save.disconnect(h1, sender=MyPerson)
        signals.post_save.disconnect(h2, sender=MyPerson)
        signals.pre_save.disconnect(h3, sender=Person)
        signals.post_save.disconnect(h4, sender=Person)
        signals.pre_save.disconnect(h5, sender=MyPersonProxy)
        signals.post_save.disconnect(h6, sender=MyPersonProxy)

    def test_content_type(self):
        ctype = ContentType.objects.get_for_model
        self.assertIs(ctype(Person), ctype(OtherPerson))

    def test_user_userproxy_userproxyproxy(self):
        User.objects.create(name='Bruce')

        resp = [u.name for u in User.objects.all()]
        self.assertEqual(resp, ['Bruce'])

        resp = [u.name for u in UserProxy.objects.all()]
        self.assertEqual(resp, ['Bruce'])

        resp = [u.name for u in UserProxyProxy.objects.all()]
        self.assertEqual(resp, ['Bruce'])

    def test_proxy_for_model(self):
        self.assertEqual(UserProxy, UserProxyProxy._meta.proxy_for_model)

    def test_concrete_model(self):
        self.assertEqual(User, UserProxyProxy._meta.concrete_model)

    def test_proxy_delete(self):
        """
        Proxy objects can be deleted
        """
        User.objects.create(name='Bruce')
        u2 = UserProxy.objects.create(name='George')

        resp = [u.name for u in UserProxy.objects.all()]
        self.assertEqual(resp, ['Bruce', 'George'])

        u2.delete()

        resp = [u.name for u in UserProxy.objects.all()]
        self.assertEqual(resp, ['Bruce'])

    def test_select_related(self):
        """
        We can still use `select_related()` to include related models in our
        querysets.
        """
        country = Country.objects.create(name='Australia')
        State.objects.create(name='New South Wales', country=country)

        resp = [s.name for s in State.objects.select_related()]
        self.assertEqual(resp, ['New South Wales'])

        resp = [s.name for s in StateProxy.objects.select_related()]
        self.assertEqual(resp, ['New South Wales'])

        self.assertEqual(StateProxy.objects.get(name='New South Wales').name,
            'New South Wales')

        resp = StateProxy.objects.select_related().get(name='New South Wales')
        self.assertEqual(resp.name, 'New South Wales')

    def test_proxy_bug(self):
        contributor = TrackerUser.objects.create(name='Contributor',
            status='contrib')
        someone = BaseUser.objects.create(name='Someone')
        Bug.objects.create(summary='fix this', version='1.1beta',
            assignee=contributor, reporter=someone)
        pcontributor = ProxyTrackerUser.objects.create(name='OtherContributor',
            status='proxy')
        Improvement.objects.create(summary='improve that', version='1.1beta',
            assignee=contributor, reporter=pcontributor,
            associated_bug=ProxyProxyBug.objects.all()[0])

        # Related field filter on proxy
        resp = ProxyBug.objects.get(version__icontains='beta')
        self.assertEqual(repr(resp), '<ProxyBug: ProxyBug:fix this>')

        # Select related + filter on proxy
        resp = ProxyBug.objects.select_related().get(version__icontains='beta')
        self.assertEqual(repr(resp), '<ProxyBug: ProxyBug:fix this>')

        # Proxy of proxy, select_related + filter
        resp = ProxyProxyBug.objects.select_related().get(
            version__icontains='beta'
        )
        self.assertEqual(repr(resp), '<ProxyProxyBug: ProxyProxyBug:fix this>')

        # Select related + filter on a related proxy field
        resp = ProxyImprovement.objects.select_related().get(
            reporter__name__icontains='butor'
        )
        self.assertEqual(
            repr(resp),
            '<ProxyImprovement: ProxyImprovement:improve that>'
        )

        # Select related + filter on a related proxy of proxy field
        resp = ProxyImprovement.objects.select_related().get(
            associated_bug__summary__icontains='fix'
        )
        self.assertEqual(
            repr(resp),
            '<ProxyImprovement: ProxyImprovement:improve that>'
        )

    def test_proxy_load_from_fixture(self):
        management.call_command('loaddata', 'mypeople.json', verbosity=0)
        p = MyPerson.objects.get(pk=100)
        self.assertEqual(p.name, 'Elvis Presley')

    def test_eq(self):
        self.assertEqual(MyPerson(id=100), Person(id=100))

@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
                   ROOT_URLCONF='proxy_models.urls',)
class ProxyModelAdminTests(TestCase):
    fixtures = ['myhorses']

    def test_cascade_delete_proxy_model_admin_warning(self):
        """
        Test if admin gives warning about cascade deleting models referenced
        to concrete model by deleting proxy object.
        """
        tracker_user = TrackerUser.objects.all()[0]
        base_user = BaseUser.objects.all()[0]
        issue = Issue.objects.all()[0]
        with self.assertNumQueries(7):
            collector = admin.utils.NestedObjects('default')
            collector.collect(ProxyTrackerUser.objects.all())
        self.assertIn(tracker_user, collector.edges.get(None, ()))
        self.assertIn(base_user, collector.edges.get(None, ()))
        self.assertIn(issue, collector.edges.get(tracker_user, ()))

    def test_delete_str_in_model_admin(self):
        """
        Test if the admin delete page shows the correct string representation
        for a proxy model.
        """
        user = TrackerUser.objects.get(name='Django Pony')
        proxy = ProxyTrackerUser.objects.get(name='Django Pony')

        user_str = (
            'Tracker user: %s' % (user.pk, user))
        proxy_str = (
            'Proxy tracker user: %s' %
            (proxy.pk, proxy))

        self.client.login(username='super', password='secret')
        response = self.client.get('/admin/proxy_models/trackeruser/%s/delete/' % (user.pk,))
        delete_str = response.context['deleted_objects'][0]
        self.assertEqual(delete_str, user_str)
        response = self.client.get('/admin/proxy_models/proxytrackeruser/%s/delete/' % (proxy.pk,))
        delete_str = response.context['deleted_objects'][0]
        self.assertEqual(delete_str, proxy_str)
        self.client.logout()


text:
"""Restore a deleted StoredFileNode. If the file was reuploaded, renames the file
to <filename> (restored).<ext>. For example, README.rst would be renamed to README (restored).rst.

    python -m scripts.restore_file 123ab --dry
    python -m scripts.restore_file 123ab

"""
import sys
import logging

from framework.transactions.context import TokuTransaction
from website.app import init_app
from website.files.models.base import TrashedFileNode, StoredFileNode
from scripts import utils as script_utils

logger = logging.getLogger(__name__)

def main():
    init_app(routes=False)
    dry = '--dry' in sys.argv
    if not dry:
        script_utils.add_file_logger(logger, __file__)
    with TokuTransaction():
        stored = StoredFileNode.find().get_keys()
        trashed = TrashedFileNode.find().get_keys()

        stored_set = set(stored)
        trashed_set = set(trashed)

        intersection = trashed_set & stored_set

        print('There are {} restored trashed file nodes'.format(len(intersection)))

        for trash_id in intersection:
            TrashedFileNode.remove_one(trash_id)
            print('Removed TrashedFileNode {}'.format(trash_id))

        if dry:
            raise RuntimeError('Dry run - rolling back transaction')

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Mycol. Soc. Japan 14(2): 176 (1973)

#### Original name
Sporormia cainii Mukerji & N.N. Bhandari

### Remarks
null


text:
//
//  ZHAdvertisementSView.h
//  02-广告视图
//
//  Created by qianfeng on 15/12/15.
//  Copyright (c) 2015年 肖喆. All rights reserved.
//

#import <UIKit/UIKit.h>
@class ZHAdvertisementSView;
@protocol ZHAdvertisementSViewDelegate
@optional
/**
 *  图片被点击后调用这个方法
 */
- (void)advertisementSView:(ZHAdvertisementSView *)scrollView imageViewDidClickAtIndex:(NSInteger)index;
@end

@interface ZHAdvertisementSView : UIScrollView<UIScrollViewDelegate>

@property (nonatomic,weak) id<ZHAdvertisementSViewDelegate> ZHDelegate;

/**
 *  可以设置是否添加定时器
 */
@property (nonatomic,assign,getter=isAddTimer)BOOL addTimer;
//@property (nonatomic,strong)UIPageControl *pageControl;

/**
 *  返回一个顶部的广告滚动条 默认为宽度屏幕宽度 ,高度150*ZHScale
 */
+ (instancetype)advertisementScrollVeiw;
/**
 *  添加需要滚动的图片数组
 */
- (void)addImages :(NSArray *)imageNames;

/**
 *可初始化frame
 */
- (instancetype)initWithFrame:(CGRect)frame;
/**
 *  可以传入自定义view 的数组 供滚动
 */
- (void)addCustomViewArray:(NSArray *)viewArray;

@end


text:
class ActorManager : public IActorManager
{
    public:
        ActorManager();
        virtual ~ActorManager();

        virtual void Add(const ActorPtr actor) override;
        virtual bool Remove(ActorId id) override;
        virtual ActorPtr Get(ActorId id) override;
        virtual void Update() override;
        virtual void Render() override;
        virtual bool IsColliding(const Actor& actor, ActorPtr collider) override;
        virtual bool IsColliding(const AABB2& box, ActorPtr collider) override;

private:
        // non-copyable
        ActorManager(const ActorManager& rhs);
        ActorManager& operator=(const ActorManager& rhs);

    protected:
        ActorPtrList m_actors;
};

#endif //__ACTORMANAGER_H_


text:
package org.camunda.bpm.extension.osgi.itest.scripting;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Hashtable;

import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.extension.osgi.engine.ProcessEngineFactory;
import org.camunda.bpm.extension.osgi.engine.ProcessEngineFactoryWithELResolver;
import org.camunda.bpm.extension.osgi.itest.OSGiTestEnvironment;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.CoreOptions;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.OptionUtils;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.ops4j.pax.tinybundles.core.TinyBundles;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;

@RunWith(PaxExam.class)
@ExamReactorStrategy(PerMethod.class)
public class ScriptEngineBundleTrackerCustomizerIntegrationTest extends OSGiTestEnvironment {

  @Configuration
  @Override
  public Option[] createConfiguration() {
    return OptionUtils.combine(super.createConfiguration(), CoreOptions.provision(createTestBundle()));
  }

  protected ProcessEngine processEngine;

  @Before
  public void setUp() {
    createProcessEngine();
  }

  @After
  public void tearDown() {
    processEngine.close();
  }

  private void createProcessEngine() {
    StandaloneProcessEngineConfiguration configuration = new StandaloneProcessEngineConfiguration();
    configuration.setDatabaseSchemaUpdate("create-drop").setDataSource(createDatasource()).setJobExecutorActivate(false);
    ProcessEngineFactory processEngineFactory = new ProcessEngineFactoryWithELResolver();
    processEngineFactory.setProcessEngineConfiguration(configuration);
    processEngineFactory.setBundle(getBundle("org.camunda.bpm.extension.osgi"));
    try {
      processEngineFactory.init();
      processEngine = processEngineFactory.getObject();
      ctx.registerService(ProcessEngine.class.getName(), processEngine, new Hashtable<String, String>());
    } catch (Exception e) {
      fail(e.toString());
    }
  }

  private InputStream createTestBundle() {
    try {
      return TinyBundles
          .bundle()
          .add("META-INF/services/javax.script.ScriptEngineFactory",
              new FileInputStream(new File("src/test/resources/scripting/javax.script.ScriptEngineFactory")))
          .add(TestScriptEngineFactory.class)
          .add(org.camunda.bpm.extension.osgi.Constants.BUNDLE_PROCESS_DEFINTIONS_DEFAULT + "testScriptProcess.bpmn",
              new FileInputStream(new File("src/test/resources/scripting/testScriptProcess.bpmn"))).set(Constants.DYNAMICIMPORT_PACKAGE, "*")
          .set(Constants.BUNDLE_SYMBOLICNAME, "org.camunda.bpm.osgi.example").build();
    } catch (FileNotFoundException fnfe) {
      fail(fnfe.toString());
      return null;
    }
  }

  @Test
  public void scriptEngineHasBeenRegistered() throws BundleException {
    ProcessInstance instance = processEngine.getRuntimeService().startProcessInstanceByKey("Process_1");
    assertThat(instance.isEnded(), is(true));
  }

  /**
   * The Engine should throw a {@link ProcessEngineException} when trying to
   * execute the script because the bundle with the ScriptEngine has been
   * uninstalled.
   */
  @Test(expected = ProcessEngineException.class)
  public void scriptEngineHasUnregisteredAfterBundleUninstall() throws BundleException {
    Bundle testBundle = getBundle("org.camunda.bpm.osgi.example");
    testBundle.uninstall();
    processEngine.getRuntimeService().startProcessInstanceByKey("Process_1");
  }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
    <changeSet author="maxence" id="1496904921-1">
        <renameColumn tableName="iteration_plannedworkloads"
                      oldColumnName="period"
                      newColumnName="num_period" />
        <renameColumn tableName="iteration_replannedworkloads"
                      oldColumnName="period"
                      newColumnName="num_period" />
    </changeSet>
</databaseChangeLog>


text:
"""
The Record class is the container/wrapper for information
    that pertains to a particular record in the Airtable
    web application. This class will hold the following
    pieces of information:
        - a table object, which permits mutability of the record
        - the record id
        - the raw JSON object (which should be parsed by requests)
        - and methods to allow for the alteration of a record
        (namely patch and put updates)
    Important Methods:
        - init: assign the above info
        - getId: returns the record ID
        - get: returns a particular field value (passed the fieldName)
        - set: sets a particular field value to be the passed in value
        - save: ??? I guess it just issues a put request to update
            the object stored on the server
        -
"""

class Record(object):
    """docstring for Record"""
    def __init__(self, arg):
        self.arg = arg


text:
import base64
import json

from twisted.internet.defer import (
    inlineCallbacks, returnValue, Deferred, succeed)
from twisted.web.error import SchemeNotSupported

from vumi.config import ConfigInt, ConfigText, ConfigList
from vumi.utils import http_request_full
from vumi.transports.httprpc import httprpc
from vumi import log

from go.apps.http_api_nostream.auth import AuthorizedResource
from go.apps.http_api_nostream.resource import ConversationResource
from go.vumitools.app_worker import GoApplicationWorker
from go.vumitools.utils import extract_auth_from_url

# NOTE: Things in this module are subclassed and used by go.apps.http_api.

class HTTPWorkerConfig(GoApplicationWorker.CONFIG_CLASS):
    """Configuration options for StreamingHTTPWorker."""

    web_path = ConfigText(
        "The path the HTTP worker should expose the API on.",
        required=True, static=True)
    web_port = ConfigInt(
        "The port the HTTP worker should open for the API.",
        required=True, static=True)
    health_path = ConfigText(
        "The path the resource should receive health checks on.",
        default='/health/', static=True)
    concurrency_limit = ConfigInt(
        "Maximum number of clients per account. A value less than "
        "zero disables the limit.",
        default=10)
    timeout = ConfigInt(
        "How long to wait for a response from a server when posting "
        "messages or events", default=5, static=True)
    worker_concurrency_limit = ConfigInt(
        "Maximum number of clients per account per worker. A value less than "
        "zero disables the limit. (Unlike concurrency_limit, this queues "
        "requests instead of rejecting them.)",
        default=1, static=True)
    http_retry_api = ConfigText(
        "Base URL for the HTTP Retry API. If set to null, message and"
        " event requests are not retried.",
        default=None, static=True)
    http_retry_intervals = ConfigList(
        "List of delays, in seconds relative to the initial failed request, at"
        " which retries should be scheduled. Default is 5 minutes, 30 minutes"
        " and 1 hour.",
        default=(300, 1800, 3600), static=True)
    http_retry_timeout = ConfigInt(
        "How long to wait for a response from the retry API (in seconds).",
        default=5, static=True)

class ConcurrencyLimiterError(Exception):
    """
    Error raised by concurrency limiters.
    """

class ConcurrencyLimiter(object):
    """
    Concurrency limiter.

    Each concurrent operation should call :meth:`start` and wait for the
    deferred it returns to fire before doing any work. When it's done, it
    should call :meth:`stop` to signal completion and allow the next queued
    operation to begin.

    Internally, we track two things:
      * :attr:`_concurrents` holds the number of active operations, for which
        the deferred returned by :meth:`start` has fired, but :meth:`stop` has
        not been called.
      * :attr:`_waiters` holds a list of pending deferreds that have been
        returned by :meth:`start` but not yet fired.
    """

    def __init__(self, name, limit):
        self._name = name
        self._limit = limit
        self._concurrents = 0
        self._waiters = []

    def _inc_concurrent(self):
        self._concurrents += 1
        return self._concurrents

    def _dec_concurrent(self):
        if self._concurrents <= 0:
            raise ConcurrencyLimiterError(
                "Can't decrement key below zero: %s" % (self._name,))
        else:
            self._concurrents -= 1
        return self._concurrents

    def _make_waiter(self):
        d = Deferred()
        self._waiters.append(d)
        return d

    def _pop_waiter(self):
        if not self._waiters:
            return None
        return self._waiters.pop(0)

    def _check_concurrent(self):
        if self._concurrents >= self._limit:
            return
        d = self._pop_waiter()
        if d is not None:
            self._inc_concurrent()
            d.callback(None)

    def empty(self):
        """
        Check if this concurrency limiter is empty so it can be cleaned up.
        """
        return (not self._concurrents) and (not self._waiters)

    def start(self):
        """
        Start a concurrent operation.

        If we are below the limit, we increment the concurrency count and fire
        the deferred we return. If not, we add the deferred to the waiters list
        and return it unfired.
        """
        # While the implemetation matches the description in the docstring
        # conceptually, it always adds a new waiter and then calls
        # _check_concurrent() to handle the various cases.
        if self._limit < 0:
            # Special case for no limit, never block.
            return succeed(None)
        elif self._limit == 0:
            # Special case for limit of zero, always block forever.
            return Deferred()
        d = self._make_waiter()
        self._check_concurrent()
        return d

    def stop(self):
        """
        Stop a concurrent operation.

        If there are waiting operations, we pop and fire the first. If not, we
        decrement the concurrency count.
        """
        # While the implemetation matches the description in the docstring
        # conceptually, it always decrements the concurrency counter and then
        # calls _check_concurrent() to handle the various cases.
        if self._limit <= 0:
            # Special case for where we don't keep state.
            return
        self._dec_concurrent()
        self._check_concurrent()

class ConcurrencyLimitManager(object):
    """
    Concurrency limit manager.

    Each concurrent operation should call :meth:`start` with a key and wait for
    the deferred it returns to fire before doing any work. When it's done, it
    should call :meth:`stop` to signal completion and allow the next queued
    operation to begin.
    """

    def __init__(self, limit):
        self._limit = limit
        self._concurrency_limiters = {}

    def _get_limiter(self, key):
        if key not in self._concurrency_limiters:
            self._concurrency_limiters[key] = ConcurrencyLimiter(
                key, self._limit)
        return self._concurrency_limiters[key]

    def _cleanup_limiter(self, key):
        limiter = self._concurrency_limiters.get(key)
        if limiter and limiter.empty():
            del self._concurrency_limiters[key]

    def start(self, key):
        """
        Start a concurrent operation.

        This gets the concurrency limiter for the given key (creating it if
        necessary) and starts a concurrent operation on it.
        """
        start_d = self._get_limiter(key).start()
        self._cleanup_limiter(key)
        return start_d

    def stop(self, key):
        """
        Stop a concurrent operation.

        This gets the concurrency limiter for the given key (creating it if
        necessary) and stops a concurrent operation on it. If the concurrency
        limiter is empty, it is deleted.
        """
        self._get_limiter(key).stop()
        self._cleanup_limiter(key)

class HttpRetryApiError(Exception):
    """
    Raised when an error occurs while submitting HTTP requests for retrying.
    """

class NoStreamingHTTPWorker(GoApplicationWorker):

    worker_name = 'http_api_nostream_worker'
    CONFIG_CLASS = HTTPWorkerConfig

    @inlineCallbacks
    def setup_application(self):
        yield super(NoStreamingHTTPWorker, self).setup_application()
        config = self.get_static_config()
        self.web_path = config.web_path
        self.web_port = config.web_port
        self.health_path = config.health_path

        # HTTP request settings
        self.http_request_timeout = config.timeout

        # HTTP retry API settings
        self.http_retry_api = config.http_retry_api
        self.http_retry_intervals = config.http_retry_intervals
        self.http_retry_timeout = config.http_retry_timeout

        # Set these to empty dictionaries because we're not interested
        # in using any of the helper functions at this point.
        self._event_handlers = {}
        self._session_handlers = {}

        self.concurrency_limiter = ConcurrencyLimitManager(
            config.worker_concurrency_limit)
        self.webserver = self.start_web_resources([
            (self.get_conversation_resource(), self.web_path),
            (httprpc.HttpRpcHealthResource(self), self.health_path),
        ], self.web_port)

    def get_conversation_resource(self):
        return AuthorizedResource(self, ConversationResource)

    @inlineCallbacks
    def teardown_application(self):
        yield super(NoStreamingHTTPWorker, self).teardown_application()
        yield self.webserver.loseConnection()

    def get_all_api_config(self, conversation):
        return conversation.config.get('http_api_nostream', {})

    def get_api_config(self, conversation, key, default=None):
        return self.get_all_api_config(conversation).get(key, default)

    @inlineCallbacks
    def consume_user_message(self, message):
        msg_mdh = self.get_metadata_helper(message)
        conversation = yield msg_mdh.get_conversation()
        if conversation is None:
            log.warning("Cannot find conversation for message: %r" % (
                message,))
            return
        ignore = self.get_api_config(conversation, 'ignore_messages', False)
        if not ignore:
            push_url = self.get_api_config(conversation, 'push_message_url')
            yield self.send_message_to_client(message, conversation, push_url)

    def send_message_to_client(self, message, conversation, push_url):
        if push_url is None:
            log.warning(
                "push_message_url not configured for conversation: %s" % (
                    conversation.key))
            return
        return self.push(conversation.user_account.key, push_url, message)

    @inlineCallbacks
    def consume_unknown_event(self, event):
        config = yield self.get_message_config(event)
        conversation = config.conversation
        ignore = self.get_api_config(conversation, 'ignore_events', False)
        if not ignore:
            push_url = self.get_api_config(conversation, 'push_event_url')
            yield self.send_event_to_client(event, conversation, push_url)

    def send_event_to_client(self, event, conversation, push_url):
        if push_url is None:
            log.info(
                "push_event_url not configured for conversation: %s" % (
                    conversation.key))
            return
        return self.push(conversation.user_account.key, push_url, event)

    @inlineCallbacks
    def schedule_push_retry(self, user_account_key, url, method, data,
                            headers):
        if self.http_retry_api is None:
            returnValue(None)
        list_headers = dict((k, [v]) for k, v in headers.iteritems())
        retry_url = (
            self.http_retry_api.encode("utf-8").rstrip('/') + '/requests/')
        retry_headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'X-Owner-ID': user_account_key.encode("utf-8"),
        }
        retry_data = json.dumps({
            "intervals": self.http_retry_intervals,
            "request": {
                "url": url,
                "method": method,
                "body": data,
                "headers": list_headers,
            },
        }).encode('utf-8')
        try:
            resp = yield http_request_full(
                retry_url, data=retry_data, headers=retry_headers,
                timeout=self.http_retry_timeout)
            if resp.code == 429:
                log.warning(
                    "Retrying is rate limited for account '%s'."
                    " Discarding HTTP request." % (user_account_key,))
                returnValue(None)
            elif not (200 <= resp.code < 300):
                raise HttpRetryApiError(
                    "HTTP retry failed: %s - %s" % (resp.code, resp.phrase))
        except Exception as err:
            log.warning(
                'Error scheduling retry of request'
                ' [account: %r, request: %r, error: %r]'
                % (user_account_key, retry_data, err))
            raise
        log.info(
            'Successfully scheduled retry of request'
            ' [account: %r, url: %r]'
            % (user_account_key, url))

    def _push_headers(self, auth=None):
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
        }
        if auth is not None:
            username, password = auth
            if username is None:
                username = ''
            if password is None:
                password = ''
            headers['Authorization'] = 'Basic %s' % (
                base64.b64encode('%s:%s' % (username, password)),)
        return headers

    @inlineCallbacks
    def push(self, user_account_key, url, vumi_message):
        data = vumi_message.to_json().encode('utf-8')
        auth, url = extract_auth_from_url(url.encode('utf-8'))
        headers = self._push_headers(auth=auth)
        retry_required = True
        try:
            resp = yield http_request_full(
                url, data=data, headers=headers,
                timeout=self.http_request_timeout)
        except Exception as err:
            log.warning('%s pushing message to %s (%r)'
                        % (err.__class__.__name__, url, err))
            if isinstance(err, SchemeNotSupported):
                # retrying bad URLs won't help
                retry_required = False
        else:
            if 200 <= resp.code < 300:
                retry_required = False
            else:
                log.warning('Got unexpected response code %s from %s' % (
                            resp.code, url))
                if not (500 <= resp.code < 600):
                    retry_required = False
        if retry_required:
            yield self.schedule_push_retry(
                user_account_key, url=url, method='POST', data=data,
                headers=headers)

    def get_health_response(self):
        return "OK"


text:
var pbs = require('../')
var protobuf = require('protocol-buffers')
var tape = require('tape')
var fs = require('fs')

var schema = fs.readFileSync(__dirname + '/test.proto')
var messages = pbs(schema)
var pbMessages = protobuf(schema)

tape('decodes', function (t) {
  t.plan(1)

  var decoder = messages.Test.decode()

  decoder.hello(function (hello, cb) {
    t.same(hello, 'world', 'got hello world')
  })

  decoder.on('finish', function () {
    t.end()
  })

  var buf = pbMessages.Test.encode({
    hello: 'world'
  })

  decoder.end(buf)
})

tape('decodes required field only once', function (t) {
  t.plan(1)

  var decoder = messages.Test.decode()

  decoder.hello(function (hello, cb) {
    t.same(hello, 'world', 'got hello world')
    cb()
  })

  decoder.on('finish', function () {
    t.end()
  })

  var buf = pbMessages.TestRepeated.encode({
    hello: ['world', 'world2']
  })

  decoder.end(buf)
})

tape('decodes repeated', function (t) {
  t.plan(3)

  var decoder = messages.TestRepeated.decode()
  var expected = ['a', 'b', 'c']

  decoder.hello(function (hello, cb) {
    t.same(hello, expected.shift())
    cb()
  })

  decoder.on('finish', function () {
    t.end()
  })

  var buf = pbMessages.TestRepeated.encode({
    hello: expected
  })

  decoder.end(buf)
})

tape('decoder fails if missing required message', function (t) {
  t.plan(1)

  var decoder = messages.Test.decode()

  decoder.on('error', function (err) {
    t.ok(err, 'had error')
    t.end()
  })

  decoder.end()
})

tape('decoder allows missing optional message', function (t) {
  t.plan(1)

  var decoder = messages.TestOptional.decode()

  decoder.on('finish', function () {
    t.ok(true, 'everthing is fine')
    t.end()
  })

  decoder.end()
})


text:
import uuid
from xml.etree import ElementTree as ET

from amt import client

# Additional useful constants
NS_SOAP_ENV = 'http://www.w3.org/2003/05/soap-envelope'
NS_WS_ADDR = 'http://schemas.xmlsoap.org/ws/2004/08/addressing'
NS_WSMAN = 'http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd'

_ANONYMOUS = 'http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous'
METHOD_GET = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get"
METHOD_PUT = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Put"

ET.register_namespace('s', NS_SOAP_ENV)
ET.register_namespace('wsa', NS_WS_ADDR)
ET.register_namespace('wsman', NS_WSMAN)

# Pre-define QName wrapper which consist of {uri}local
_QN_MUSTUNDERSTAND = ET.QName(NS_SOAP_ENV, 'mustUnderstand')
_QN_ENVELOPE = ET.QName(NS_SOAP_ENV, 'Envelope')
_QN_HEADER = ET.QName(NS_SOAP_ENV, 'Header')
_QN_ACTION = ET.QName(NS_WS_ADDR, 'Action')
_QN_TO = ET.QName(NS_WS_ADDR, 'To')
_QN_RESOURCEURI = ET.QName(NS_WSMAN, 'ResourceURI')
_QN_BODY = ET.QName(NS_SOAP_ENV, 'Body')
_QN_MESSAGE = ET.QName(NS_WS_ADDR, 'MessageID')
_QN_REPLYTO = ET.QName(NS_WS_ADDR, 'ReplyTo')
_QN_ADDRESS = ET.QName(NS_WS_ADDR, 'Address')
_QN_SELECTORSET = ET.QName(NS_WSMAN, 'SelectorSet')
_QN_SELECTOR = ET.QName(NS_WSMAN, 'Selector')
_QN_NAME = ET.QName(NS_WSMAN, 'Name')
_QN_REFERENCEPARAMETERS = ET.QName(NS_WS_ADDR, 'ReferenceParameters')

POWER_STATES = {
    'on': 2,
    'off': 8,
    'reboot': 5
}

# Valid boot devices
BOOT_DEVICES = {
    'pxe': 'Intel(r) AMT: Force PXE Boot',
    'hd': 'Intel(r) AMT: Force Hard-drive Boot',
    'cd': 'Intel(r) AMT: Force CD/DVD Boot',
}

def friendly_power_state(state):
    for k, v in POWER_STATES.items():
        if v == int(state):
            return k

def get_request(host_uri, resource_uri):
    """ Get AMT server info

    :param host_uri: a URI to host
    :param resource_uri: a URI to an XML schema
    :returns: XML string
    """
    xml = wsman_get(host_uri, resource_uri)
    return ET.tostring(xml, encoding="UTF-8")

def power_state_request(host_uri, power_state):
    """ Change AMT Server power state

    :param host_uri: a URI to host
    :param power_state: target power state
    :returns: XML string
    """
    method = 'RequestPowerStateChange'
    selectorset = _create_selectorset('Name',
                                      'Intel(r) AMT Power Management Service')
    method_input = _generate_power_action_input(method, POWER_STATES[power_state])
    xml = wsman_invoke(host_uri, client.CIM_PowerManagementService, method,
                       selectorset, method_input)
    return ET.tostring(xml, encoding="UTF-8")

def enable_remote_kvm(uri, passwd):
    stub = """<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsman="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">
<s:Header>
<wsa:Action s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/09/transfer/Put</wsa:Action>
<wsa:To s:mustUnderstand="true">%(uri)s</wsa:To>
<wsman:ResourceURI s:mustUnderstand="true">http://intel.com/wbem/wscim/1/ips-schema/1/IPS_KVMRedirectionSettingData</wsman:ResourceURI>
<wsa:MessageID s:mustUnderstand="true">uuid:%(uuid)s</wsa:MessageID>
<wsa:ReplyTo>
    <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
</wsa:ReplyTo>
</s:Header>
<s:Body>
<g:IPS_KVMRedirectionSettingData xmlns:g="http://intel.com/wbem/wscim/1/ips-schema/1/IPS_KVMRedirectionSettingData">
<g:DefaultScreen>0</g:DefaultScreen>
<g:ElementName>Intel(r) KVM Redirection Settings</g:ElementName>
<g:EnabledByMEBx>true</g:EnabledByMEBx>
<g:InstanceID>Intel(r) KVM Redirection Settings</g:InstanceID>
<g:Is5900PortEnabled>true</g:Is5900PortEnabled>
<g:OptInPolicy>false</g:OptInPolicy>
<g:RFBPassword>%(passwd)s</g:RFBPassword>
<g:SessionTimeout>0</g:SessionTimeout>
</g:IPS_KVMRedirectionSettingData>
</s:Body>
</s:Envelope>"""  # noqa
    return stub % {'uri': uri, 'passwd': passwd, 'uuid': uuid.uuid4()}

def kvm_redirect(uri):
    stub = """<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsman="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:n1="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_KVMRedirectionSAP">
<s:Header>
<wsa:Action s:mustUnderstand="true">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_KVMRedirectionSAP/RequestStateChange</wsa:Action>
<wsa:To s:mustUnderstand="true">%(uri)s</wsa:To>
<wsman:ResourceURI s:mustUnderstand="true">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_KVMRedirectionSAP</wsman:ResourceURI>
<wsa:MessageID s:mustUnderstand="true">uuid:%(uuid)s</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
</wsa:ReplyTo>
</s:Header>
<s:Body>
<n1:RequestStateChange_INPUT>
<n1:RequestedState>2</n1:RequestedState>
</n1:RequestStateChange_INPUT>
</s:Body></s:Envelope>"""  # noqa
    return stub % {'uri': uri, 'uuid': uuid.uuid4()}

def change_boot_to_pxe_request(uri):
    return change_boot_order_request(
        uri, boot_device='pxe')

def change_boot_order_request(uri, boot_device):
    assert boot_device in BOOT_DEVICES
    stub = """<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsman="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:n1="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting">
<s:Header>
<wsa:Action s:mustUnderstand="true">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting/ChangeBootOrder</wsa:Action>
<wsa:To s:mustUnderstand="true">%(uri)s</wsa:To>
<wsman:ResourceURI s:mustUnderstand="true">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting</wsman:ResourceURI>
<wsa:MessageID s:mustUnderstand="true">uuid:%(uuid)s</wsa:MessageID>
<wsa:ReplyTo>
    <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
</wsa:ReplyTo>
<wsman:SelectorSet>
   <wsman:Selector Name="InstanceID">Intel(r) AMT: Boot Configuration 0</wsman:Selector>
</wsman:SelectorSet>
</s:Header>
<s:Body>
  <n1:ChangeBootOrder_INPUT>
     <n1:Source>
        <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
        <wsa:ReferenceParameters>
            <wsman:ResourceURI>http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootSourceSetting</wsman:ResourceURI>
            <wsman:SelectorSet>
                <wsman:Selector wsman:Name="InstanceID">%(boot_device)s</wsman:Selector>
            </wsman:SelectorSet>
         </wsa:ReferenceParameters>
     </n1:Source>
   </n1:ChangeBootOrder_INPUT>
</s:Body></s:Envelope>"""  # noqa
    return stub % {'uri': uri, 'uuid': uuid.uuid4(),
                   'boot_device': BOOT_DEVICES[boot_device]}

def enable_boot_config_request(uri):
    stub = """<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsman="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:n1="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService">
<s:Header>
<wsa:Action s:mustUnderstand="true">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService/SetBootConfigRole</wsa:Action>
<wsa:To s:mustUnderstand="true">%(uri)s</wsa:To>
<wsman:ResourceURI s:mustUnderstand="true">http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootService</wsman:ResourceURI>
<wsa:MessageID s:mustUnderstand="true">uuid:%(uuid)s</wsa:MessageID>
<wsa:ReplyTo><wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address></wsa:ReplyTo>
<wsman:SelectorSet>
    <wsman:Selector Name="Name">Intel(r) AMT Boot Service</wsman:Selector>
</wsman:SelectorSet>
</s:Header>
<s:Body>
<n1:SetBootConfigRole_INPUT>
    <n1:BootConfigSetting>
        <wsa:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
        <wsa:ReferenceParameters>
             <wsman:ResourceURI>http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_BootConfigSetting</wsman:ResourceURI>
             <wsman:SelectorSet>
                  <wsman:Selector wsman:Name="InstanceID">Intel(r) AMT: Boot Configuration 0</wsman:Selector>
             </wsman:SelectorSet>
        </wsa:ReferenceParameters>
    </n1:BootConfigSetting>
    <n1:Role>1</n1:Role>
</n1:SetBootConfigRole_INPUT>
</s:Body></s:Envelope>"""  # noqa
    return stub % {'uri': uri, 'uuid': uuid.uuid4()}

def wsman_get(host_uri, resource_uri, selectorset=None):
    """ Get target server info

    :param host_uri: a URI to host
    :param resource_uri: a URI to an XML schema
    :param selectorset: selectorset option
    :returns: XML element
    """
    request = _create_soap_request(host_uri, resource_uri,
                                   METHOD_GET, selectorset)
    return request

def wsman_invoke(host_uri, resource_uri, method,
                 selectorset=None, method_input=None):
    """ invoke method on target server

    :param host_uri: a URI to host
    :param resource_uri: a URI to an XML schema
    :param method: invoke method
    :param selectorset: selectorset option
    :param method_input: a XML element as invoke input
    :returns: XML element
    """
    action = resource_uri+'/'+method
    request = _create_soap_request(host_uri, resource_uri, action,
                                   selectorset, method_input)
    return request

def _generate_power_action_input(method, power_state):
    """ Create Power State Change Input

    :param method: Input method name
    :param power_state: target power_state
    :returns: XML element
    """
    ns = client.CIM_PowerManagementService
    el_input = _create_method_input(ns, method)
    qn_power = ET.QName(ns, 'PowerState')
    el_power = ET.SubElement(el_input, qn_power)
    el_power.text = str(power_state)
    el_selector = _create_selectorset('Name', 'ManagedSystem')
    qn_reference = ET.QName(ns, 'ManagedElement')
    el_reference = _create_reference(qn_reference, client.CIM_ComputerSystem,
                                     el_selector)
    el_input.append(el_reference)
    return el_input

def _create_method_input(ns, method):
    """ Create Input method element

    :param ns: namepace of element
    :method: Input method name
    :returns: XML element
    """
    qn_method = ET.QName(ns, method+'_INPUT')
    return ET.Element(qn_method)

def _create_soap_request(host_uri, resource_uri, method,
                         selectorset=None, method_input=None):
    """ Create a soap request using ElementTree

    :param host_uri: a URI to host
    :param resource_uri: a URI to an XML schema
    :param method: calling method
    :param selectorset: selectorset option
    :param method_input: a XML element as input
    :returns: XML element
    """

    root = ET.Element(_QN_ENVELOPE)
    header = _create_header_element(host_uri, resource_uri, method,
                                    selectorset)
    root.append(header)
    body = _create_body_element(method_input)
    root.append(body)
    return root

def _create_header_element(host_uri, resource_uri, method, selectorset):
    """ Create a Header XML element

    :param host_uri: a URI to host
    :param resource_uri: a URI to an XML schema
    :param method: calling method
    :param selectorset: selectorset option
    :returns: XML element
    """
    header = ET.Element(_QN_HEADER)
    el_action = ET.SubElement(header, _QN_ACTION)
    el_action.set(_QN_MUSTUNDERSTAND, 'true')
    el_action.text = method

    el_to = ET.SubElement(header, _QN_TO)
    el_to.text = host_uri
    el_to.set(_QN_MUSTUNDERSTAND, 'true')

    el_resourceURI = ET.SubElement(header, _QN_RESOURCEURI)
    el_resourceURI.set(_QN_MUSTUNDERSTAND, 'true')
    el_resourceURI.text = resource_uri

    el_messageID = ET.SubElement(header, _QN_MESSAGE)
    el_messageID.set(_QN_MUSTUNDERSTAND, 'true')
    el_messageID.text = 'uuid:%s' % uuid.uuid4()

    el_replyto = ET.SubElement(header, _QN_REPLYTO)
    el_address = ET.SubElement(el_replyto, _QN_ADDRESS)
    el_address.text = _ANONYMOUS

    if selectorset is not None:
        header.append(selectorset)

    return header

def _create_body_element(method_input=None):
    """ Create a Body XML element

    :param method_input: a XML element as input
    :returns: XML element
    """
    body = ET.Element(_QN_BODY)
    if method_input is not None:
        body.append(method_input)
    return body

def _create_selectorset(name, item):
    """ Create selectorset XML element

    :param name: the value of selector's 'Name' attribute
    :param item: the value of selector
    :returns: XML element
    """
    # TODO name seems related to item according AMT SDK reference,
    # need to find the relationship
    el_selectorset = ET.Element(_QN_SELECTORSET)
    el_selector = ET.SubElement(el_selectorset, _QN_SELECTOR)
    el_selector.set(_QN_NAME, name)
    el_selector.text = item
    return el_selectorset

def _create_reference(qname, uri, el_selectorset):
    """ Create a reference XML element:

    :param qname: the QName of the reference
    :param uri: the value of referenceURI
    :param el_selectorset: a selectorset XML element
    :returns: XML element
    """
    el_reference = ET.Element(qname)
    el_address = ET.SubElement(el_reference, _QN_ADDRESS)
    el_address.text = _ANONYMOUS
    el_reference_parameters = ET.SubElement(el_reference,
                                            _QN_REFERENCEPARAMETERS)
    el_resourceuri = ET.SubElement(el_reference_parameters,
                                   _QN_RESOURCEURI)
    el_resourceuri.text = uri
    el_reference_parameters.append(el_selectorset)
    return el_reference

# Local Variables:
# eval: (whitespace-mode -1)
# End:


text:
namespace soso {

///
/// Tags entity as a sun.
///
struct Sun
{
  Sun() = default;
};

} // namespace soso


text:
<!DOCTYPE html>

        <title>Vue.js 0.10 is here! — Sanskrit Notes संस्कृत टिप्पणी</title>
        <meta charset="utf-8">
        <meta name="description" content="Sanskrit Notes संस्कृत टिप्पणी - A easy modern introduction to the ancient language.">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

        <meta property="og:type" content="article">
        <meta property="og:title" content="Vue.js 0.10 is here! — Vue.js">
        <meta property="og:description" content="Sanskrit Notes संस्कृत टिप्पणी - A easy modern introduction to the ancient language.">
        <meta property="og:image" content="https://sanskritnotes.com//images/logo.png">

        <meta name="twitter:card" content="summary">
        <meta name="twitter:title" content="Vue.js 0.10 is here! — Vue.js">
        <meta name="twitter:description" content="Sanskrit Notes संस्कृत टिप्पणी - A easy modern introduction to the ancient language.">
        <meta name="twitter:image" content="https://sanskritnotes.com/images/logo.png">

        <link rel="icon" href="/images/logo.png" type="image/x-icon">

        <link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600|Roboto Mono' rel='stylesheet' type='text/css'>
        <link href='//fonts.googleapis.com/css?family=Dosis:500&text=Vue.js' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" href="/css/page.css">

    Sanskrit Notes संस्कृत टिप्पणी

  <form id="search-form">
    <input type="text" id="search-query-nav" class="search-query st-default-search-input">
  </form>

Notes

  <form id="search-form">
    <input type="text" id="search-query-nav" class="search-query st-default-search-input">
  </form>

Notes

            Recent Posts

                Announcing Vue.js 2.0

                March 2016 Update

                Common Beginner Gotchas

                Announcing vue-cli

                Why Vue.js doesn't support templateURL

                Vue.js 1.0.0 Released

                Vue.js 0.12 released!

                0.11 Component Tips

                Vue.js 0.11 released!

                Vue.js 0.10.6, and what's next

Vue.js 0.10 is here!

Mar 22, 2014

Vue.js 0.10.0 (Blade Runner) has been released! This release comes with many useful additions based on the suggestions from the users, notably interpolation in literal directives, dynamic components with the new v-view directive, array filters, and the option to configure interpolation delimiters. Internally, the codebase has received many refactoring and improvements which makes Vue.js even faster.

See the Installation page for the latest builds.

New

Literal directives can now contain interpolation tags. These tags will be evaluated only once at compile time. An example usage is conditionally decide which component to instantiate with v-component="{{type}}". Doc.

Attributes listed in the paramAttributes option now accept mustache interpolations too. They will also only be evaluated once.

v-repeat now accepts an argument which will be used as the identifier for the wrapped object. This allows more explicit property access in repeaters. Doc.

Added v-view directive which binds to a string value and dynamically instantiate different components using that string as the component ID. Doc.

Added filterBy and orderBy filters for v-repeat. Doc.

Custom filters that access properties on its this context will be considered computed filters. Doc.

You can now access the event in v-on handler expressions as $event. Example: <a v-on="click:handle('hello', $event)">Hello</a>

Interpolation delimiters can now be customized via the delimiters global config option. Example: Vue.config({ delimiters: ["[", "]"] }) will change the matched interpolation tags to [[ ]] for text bindings and [[[ ]]] for html bindings.

Changed

{{>yield}} syntax has been deprecated. A Web Components spec compatible content insertion mechanism using <content> elements has been introduced. Doc.

To use a component as a custom element, the component ID must now contain a hyphen (-). This is consistent with the current custom element spec draft.

v-repeat Arrays' augmented methods have been renamed from set to $set(index, value) and remove to $remove(index | value). The prefix better differentiates them from native methods. The replace method has been removed.

When iterating over an Object with v-repeat, the object no longer gets a $repeater array. Instead, the object is now augmented with two methods: $add(key, value) and $delete(key), which will trigger corresponding view updates.

v-if now creates and destroys a child ViewModel instance when the binding value changes, instead of simply removing/inserting the DOM node. In addition, it can no longer be used with v-repeat. Use v-show or the new built-in array filters instead.

v-with can no longer be used alone. It now must be used with either v-component or v-view. v-component can also be used as an empty directive just to create a child VM using the default Vue constructor.

Production build now strips all warnings and debug logs. To leverage debug: true, use the development version. The development version now has more detailed warning messages.

Fixed

event.stopPropagation() and event.preventDefault() inside v-on handlers now work as expected.

parent option now works properly when used in Vue.extend

Mustache bindings inside <textarea> are now properly interpolated before being set as value.

Internal

v-component, v-with and v-if have been re-written for a cleaner compile flow.

v-repeat has been re-written to use refined diff algorithm which triggers minimum DOM manipulations when the array is set to a different instance containing overlapping elements. This makes it efficient to pipe an Array through filters.

template option now directly clones native <template>'s content when available.

Overall performance improvements for both initialization and rendering.

        <link href="//cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="/css/search.css">


text:
Quantitative analysis of several changes on the Colombian constitution using natural language processing (NPL) and complex networks.

Using getPlaneText.py you can get the pure text from PDF file. After this you will be able to start some NLP using TextBlob python module.
Tabula manuel aristaran


text:
__author__ = "Daniel Perez-Gil"
__copyright__ = "Copyright 2016, OpenCB"
__license__ = "Apache License 2.0"
__version__ = "0.3.2"
__maintainer__ = "Daniel Perez-Gil"
__email__ = "opencb@googlegroups.com"
__status__ = "Development"


text:
class AddIndexesToShoppeDeliveryServices < ActiveRecord::Migration
  def change
    add_index :shoppe_delivery_services, :active
    add_index :shoppe_delivery_service_prices, :delivery_service_id
    add_index :shoppe_delivery_service_prices, :min_weight
    add_index :shoppe_delivery_service_prices, :max_weight
    add_index :shoppe_delivery_service_prices, :price
  end
end


text:
package com.consol.citrus.dsl.builder;

import com.consol.citrus.TestAction;
import com.consol.citrus.actions.SendMessageAction;
import com.consol.citrus.dsl.actions.DelegatingTestAction;
import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import com.consol.citrus.http.message.HttpMessageHeaders;
import org.springframework.http.HttpMethod;

/**
 * Special method for HTTP senders. This builder is used to set the Citrus special headers with special
 * meanings in a type safe manner.
 *
 * @author Christoph Deppisch
 * @since 2.3
 * @deprecated since 2.6 in favour of using {@link HttpActionBuilder}
 */
public class SendHttpMessageBuilder extends SendMessageBuilder<SendMessageAction, SendHttpMessageBuilder> {

    /**
     * Constructor delegating to the parent constructor
     *
     * @param action action defined by this definiton
     */
    public SendHttpMessageBuilder(SendMessageAction action) {
        super(action);
    }

    /**
     * Constructor using delegate test action.
     * @param action
     */
    public SendHttpMessageBuilder(DelegatingTestAction<TestAction> action) {
        super(action);
    }

    /**
     * Set the method of the request (GET, POST, ...)
     *
     * @param method method to set
     * @return self
     */
    public SendHttpMessageBuilder method(HttpMethod method) {
        header(HttpMessageHeaders.HTTP_REQUEST_METHOD, method.name());
        return this;
    }

    /**
     * Set the endpoint URI for the request. This works only if the HTTP endpoint used
     * doesn't provide an own endpoint URI resolver.
     *
     * @param uri absolute URI to use for the endpoint
     * @return self
     */
    public SendHttpMessageBuilder uri(String uri) {
        // Set the endpoint URL properly.
        header(DynamicEndpointUriResolver.ENDPOINT_URI_HEADER_NAME, uri);
        return this;
    }

    /**
     * Add a path to the endpoint URL. The path should start with a '/', any
     * multiple slashes on the concatenation point between endpoint URL and path are squeezed
     * to a single '/'. This works only if the HTTP endpoint used
     * doesn't provide an own endpoint URI resolver so that the default endpoint URI resolver, which
     * evaluates the message header citrus_endpoint_uri and citrus_request_path
     * for resolving the endpoint uri.
     *
     * @param path to set
     * @return self
     */
    public SendHttpMessageBuilder path(String path) {
        header(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, path);
        return this;
    }

    /**
     * Adds a query param to the request uri.
     * @param name
     * @param value
     * @return
     */
    public SendHttpMessageBuilder queryParam(String name, String value) {
        String queryParams;
        if (getMessageContentBuilder().getMessageHeaders().containsKey(DynamicEndpointUriResolver.QUERY_PARAM_HEADER_NAME)) {
            queryParams = getMessageContentBuilder().getMessageHeaders().get(DynamicEndpointUriResolver.QUERY_PARAM_HEADER_NAME).toString();
            queryParams += "," + name + "=" + value;
        } else {
            queryParams = name + "=" + value;
        }

        header(DynamicEndpointUriResolver.QUERY_PARAM_HEADER_NAME, queryParams);

        return this;
    }

    @Override
    @Deprecated
    public SendHttpMessageBuilder http() {
        return this;
    }

    @Override
    @Deprecated
    public SendSoapMessageBuilder soap() {
        throw new CitrusRuntimeException("Invalid use of http and soap action builder");
    }
}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}

{-# OPTIONS_GHC -fno-warn-orphans #-}

module Main where

import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import           Control.Applicative
import           Control.Concurrent.Async.Lifted
import           Control.Concurrent.STM
import           Control.Exception.Lifted
import           Control.Logging
import           Control.Monad hiding (forM_)
import           Control.Monad.IO.Class
import           Control.Monad.Morph
import           Control.Monad.Trans.Control
import           Control.Monad.Trans.Resource
import qualified Crypto.Hash.SHA512 as SHA512
import           Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BL
import           Data.Conduit
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.Lazy as CL
import qualified Data.Conduit.List as CL
import           Data.Conduit.Zlib as CZ
import qualified Data.HashMap.Strict as M
import           Data.List
import           Data.Monoid ((<>))
import           Data.Serialize hiding (label)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import           Network.HTTP.Conduit hiding (Response)
import           Options.Applicative as Opt
import           Prelude
import           System.Directory
import           System.FilePath
import           System.IO
import           System.IO.Temp

data Options = Options
    { verbose     :: Bool
    , rebuild     :: Bool
    , mirrorFrom  :: String
    , mirrorTo    :: String
    }

defaultOptions :: Options
defaultOptions = Options
    { verbose     = False
    , rebuild     = False
    , mirrorFrom  = ""
    , mirrorTo    = ""
    }

hackageBaseUrl :: String
hackageBaseUrl = "http://hackage.haskell.org"

options :: Opt.Parser Options
options = Options
    <$> switch (long "verbose" <> help "Display verbose output")
    <*> switch (long "rebuild" <> help "Don't mirror; used for rebuilding")
    <*> strOption (long "from" <> value hackageBaseUrl
                   <> help "Base URL to mirror from")
    <*> strOption (long "to" <> help "Base URL of server mirror to")

data Package = Package
    { packageName       :: !String
    , packageVersion    :: !String
    , packageCabal      :: !BL.ByteString
    , packageIdentifier :: !ByteString
    , packageTarEntry   :: !Tar.Entry
    }

packageFullName :: Package -> String
packageFullName Package {..} = packageName <> "-" <> packageVersion

data PathKind = UrlPath | FilePath

pathKind :: String -> PathKind
pathKind url
    | "http://" `isPrefixOf` url || "https://" `isPrefixOf` url = UrlPath
    | otherwise = FilePath

indexPackages :: (MonadThrow m, MonadBaseControl IO m, CL.MonadActive m)
              => Source m ByteString -> Source m Package
indexPackages src = do
    lbs <- lift $ CL.lazyConsume src
    sinkEntries $ Tar.read (BL.fromChunks lbs)
  where
    sinkEntries (Tar.Next ent entries)
        | Tar.NormalFile cabal _ <- Tar.entryContent ent = do
            case splitDirectories (Tar.entryPath ent) of
                [name, vers, _] ->
                    yield $ Package name vers cabal
                        (T.encodeUtf8 (T.pack (name <> vers))) ent
                ["preferred-versions"]    -> return ()
                [_, "preferred-versions"] -> return ()
                xs -> errorL' $ "Failed to parse package name: "
                           <> T.pack (Tar.entryPath ent) <> " ("
                           <> T.pack (show xs) <> ")"
            sinkEntries entries
        | otherwise = sinkEntries entries
    sinkEntries Tar.Done = return ()
    sinkEntries (Tar.Fail e) =
        monadThrow $ userError $ "Failed to read tar file: " ++ show e

downloadFromUrl :: (MonadResource m, MonadBaseControl IO m)
                => Manager -> String -> String -> Source m ByteString
downloadFromUrl mgr path file = do
    req  <- lift $ parseUrl (path </> file)
    resp <- lift $ http req mgr
    (src, _fin) <- lift $ unwrapResumable (responseBody resp)
    src

downloadFromPath :: MonadResource m => String -> String -> Source m ByteString
downloadFromPath path file = do
    let p = path </> file
    exists <- liftIO $ doesFileExist p
    when exists $ CB.sourceFile p

download :: (MonadResource m, MonadBaseControl IO m)
         => Manager
         -> String               -- ^ The server path, like /tmp/foo
         -> String               -- ^ The file's path within the server path
         -> Source m ByteString
download mgr path@(pathKind -> UrlPath) = downloadFromUrl mgr path
download _ path = downloadFromPath path

upload :: (MonadResource m, m ~ ResourceT IO)
       => Manager
       -> String
       -> String
       -> Source m ByteString
       -> m ()
upload _ path file src = do
    let p = path </> file
    liftIO $ createDirectoryIfMissing True (takeDirectory p)
    src $$ CB.sinkFile p

main :: IO ()
main = withStdoutLogging $ execParser opts >>= mirrorHackage
  where
    opts = info (helper <*> options)
                (fullDesc
                 <> progDesc "Mirror the necessary parts of Hackage"
                 <> header "simple-mirror - mirror only the minimum")

mirrorHackage :: Options -> IO ()
mirrorHackage Options {..} = withManager $ \mgr -> do
    sums <- getChecksums mgr
    putChecksums mgr "00-checksums.bak" sums
    newSums <- liftIO $ newTVarIO sums
    changed <- liftIO $ newTVarIO False
    void $ go mgr sums newSums changed `finally` do
        ch <- liftIO $ readTVarIO changed
        when ch $ do
            sums' <- liftIO $ readTVarIO newSums
            putChecksums mgr "00-checksums.dat" sums'
  where
    go mgr sums newSums changed = do
        ents <- CL.lazyConsume $
            getEntries mgr $= processEntries mgr sums newSums changed

        -- Use a temp file as a "backing store" to accumulate the new tarball.
        -- Only when it is complete and we've reached the end normally do we
        -- copy the file onto the server.  The checksum file is saved in all
        -- cases so that we know what we mirrored in this session; the index
        -- file, meanwhile, is always valid (albeit temporarily out-of-date if
        -- we abort due to an exception).
        withTemp "index" $ \temp -> do
            CB.sourceLbs (Tar.write ents)
                $= CZ.compress 7 (WindowBits 31) -- gzip compression
                $$ CB.sinkFile temp

            -- Writing the tarball is what causes the changed bit to be
            -- calculated, so we write it first to a temp file and then only
            -- upload it if necessary.
            ch <- liftIO $ readTVarIO changed
            when ch $ void $ do
                _ <- push mgr "00-index.tar.gz" $ CB.sourceFile temp
                log' "Uploaded 00-index.tar.gz"

    processEntries mgr sums newSums changed =
        CL.mapMaybeM $ \pkg@(Package {..}) -> do
            let sha = SHA512.hashlazy packageCabal
                et  = Tar.entryTime packageTarEntry
                new = case M.lookup packageIdentifier sums of
                    Nothing -> True
                    Just (et', _sha') -> et /= et' -- || sha /= sha'
            valid <- if new
                     then mirror mgr pkg sha newSums changed
                     else return True
            return $ mfilter (const valid) (Just packageTarEntry)

    mirror mgr pkg sha newSums changed = do
        let fname = packageFullName pkg
            dir   = "package" </> fname
            upath = addExtension dir ".tar.gz"
            dpath = dir </> addExtension fname ".tar.gz"
            cabal = dir </> addExtension (packageName pkg) ".cabal"
        (el, er) <-
            if rebuild
            then return (Right (), Right ())
            else do
                res <- concurrently
                    (push mgr upath $ download mgr mirrorFrom dpath)
                    (push mgr cabal $ CB.sourceLbs (packageCabal pkg))
                log' $ T.pack fname
                return res
        case (el, er) of
            (Right (), Right ()) -> liftIO $ atomically $ do
                writeTVar changed True
                modifyTVar newSums $
                    M.insert (packageIdentifier pkg)
                        (Tar.entryTime (packageTarEntry pkg), sha)
                return True
            _ -> return False

    push mgr file src = do
        eres <- try $ liftResourceT $ upload mgr mirrorTo file src
        case eres of
            Right () -> return ()
            Left e -> do
                let msg = T.pack (show (e :: SomeException))
                unless ("No tarball exists for this package version"
                        `T.isInfixOf` msg) $
                    warn' $ "FAILED " <> T.pack file <> ": " <> msg
        return eres

    getChecksums mgr = do
        sums <- download mgr mirrorTo "00-checksums.dat" $$ CB.sinkLbs
        log' $ "Downloaded checksums.dat from " <> T.pack mirrorTo
        return $ if BL.null sums
                 then M.empty
                 else case decodeLazy sums of
                     Left _    -> M.empty
                     Right res -> M.fromList res

    putChecksums mgr file sums = do
        _ <- push mgr file $ yield (encode (M.toList sums))
        log' $ "Uploaded " <> T.pack file

    getEntries mgr = do
        log' $ "Downloading index.tar.gz from " <> T.pack mirrorFrom
        indexPackages $
            download mgr mirrorFrom "00-index.tar.gz" $= CZ.ungzip

    withTemp prefix f = control $ \run ->
        withSystemTempFile prefix $ \temp h -> hClose h >> run (f temp)


text:
from luigi.contrib.s3 import S3Target

from ob_pipelines.batch import BatchTask, LoggingTaskWrapper
from ob_pipelines.config import settings
from ob_pipelines.entities.sample import Sample
from ob_pipelines.tasks.index_bam import IndexBam
from ob_pipelines.tasks.sort_bam import SortBam

class FilterSpliced(BatchTask, LoggingTaskWrapper, Sample):
    job_definition = 'filter-spliced'

    @property
    def parameters(self):
        return {
            'input': self.input()[0].path,
            'output': self.output().path
        }

    def requires(self):
        return SortBam(sample_id=self.sample_id), IndexBam(sample_id=self.sample_id)

    def output(self):
        return S3Target('{}/{}/filtered/{}.spliced_reads.bam'.format(
            settings.get_target_bucket(), self.sample_folder, self.sample_id))


text:
{% extends "base_satchmo.html" %}
{% load i18n %}

{% block navbar %}

{% trans "Home" %}

{% endblock %}

{% block content %}

{% trans "Password reset successful" %}

{% trans "We've e-mailed a new password to the e-mail address you submitted. You should receive it shortly." %}

{% endblock %}


text:
Imports LiteDB
Partial Class AddJob
    Inherits LoggedInUsersOnly

    Public Overrides Sub Page_Load(sender As Object, e As EventArgs)
        MyBase.Page_Load(sender, e)

        If Request.HttpMethod = "GET" Then
            DropDownList1.Items.Clear()
            DropDownList1.Items.Add(New ListItem("Select your organization", "-1"))
            Using db = New LiteDatabase(Server.MapPath("~/App_Data/Database.accdb"))
                Dim usrTbl = db.GetCollection(Of User)("Users")
                Dim orgTbl = db.GetCollection(Of Organization)("Organizations")
                Dim jobTbl = db.GetCollection(Of JobProposal)("Proposals")
                Dim usr = usrTbl.FindById(New BsonValue(Session("UserID")))
                Dim orgs = orgTbl.Find(Function(x) x.Approved AndAlso x.OwnerID = usr.Id).OrderBy(Function(x) x.OrganizationName)
                For Each org As Organization In orgs
                    DropDownList1.Items.Add(New ListItem(org.OrganizationName, org.Id.ToString))
                Next
            End Using
        End If

    End Sub

    Public Sub OrgSelect(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
        Using db = New LiteDatabase(Server.MapPath("~/App_Data/Database.accdb"))
            Dim orgTbl = db.GetCollection(Of Organization)("Organizations")
            Dim org = orgTbl.FindById(Integer.Parse(DropDownList1.SelectedValue))
            If org IsNot Nothing Then
                imgOrg.ImageUrl = org.ImageLoc
            End If
        End Using
    End Sub

    Public Sub Add(sender As Object, e As EventArgs) Handles btnAdd.Click
        ' TODO finish later...
        If txtGigName.Text.Length < 2 Then
            lblError.Text = "You must enter a job name"
            lblError.Visible = True
            Return
        End If
        If txtDescription.Text.Length < 2 Then
            lblError.Text = "You must enter a description"
            lblError.Visible = True
            Return
        End If
        If txtImages.Text.Length < 2 Then
            lblError.Text = "You must enter at least 1 image url"
            lblError.Visible = True
            Return
        End If
        If txtPrice.Text.Length < 2 Then
            lblError.Text = "You must enter a price"
            lblError.Visible = True
            Return
        End If
        If txtShortDescription.Text.Length < 2 Then
            lblError.Text = "You must enter a short description"
            lblError.Visible = True
            Return
        End If
        Using db = New LiteDatabase(Server.MapPath("~/App_Data/Database.accdb"))
            Dim orgId = Integer.Parse(DropDownList1.SelectedIndex)
            If orgId < 1 Then
                lblError.Text = "You must select an organization to proceed"
                lblError.Visible = True
                Return
            End If
            Dim gigTbl = db.GetCollection(Of JobProposal)("Proposals")
            Dim usrTbl = db.GetCollection(Of User)("Users")
            If Session("UserID") Is Nothing Then
                lblError.Text = "Login problem."
                lblError.Visible = True
                Return
            End If
            Dim usr = usrTbl.FindById(New BsonValue(Session("UserID")))
            Dim price As Double
            If Not Double.TryParse(txtPrice.Text, price) Then
                lblError.Text = "Price must be number-convertible"
                lblError.Visible = true
                Return
            End If
            Dim entry = New JobProposal With {
                .Description = txtDescription.Text,
                .ImageURLs = txtImages.Text.Split(New Char() {"\n", "\r"}, StringSplitOptions.RemoveEmptyEntries),
                .Offerer = usr.Id,
                .OffererOrg = orgId,
                .Price = price,
                .Title = txtGigName.Text,
                .Type = GigType.OfferJob,
                .VideoURL = txtVideoURL.Text,
                .ShortDescription = txtShortDescription.Text
            }
            gigTbl.Insert(entry)
            gigTbl.Update(entry)
            Response.Redirect("/JobPage.aspx?job=" & entry.Id)
        End Using
    End Sub

End Class


text:
@class Cytoband;
@class AlignmentResults;
@class IGVContext;
@class FeatureInterval;
@class LMResource;

@interface  BAMReader : NSObject
- (id)initWithResource:(LMResource *)resource;
- (id)initWithPath:(NSString *)path;
@property(nonatomic, retain) NSMutableArray *chromosomeNames;
@property(nonatomic, retain) NSMutableDictionary *chrLookupTable;

- (AlignmentResults *)fetchAlignmentsWithFeatureInterval:(FeatureInterval *)featureInterval error:(NSError **)error;
@end


text:
"""Support for XBee Zigbee lights."""
from __future__ import annotations

import voluptuous as vol

from homeassistant.components.light import ColorMode, LightEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType

from . import PLATFORM_SCHEMA, XBeeDigitalOut, XBeeDigitalOutConfig
from .const import CONF_ON_STATE, DEFAULT_ON_STATE, DOMAIN, STATES

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {vol.Optional(CONF_ON_STATE, default=DEFAULT_ON_STATE): vol.In(STATES)}
)

def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Create and add an entity based on the configuration."""
    zigbee_device = hass.data[DOMAIN]
    add_entities([XBeeLight(XBeeDigitalOutConfig(config), zigbee_device)])

class XBeeLight(XBeeDigitalOut, LightEntity):
    """Use XBeeDigitalOut as light."""

    _attr_color_mode = ColorMode.ONOFF
    _attr_supported_color_modes = {ColorMode.ONOFF}


text:
<?php

declare(strict_types=1);

namespace Comely\IO\DependencyInjection;

use Comely\IO\DependencyInjection\Services\Service;

/**
 * Class Services
 * @package Comely\IO\DependencyInjection
 */
class Services
{
    /** @var DependencyInjectionContainer */
    private $diContainer;
    /** @var array */
    private $services;

    /**
     * Services constructor.
     * @param DependencyInjectionContainer $diContainer
     */
    public function __construct(DependencyInjectionContainer $diContainer)
    {
        $this->diContainer = $diContainer;
        $this->services = [];
    }

    /**
     * @param string $key
     * @return bool
     */
    public function has(string $key): bool
    {
        return array_key_exists($key, $this->services);
    }

    /**
     * @param string $key
     * @return Service
     */
    public function service(string $key): Service
    {
        if ($this->has($key)) {
            return $this->services[$key];
        }

        $newService = new Service($key);
        $this->services[$key] = $newService;
        return $newService;
    }
}


text:
/* eslint-env node */
'use strict';

const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');

module.exports = function(defaults) {
  let app = new EmberAddon(defaults, {
    // Add options here
  });

  /*
    This build file specifies the options for the dummy test app of this
    addon, located in `/tests/dummy`
    This build file does *not* influence how the addon or the app using it
    behave. You most likely want to be modifying `./index.js` or app's build file
  */

  app.import('node_modules/corejs-typeahead/dist/typeahead.jquery.js');
  app.import('vendor/aupac-typeahead.css');

  app.import('node_modules/bootstrap/dist/css/bootstrap.css');
  app.import('node_modules/bootstrap/dist/css/bootstrap.css.map', {
    destDir: 'assets'
  });
  app.import('node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.eot', {
    destDir: 'fonts'
  });
  app.import('node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf', {
    destDir: 'fonts'
  });
  app.import('node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.svg', {
    destDir: 'fonts'
  });
  app.import('node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', {
    destDir: 'fonts'
  });
  app.import('node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2', {
    destDir: 'fonts'
  });

  return app.toTree();
};


text:
package util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static final SessionFactory sessionFactory;

	static {
		try {
			sessionFactory = new Configuration().configure().buildSessionFactory();
		} catch (Throwable e) {
			System.err.println("Initial SessionFactory creation failed. " + e);
			throw new ExceptionInInitializerError(e);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}


text:
package org.osgi.test.cases.dmt.tc4.rfc141;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Date;

import org.osgi.service.dmt.DmtData;
import org.osgi.service.dmt.DmtIllegalStateException;
import org.osgi.test.support.OSGiTestCase;

public class TestBug1670_NewDmtDataTypes extends OSGiTestCase{

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		System.out.println("setting up");
	}

	@Override
	protected void tearDown() throws Exception {
		super.tearDown();
		System.out.println( "tearing down");
	}

	/**
	 * tests existence of specified constants for data formats in org.osgi.service.dmt.DmtData
	 */
	public void testNewFormatConstants() throws Exception {
		checkIntConstant(DmtData.class, "FORMAT_LONG", 0x2000 );
		checkIntConstant(DmtData.class, "FORMAT_DATE_TIME", 0x4000 );
	}

	/**
	 * performs several checks with an DmtData instance of FORMAT_LONG
	 */
	public void testFormatLong() throws Exception {
		long l = 2701;
		DmtData data = new DmtData( l );
		try {
			// just testing with the new formats
			data.getDateTime();
			// ...
			fail( "must not be able to retrieve any format other than FORMAT_LONG");
		} catch (DmtIllegalStateException e) {}
		assertEquals(DmtData.FORMAT_LONG, data.getFormat() );
		long l2 = data.getLong();
		assertEquals( "initial and returned value are not the same", l, l2 );
	}

//	/**
//	 * performs following checks with an DmtData instance of FORMAT_UNSIGNED_INTEGER
//	 * - minimum and maximum value
//	 * - retrieval with getters of wrong format
//	 * - checks reported format
//	 * - compares retrieved value with initial one
//	 */
//	public void testFormatUnsignedInteger() throws Exception {
//		// test minimum limit
//		String uint = "-3";
//		DmtData data = null;
//		try {
//			data = new DmtData( uint, DmtData.FORMAT_UNSIGNED_INTEGER );
//			fail( "DmtData must not accept negative values for FORMAT_UNSIGNED_INTEGER" );
//		} catch (IllegalArgumentException e) {}
//
//		// test maximum limit
//		long max = 2l * Integer.MAX_VALUE ;
//		uint = "" + (max + 1);
//		try {
//			data = new DmtData( uint, DmtData.FORMAT_UNSIGNED_INTEGER );
//			fail( "DmtData must not accept values bigger than " + max + " for FORMAT_UNSIGNED_INTEGER" );
//		} catch (IllegalArgumentException e) {}
//
//		uint = "2701";
//		data = new DmtData( uint, DmtData.FORMAT_UNSIGNED_INTEGER );
//		try {
//			// just testing with the new formats
//			data.getLong();
//			data.getUnsignedLong();
//			data.getDateTime();
//			data.getHexBinary();
//			data.getNodeUri();
//			// ...
//			fail( "must not be able to retrieve any format other than FORMAT_UNSIGNED_INTEGER");
//		} catch (DmtIllegalStateException e) {}
//		assertEquals(DmtData.FORMAT_UNSIGNED_INTEGER, data.getFormat() );
//		String uint2 = data.getUnsignedInteger();
//		assertEquals( "initial and returned value are not the same", uint, uint2 );
//	}

//	/**
//	 * performs following checks with an DmtData instance of FORMAT_UNSIGNED_LONG
//	 * - minimum and maximum value
//	 * - retrieval with getters of wrong format
//	 * - checks reported format
//	 * - compares retrieved value with initial one
//	 */
//	public void testFormatUnsignedLong() throws Exception {
//		// test minimum limit
//		String ulong = "-3";
//		DmtData data = null;
//		try {
//			data = new DmtData( ulong, DmtData.FORMAT_UNSIGNED_LONG );
//			fail( "DmtData must not accept negative values for FORMAT_UNSIGNED_LONG" );
//		} catch (IllegalArgumentException e) {}
//
//		// test maximum limit
//		BigInteger bdMax = new BigInteger("" + Long.MAX_VALUE).multiply( new BigInteger( "2" ) );
//		BigInteger bdMaxPlus1 = bdMax.add(new BigInteger("1"));
//
//		try {
//			data = new DmtData( bdMaxPlus1.toString(), DmtData.FORMAT_UNSIGNED_LONG );
//			fail( "DmtData must not accept values bigger than " + bdMax + " for FORMAT_UNSIGNED_LONG" );
//		} catch (IllegalArgumentException e) {}
//
//		ulong = "2701";
//		data = new DmtData( ulong, DmtData.FORMAT_UNSIGNED_LONG );
//		try {
//			// just testing with the new formats
//			data.getLong();
//			data.getUnsignedInteger();
//			data.getDateTime();
//			data.getHexBinary();
//			data.getNodeUri();
//			// ...
//			fail( "must not be able to retrieve any format other than FORMAT_UNSIGNED_LONG");
//		} catch (DmtIllegalStateException e) {}
//		assertEquals(DmtData.FORMAT_UNSIGNED_LONG, data.getFormat() );
//		String ulong2 = data.getUnsignedLong();
//		assertEquals( "initial and returned value are not the same", ulong, ulong2 );
//	}

	/**
	 * performs following checks with an DmtData instance of FORMAT_DATE_TIME
	 * - wrong time format in given string
	 * - retrieval with getters of wrong format
	 * - checks reported format
	 * - compares retrieved value with initial one
	 *
	 * TODO test is against string, mst be against Date object
	 */
	public void testFormatDateTime() throws Exception {
		DmtData data = null;
		String dt = "20100101T102030";
		try {
			data = new DmtData( dt, DmtData.FORMAT_DATE_TIME );
			fail( "DmtData(String,int) must not accept FORMAT_DATE_TIME format" );
		} catch (IllegalArgumentException e) {
		}
		dt = "20100101T102030Z";
		try {
			data = new DmtData( dt, DmtData.FORMAT_DATE_TIME );
			fail( "DmtData(String,int) must not accept FORMAT_DATE_TIME format" );
		} catch (IllegalArgumentException e) {
		}

		Date dt1 = new Date();
		try {
			data = new DmtData(dt1);
		} catch (IllegalArgumentException e) {
			fail( "DmtData(Date) must not throw IllegalArgumentException" );
		}
		try {
			// just testing with the new formats
			data.getLong();
			// ...
			fail( "must not be able to retrieve any format other than FORMAT_DATE_TIME");
		} catch (DmtIllegalStateException e) {}
		assertEquals(DmtData.FORMAT_DATE_TIME, data.getFormat() );
		Date dt2 = data.getDateTime();
		assertEquals( "initial and returned value are not the same", dt1, dt2 );
	}

//	/**
//	 * performs several checks with an DmtData instance of FORMAT_HEX_BINARY
//	 */
//	public void testFormatHexBinary() throws Exception {
//		byte[] bytes = "a hexbinary test string".getBytes();
//		DmtData data = new DmtData( bytes, DmtData.FORMAT_HEX_BINARY );
//		try {
//			// just testing with the new formats
//			data.getLong();
//			data.getUnsignedInteger();
//			data.getUnsignedLong();
//			data.getDateTime();
//			data.getNodeUri();
//			// ...
//			fail( "must not be able to retrieve any format other than FORMAT_HEX_BINARY");
//		} catch (DmtIllegalStateException e) {}
//		assertEquals(DmtData.FORMAT_HEX_BINARY, data.getFormat() );
//		byte[] bytes2 = data.getHexBinary();
//		for (int i = 0; i < bytes2.length; i++) {
//			assertEquals( "initial and returned bytes are not the same", bytes[i], bytes2[i] );
//		}
//	}
//
//	/**
//	 * performs several checks with an DmtData instance of FORMAT_NODE_URI
//	 */
//	public void testFormatNodeUri() throws Exception {
//		String uri = "protocol://host:port/path/file";
//		DmtData data = new DmtData( uri, DmtData.FORMAT_NODE_URI );
//		try {
//			// just testing with the new formats
//			data.getLong();
//			data.getUnsignedInteger();
//			data.getUnsignedLong();
//			data.getDateTime();
//			data.getHexBinary();
//			// ...
//			fail( "must not be able to retrieve any format other than FORMAT_NODE_URI");
//		} catch (DmtIllegalStateException e) {}
//		assertEquals(DmtData.FORMAT_NODE_URI, data.getFormat() );
//		String uri2 = data.getNodeUri();
//		assertEquals( "initial and returned uri values are not the same", uri, uri2 );
//	}

	/**
	 * helper method to check a given class for existence and correct type, modifiers and value of a given field name
	 * @param fieldClass the class to be checked
	 * @param fieldName the name of the field
	 * @param value the expected value of the field
	 */
	private void checkIntConstant(Class< ? > fieldClass, String fieldName,
			int value) {

		try {
			Field f = fieldClass.getField(fieldName);
			assertTrue(Modifier.isPublic(f.getModifiers()));
			assertTrue(Modifier.isStatic(f.getModifiers()));
			assertTrue(Modifier.isFinal(f.getModifiers()));
			assertEquals(fieldName, value, f.getInt(null));
		}
		catch (NoSuchFieldException e) {
			fail("missing field: " + fieldName, e);
		}
		catch (IllegalAccessException e) {
			fail("bad field: " + fieldName, e);
		}
	}
}


text:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public class PointCloudGestureEditor : EditorWindow
{
    public const float GestureAreaSize = 400;
    public const float ToolbarHeight = 50;
    public const float MinSampleDistance = 5.0f;    // min distance in pixels between consecutive samples
    PointCloudGestureTemplate template;

    bool recording = false;
    List<Vector2> points;

    public static PointCloudGestureEditor Open( PointCloudGestureTemplate template )
    {
        PointCloudGestureEditor window = EditorWindow.GetWindow<PointCloudGestureEditor>( true, "Gesture Editor: " + template.name );
        window.maxSize = new Vector2( GestureAreaSize, GestureAreaSize + ToolbarHeight + 22 );
        window.minSize = window.maxSize;
        //window.wantsMouseMove = true;
        window.Init( template );
        window.Focus();

        return window;
    }

    void Init( PointCloudGestureTemplate template )
    {
        this.template = template;
        points = new List<Vector2>();
    }

    void OnGUI()
    {
        DrawGestureView();

        GUILayout.FlexibleSpace();

        DrawToolbar();

        GUILayout.Space( 50 );

        if( Event.current.type == EventType.MouseDown )
            OnMouseDown( Event.current.mousePosition );
        else if( Event.current.type == EventType.MouseDrag )
            OnMouseDrag( Event.current.mousePosition );
        else if( Event.current.type == EventType.MouseUp )
            OnMouseUp( Event.current.mousePosition );
    }

    void OnMouseDown( Vector2 pos )
    {
        recording = true;
        points.Clear();
        AddPoint( pos );
    }

    void OnMouseDrag( Vector2 pos )
    {
        if( recording )
        {
            if( points.Count > 0 )
            {
                Vector2 lastPos = points[points.Count - 1];

                if( Vector2.SqrMagnitude( pos - lastPos ) < ( MinSampleDistance * MinSampleDistance ) )
                    return;
            }

            AddPoint( pos );

            HandleUtility.Repaint();
        }
    }

    void OnMouseUp( Vector2 pos )
    {
        recording = false;
    }

    void AddPoint( Vector2 p )
    {
        points.Add( p );
    }

    void DrawTemplate()
    {
        float size = 0.95f * GestureAreaSize;
        Rect canvasRect = new Rect( 0.5f * ( GestureAreaSize - size ), 0.5f * ( GestureAreaSize - size ), size, size );

        Vector2 center = canvasRect.center;
        float scale = 0.95f * size;

        for( int i = 1; i < template.PointCount; ++i )
        {
            Vector2 p1 = template.GetPosition( i - 1 );
            Vector2 p2 = template.GetPosition( i );

            p1.y = -p1.y;
            p2.y = -p2.y;

            p1 = center + scale * p1;
            p2 = center + scale * p2;

            Handles.DrawLine( p1, p2 );
        }
    }

    void DrawNewPoints()
    {
        if( points.Count > 1 )
        {
            Handles.color = Color.yellow;

            for( int i = 1; i < points.Count; ++i )
            {
                Vector2 p1 = points[i - 1];
                Vector2 p2 = points[i];

                Handles.CircleCap( 0, p1, Quaternion.identity, 2.0f );
                Handles.DrawLine( p1, p2 );
            }
        }
    }

    void DrawGestureView()
    {
        GUILayoutUtility.GetRect( GestureAreaSize, GestureAreaSize, GestureAreaSize, GestureAreaSize );

        Handles.color = Color.white;
        DrawTemplate();

        Handles.color = Color.yellow;
        DrawNewPoints();
    }

    void DrawToolbar()
    {
        GUILayout.BeginHorizontal( GUILayout.Height( ToolbarHeight ) );
        GUILayout.Space( 5 );

        GUI.enabled = points.Count > 1;

        if( ToolbarButton( "Clear" ) )
            Clear();

        if( ToolbarButton( "Apply" ) )
            Apply();

        GUI.enabled = true;

        GUILayout.Space( 5 );
        GUILayout.EndHorizontal();
    }

    void Clear()
    {
        points.Clear();
    }

    void Apply()
    {
        template.BeginPoints();

        for( int i = 0; i < points.Count; ++i )
        {
            Vector2 p = points[i];
            p.y = -p.y; // must flip
            template.AddPoint( 0, p );
        }

        template.EndPoints();

        Clear();
    }

    public bool ToolbarButton( string text )
    {
        return GUILayout.Button( text, GUILayout.ExpandHeight( true ) );
    }
}