text:
package de.uni_potsdam.hpi.bpt.bp2014.conversion.converter.pcm;

import de.uni_potsdam.hpi.bpt.bp2014.conversion.IConverter;
import de.uni_potsdam.hpi.bpt.bp2014.conversion.IEdge;
import de.uni_potsdam.hpi.bpt.bp2014.conversion.activity_centric.ActivityCentricProcessModel;
import de.uni_potsdam.hpi.bpt.bp2014.conversion.activity_centric.scenario.Scenario;
import de.uni_potsdam.hpi.bpt.bp2014.conversion.converter.activity_centric.ActivityCentricToSynchronizedOLC;
import de.uni_potsdam.hpi.bpt.bp2014.conversion.olc.DataObjectState;
import de.uni_potsdam.hpi.bpt.bp2014.conversion.olc.ObjectLifeCycle;
import de.uni_potsdam.hpi.bpt.bp2014.conversion.olc.StateTransition;
import de.uni_potsdam.hpi.bpt.bp2014.conversion.olc.synchronize.SynchronizedObjectLifeCycle;

import java.util.*;

/**
 * This class is a converter, which generates a {@link SynchronizedObjectLifeCycle}
 * based on a PCM Scenario. A PCM scenario is an aggregation of {@link ActivityCentricProcessModel}.
 * Hence a List of those models - called fragments - must be provided.
 */
public class ScenarioToSynchronizedOLC implements IConverter<Scenario, SynchronizedObjectLifeCycle> {

    /**
     * The list of fragments representing the Production Case Management Scenario.
     */
    private Collection<ActivityCentricProcessModel> fragments;
    /**
     * A map which maps the Data Object names to a Collection of Object Life cycles.
     * There will be at least one ObjectLifeCycles and not more thant #{@link #fragments}
     */
    private Map<String, Collection<ObjectLifeCycle>> olcsPerDataClass;
    /**
     * A Collection holding the final Object Life Cycles which will be needed in order to
     * build the synchronized object life cycle.
     */
    private Collection<ObjectLifeCycle> olcs;

    /**
     * This method generates an {@link SynchronizedObjectLifeCycle} based on a a Collection
     * of {@link ActivityCentricProcessModel}.
     * First of all the Collections {@link #fragments}, {@link #olcsPerDataClass} and
     * {@link #olcs} will be initialized.
     * Afterward we will generate Object Life Cycles for each Activity Centric Process Model.
     * Before creating an Object Life Cycle we will integrate the created OLCs.
     *
     * @param fragments The list of fragments representing the PCM Scenario.
     * @return The generated Synchronized Object Life Cycle.
     */
    public SynchronizedObjectLifeCycle convert(Collection<ActivityCentricProcessModel> fragments) {
        this.fragments = fragments;
        olcsPerDataClass = new HashMap<>();
        olcs = new HashSet<>();

        generateObjectLifeCycles();
        integrateStates();

        SynchronizedObjectLifeCycle sOLC = new SynchronizedObjectLifeCycle();
        sOLC.setObjectLifeCycles(new ArrayList<>(olcs));
        return sOLC;
    }

    /**
     * This method generates the Object Life Cycles.
     * it will create object life cycles for each data object in each fragment.
     * Therefore it used the Converter {@link ActivityCentricToSynchronizedOLC}
     * and extracts the object life cycles from the {@link SynchronizedObjectLifeCycle}.
     * They will be saved inside {@link #olcsPerDataClass}.
     */
    private void generateObjectLifeCycles() {
        for (ActivityCentricProcessModel fragment : fragments) {
            ActivityCentricToSynchronizedOLC acpm2solc = new ActivityCentricToSynchronizedOLC();
            SynchronizedObjectLifeCycle solc = (SynchronizedObjectLifeCycle) acpm2solc.convert(fragment);
            for (ObjectLifeCycle objectLifeCycle : solc.getOLCs()) {
                if (!olcsPerDataClass.containsKey(objectLifeCycle.getLabel())) {
                    olcsPerDataClass.put(objectLifeCycle.getLabel(), new HashSet<ObjectLifeCycle>());
                }
                olcsPerDataClass.get(objectLifeCycle.getLabel()).add(objectLifeCycle);
            }
        }
    }
    /**
     * This method takes the Object life cycles inside {@link #olcsPerDataClass}
     * and creates one olc per data class.
     * We assume that the start state will be called init.
     * As well as that the final states will have no outgoing edges.
     */
    private void integrateStates() {
        for (Map.Entry<String, Collection<ObjectLifeCycle>> olcsAndName : olcsPerDataClass.entrySet()) {
            Map<DataObjectState, Collection<StateTransition>> successors = new HashMap<>();
            Map<String, DataObjectState> states = new HashMap<>();
            initializeSuccessorsAndStates(olcsAndName, successors, states);
            ObjectLifeCycle olc = new ObjectLifeCycle(olcsAndName.getKey());
            for (DataObjectState dataObjectState : states.values()) {
                olc.addNode(dataObjectState);
                if (dataObjectState.getName().equals("init")) {
                    olc.setStartNode(dataObjectState);
                }
                if (dataObjectState.getOutgoingEdges().isEmpty()) {
                    olc.addFinalNode(dataObjectState);
                }
            }
            olcs.add(olc);
        }
    }

    /**
     * This method initializes the successors and states.
     * Therefore it iterates of every Object Life Cycle.
     * For each transition the source and target will be determined, and if no such state
     * has been added before it will be added to the states.
     * In addition the target will be added to the list of successors for the source.
     * @param olcsAndName A MapEntry holding all Object Life Cycles for one name name.
     * @param successors A Map holding all DataStates and a Collection of their successors. (Will save the result)
     * @param states A Map for all States (will save the result)
     */
    private void initializeSuccessorsAndStates(Map.Entry<String, Collection<ObjectLifeCycle>> olcsAndName, Map<DataObjectState,
            Collection<StateTransition>> successors,
            Map<String, DataObjectState> states) {
        for (ObjectLifeCycle olc : olcsAndName.getValue()) {
            for (IEdge transition : olc.getEdgeOfType(StateTransition.class)) {
                if (!((DataObjectState)transition.getSource()).getName().equals("i")) {
                    String sourceName = ((DataObjectState) transition.getSource()).getName();
                    String targetName = ((DataObjectState) transition.getTarget()).getName();
                    if (!states.containsKey(sourceName)) {
                        states.put(sourceName, new DataObjectState(sourceName));
                    }
                    if (!states.containsKey(targetName)) {
                        states.put(targetName, new DataObjectState(targetName));
                    }
                    if (!successors.containsKey(states.get(sourceName))) {
                        successors.put(states.get(sourceName), new HashSet<StateTransition>());
                    }
                    if (!successorExists(successors.get(states.get(sourceName)), (StateTransition) transition)) {
                        StateTransition newTransition = new StateTransition(
                                states.get(sourceName),
                                states.get(targetName),
                                ((StateTransition) transition).getLabel());
                        successors.get(states.get(sourceName)).add(newTransition);
                        states.get(sourceName).addOutgoingEdge(newTransition);
                        states.get(targetName).addIncomingEdge(newTransition);
                    }
                }
            }
        }
    }

    /**
     * Checks weather or not a transition already exists. A transition exists if and only if
     * all the following conditions are true:
     * - The source and target names are the same
     * - The state transition label is the same.
     * @param stateTransitions A Collection of all existing transitions.
     * @param transition The transition to be checked.
     * @return Returns true if the transition exists else it will return false.
     */
    private boolean successorExists(Collection<StateTransition> stateTransitions, StateTransition transition) {
        for (StateTransition stateTransition : stateTransitions) {
            if (((DataObjectState)stateTransition.getSource()).getName().equals(
                    ((DataObjectState)transition.getSource()).getName()) &&
                    ((DataObjectState)stateTransition.getTarget()).getName().equals(
                            ((DataObjectState)transition.getTarget()).getName()) &&
                    stateTransition.getLabel().equals(transition.getLabel())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public SynchronizedObjectLifeCycle convert(Scenario model) {
        return convert(model.getFragments());
    }
}


text:
@interface ServiceManaagerTopTypeListViewController ()

@end

@implementation ServiceManaagerTopTypeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [title setText:@"服务管理(设置大类)"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self requestData:YES];
}

- (void)addBtnClicked
{
    [self.navigationController pushViewController:[[NSClassFromString(@"ServiceManaagerTopTypeAddViewController") alloc]init] animated:YES];

}

- (void)requestData:(BOOL)isRefresh
{
    [HTTP_MANAGER getAllServiceTopTypeList:^(NSDictionary *succeedResult) {
        if([succeedResult[@"code"]integerValue] == 1)
        {
            self.m_arrData = succeedResult[@"ret"];
        }
        [self reloadDeals];

    } failedBolck:^(AFHTTPRequestOperation *response, NSError *error) {
        [self reloadDeals];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *info = [self.m_arrData objectAtIndex:indexPath.row];
    ServiceManaagerSubTypeAddViewController *sub = [[ServiceManaagerSubTypeAddViewController alloc]initWith:info];
    [self.navigationController pushViewController:sub animated:YES];
}

@end

redpajama_set_name: RedPajamaGithub


text:
@interface HBDrawPoint : NSObject

+ (instancetype)drawPoint:(CGPoint)point;

@property (nonatomic, strong) NSNumber * x;

@property (nonatomic, strong) NSNumber * y;

@end


text:
from __future__ import unicode_literals, print_function, absolute_import

try:
    from urllib.parse import urlsplit
except ImportError:
    from urlparse import urlsplit
from datetime import timedelta

from django.conf import settings as django_settings
from django.test import Client
from django.test import TestCase
from django.contrib.auth.models import User, update_last_login
from django.contrib.auth.signals import user_logged_in
from django.test.utils import override_settings as override_settings_orig
from django.core.urlresolvers import reverse
from django.core.exceptions import ImproperlyConfigured
from django.contrib.messages.storage.cookie import CookieStorage
from django.utils.six import text_type
from django.utils import timezone

from loginas import settings as la_settings

try:
    import imp
    reload = imp.reload  # @ReservedAssignment
except ImportError:
    pass

class override_settings(override_settings_orig):
    """
    Reload application settings module every time we redefine a setting
    """

    def enable(self):
        super(override_settings, self).enable()
        from loginas import settings as loginas_settings
        reload(loginas_settings)

    def disable(self):
        super(override_settings, self).disable()
        from loginas import settings as loginas_settings
        reload(loginas_settings)

def create_user(username='', password='', **kwargs):
    user = User(username=username, **kwargs)
    if password:
        user.set_password(password)
    user.save()
    return user

def login_as_nonstaff(request, user):
    return request.user.is_superuser or (request.user.is_staff and
                                         not user.is_staff)

class ViewTest(TestCase):

    """Tests for user_login view"""

    def setUp(self):
        self.client = Client(enforce_csrf_checks=True)
        self.client.get('/')  # To get the CSRF token for next request
        assert django_settings.CSRF_COOKIE_NAME in self.client.cookies
        self.target_user = User.objects.create(username='target')
        # setup listener
        user_logged_in.connect(update_last_login)

    def tearDown(self):
        """Disconnect the listeners"""
        user_logged_in.disconnect(update_last_login)

    def get_csrf_token_payload(self):
        return {
            'csrfmiddlewaretoken':
                self.client.cookies[django_settings.CSRF_COOKIE_NAME].value
        }

    def get_target_url(self, target_user=None):
        if target_user is None:
            target_user = self.target_user
        response = self.client.post(
            reverse("loginas-user-login", kwargs={'user_id': target_user.id}),
            data=self.get_csrf_token_payload()
        )
        self.assertEqual(response.status_code, 302)
        return response

    def assertCurrentUserIs(self, user):
        id_ = text_type(user.id if user is not None else None).encode('utf-8')
        r = self.client.post(
            reverse("current_user"),
            data=self.get_csrf_token_payload()
        )
        self.assertEqual(r.content, id_)

    def assertLoginError(self, resp):
        self.assertEqual(urlsplit(resp['Location'])[2], "/")

        messages = CookieStorage(resp)._decode(resp.cookies['messages'].value)
        self.assertIn(
            (40, "You do not have permission to do that."),
            [(m.level, m.message) for m in messages]
        )

    def assertLoginSuccess(self, resp, user):
        self.assertEqual(urlsplit(resp['Location'])[2],
                         django_settings.LOGIN_REDIRECT_URL)
        msg = la_settings.MESSAGE_LOGIN_SWITCH.format(username=user.username)
        messages = CookieStorage(resp)._decode(resp.cookies['messages'].value)
        self.assertIn(msg, "".join([m.message for m in messages]))

    def assertRaisesExact(self, exception, func, *args, **kwargs):
        try:
            func(*args, **kwargs)
            self.assertFail("{0} not raised".format(exception))
        except exception.__class__ as caught:
            self.assertEqual(caught.args, exception.args)

    def clear_session_cookie(self):
        del self.client.cookies[django_settings.SESSION_COOKIE_NAME]

    @override_settings(CAN_LOGIN_AS=login_as_nonstaff)
    def test_custom_permissions(self):
        user = create_user(u"üser", "pass", is_superuser=False, is_staff=False)
        staff1 = create_user("stäff", "pass", is_superuser=False, is_staff=True)
        staff2 = create_user("super", "pass", is_superuser=True, is_staff=True)

        # Regular user can't login as anyone
        self.assertTrue(self.client.login(username=u"üser", password="pass"))
        self.assertLoginError(self.get_target_url())
        self.assertCurrentUserIs(user)
        self.clear_session_cookie()

        # Non-superuser staff user can login as regular user
        self.assertTrue(self.client.login(username="stäff", password="pass"))
        response = self.get_target_url(user)
        self.assertLoginSuccess(response, user)
        self.assertCurrentUserIs(user)
        self.clear_session_cookie()

        # Non-superuser staff user cannot login as other staff
        self.assertTrue(self.client.login(username="stäff", password="pass"))
        self.assertLoginError(self.get_target_url(staff2))
        self.assertCurrentUserIs(staff1)
        self.clear_session_cookie()

        # Superuser staff user can login as other staff
        self.assertTrue(self.client.login(username="super", password="pass"))
        response = self.get_target_url(staff1)
        self.assertLoginSuccess(response, staff1)
        self.assertCurrentUserIs(staff1)

    @override_settings(CAN_LOGIN_AS='loginas.tests.login_as_shorter_username')
    def test_custom_permissions_as_string(self):
        ray = create_user("ray", "pass")
        lonnie = create_user("lonnie", "pass")

        # Ray cannot login as Lonnie
        self.assertTrue(self.client.login(username="ray", password="pass"))
        self.assertLoginError(self.get_target_url(lonnie))
        self.assertCurrentUserIs(ray)
        self.clear_session_cookie()

        # Lonnie can login as Ray
        self.assertTrue(self.client.login(username="lonnie", password="pass"))
        response = self.get_target_url(ray)
        self.assertLoginSuccess(response, ray)
        self.assertCurrentUserIs(ray)

    def test_custom_permissions_invalid_path(self):
        def assertMessage(message):
            self.assertRaisesExact(
                ImproperlyConfigured(message),
                self.get_target_url
            )
        with override_settings(CAN_LOGIN_AS='loginas.tests.invalid_func'):
            assertMessage(
                "Module loginas.tests does not define a invalid_func function.")
        with override_settings(CAN_LOGIN_AS='loginas.tests.invalid_path.func'):
            assertMessage("Error importing CAN_LOGIN_AS function: loginas.tests.invalid_path")

    def test_as_superuser(self):
        create_user("me", "pass", is_superuser=True, is_staff=True)
        self.assertTrue(self.client.login(username="me", password="pass"))
        response = self.get_target_url()
        self.assertLoginSuccess(response, self.target_user)
        self.assertCurrentUserIs(self.target_user)

    def test_as_non_superuser(self):
        user = create_user("me", "pass", is_staff=True)
        self.assertTrue(self.client.login(username="me", password="pass"))
        self.assertLoginError(self.get_target_url())
        self.assertCurrentUserIs(user)

    def test_as_anonymous_user(self):
        self.assertLoginError(self.get_target_url())
        self.assertCurrentUserIs(None)

    def test_get_405_method_not_allowed(self):
        url = reverse("loginas-user-login", kwargs={'user_id': '0'})
        r = self.client.get(url)
        self.assertEqual(r.status_code, 405)

    def test_missing_csrf_token_403_forbidden(self):
        url = reverse("loginas-user-login", kwargs={'user_id': '0'})
        r = self.client.post(url)
        self.assertEqual(r.status_code, 403)

    @override_settings(LOGINAS_REDIRECT_URL="/another-redirect")
    def test_loginas_redirect_url(self):
        create_user("me", "pass", is_superuser=True, is_staff=True)
        self.assertTrue(self.client.login(username="me", password="pass"))

        response = self.client.post(
            reverse("loginas-user-login", kwargs={'user_id': self.target_user.id}),
            data=self.get_csrf_token_payload()
        )
        self.assertEqual(response.status_code, 302)
        self.assertEqual(urlsplit(response['Location'])[2], "/another-redirect")

    def test_restore_original_user(self):

        # Create a super user and login as this
        original_user = create_user("me", "pass", is_superuser=True, is_staff=True)
        self.assertTrue(self.client.login(username="me", password="pass"))
        response = self.get_target_url()
        self.assertLoginSuccess(response, self.target_user)

        url = reverse("loginas-user-login", kwargs={'user_id': self.target_user.id})
        self.client.get(url)
        self.assertCurrentUserIs(self.target_user)

        # Restore
        url = reverse("loginas-logout")
        self.client.get(url)
        self.assertCurrentUserIs(original_user)

    @override_settings(LOGINAS_LOGOUT_REDIRECT_URL="/another-redirect")
    def test_loginas_redirect_url(self):
        create_user("me", "pass", is_superuser=True, is_staff=True)
        self.assertTrue(self.client.login(username="me", password="pass"))
        response = self.client.get(reverse("loginas-logout"))
        self.assertEqual(response.status_code, 302)
        self.assertEqual(urlsplit(response['Location'])[2], "/another-redirect")

    def test_last_login_not_updated(self):
        last_login = timezone.now() - timedelta(hours=1)
        self.target_user.last_login = last_login
        self.target_user.save()
        create_user("me", "pass", is_superuser=True, is_staff=True)
        self.assertTrue(self.client.login(username="me", password="pass"))
        response = self.get_target_url()
        self.assertLoginSuccess(response, self.target_user)
        self.assertCurrentUserIs(self.target_user)
        target_user = User.objects.get(id=self.target_user.id)  # refresh from db
        self.assertEqual(target_user.last_login, last_login)

    @override_settings(LOGINAS_UPDATE_LAST_LOGIN=True)
    def test_last_login_updated(self):
        last_login = timezone.now() - timedelta(hours=1)
        self.target_user.last_login = last_login
        self.target_user.save()
        create_user("me", "pass", is_superuser=True, is_staff=True)
        self.assertTrue(self.client.login(username="me", password="pass"))
        response = self.get_target_url()
        self.assertLoginSuccess(response, self.target_user)
        self.assertCurrentUserIs(self.target_user)
        target_user = User.objects.get(id=self.target_user.id)  # refresh from db
        self.assertGreater(target_user.last_login, last_login)


text:
// Copyright 2011-2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.security.zynamics.zylib.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.JCheckBox;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.border.LineBorder;

/**
 * List class that can be used to have lists with checkable entries.
 *
 * Note: Does not (yet) work with lists the grow or shrink.
 */
public class JCheckedListbox<T> extends JList<T> {
  /**
   * Keeps track of what list items are m_selected.
   */
  private final boolean[] m_selected;

  private boolean m_selectCompleteLine = true;

  public JCheckedListbox(final ListModel<T> model) {
    super(model);

    m_selected = new boolean[model.getSize()];

    setCellRenderer(new CheckedListboxRenderer<T>());

    addMouseListener(new InternalListener());
  }

  public JCheckedListbox(final T[] listData) {
    super(listData);

    m_selected = new boolean[listData.length];

    setCellRenderer(new CheckedListboxRenderer<T>());

    addMouseListener(new InternalListener());
  }

  public JCheckedListbox(final Vector<T> listData) {
    super(listData);

    m_selected = new boolean[listData.size()];

    setCellRenderer(new CheckedListboxRenderer<T>());

    addMouseListener(new InternalListener());
  }

  public JCheckedListbox(final Vector<T> listData, final boolean selectCompleteLine) {
    super(listData);

    this.m_selectCompleteLine = selectCompleteLine;

    m_selected = new boolean[listData.size()];

    setCellRenderer(new CheckedListboxRenderer<T>());

    addMouseListener(new InternalListener());
  }

  public boolean isChecked(final int index) {
    return m_selected[index];
  }

  public void setChecked(final int index, final boolean isSelected) {
    m_selected[index] = isSelected;

    updateUI();

    fireSelectionValueChanged(index, index, false);
  }

  @Override
  public void updateUI() {
    super.updateUI();
  }

  private class CheckedListboxRenderer<T> extends JPanel implements ListCellRenderer<T> {
    private static final long serialVersionUID = 7446207257969469739L;

    private final JCheckBox checkBox = new JCheckBox();

    private final LineBorder SELECTED_BORDER = new LineBorder(Color.DARK_GRAY);
    private final LineBorder UNSELECTED_BORDER = new LineBorder(Color.WHITE);

    private final Color SELECTED_COLOR = new Color(0xbdcfe7);
    private final Color UNSELECTED_COLOR = Color.WHITE;

    public CheckedListboxRenderer() {
      super(new BorderLayout());
      setBorder(UNSELECTED_BORDER);
      setBackground(UNSELECTED_COLOR);
      checkBox.setBackground(UNSELECTED_COLOR);
    }

    @Override
    public Component getListCellRendererComponent(final JList<? extends T> list, final T value,
        final int index, final boolean iss, final boolean chf) {
      checkBox.setEnabled(JCheckedListbox.this.isEnabled());

      if (m_selectCompleteLine) {
        setBorder(iss ? SELECTED_BORDER : UNSELECTED_BORDER);
        setBackground(iss ? SELECTED_COLOR : UNSELECTED_COLOR);
        checkBox.setBackground(iss ? SELECTED_COLOR : UNSELECTED_COLOR);
      }

      checkBox.setText(value.toString());
      checkBox.setSelected(m_selected[index]);

      checkBox.updateUI();

      add(checkBox, BorderLayout.WEST);

      return this;
    }
  }

  private class InternalListener extends MouseAdapter {
    @Override
    public void mouseClicked(final MouseEvent event) {
      if (!isEnabled()) {
        return;
      }

      // TODO: Somehow find a better way to check
      // whether the checkbox was hit.
      if (event.getPoint().x > 20) {
        return;
      }

      final int row = JCheckedListbox.this.locationToIndex(event.getPoint());

      m_selected[row] = !m_selected[row];

      updateUI();

      fireSelectionValueChanged(row, row, false);
    }
  }
}


text:
package focus.criteria;

import java.util.*;

public class Functions {

    @SafeVarargs
    public static <D> Set<D> setOf(D... values) {
        switch (values.length) {
            case 0:
                return Collections.emptySet();
            case 1:
                return Collections.singleton(values[0]);
            default:
                return Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(values)));
        }
    }

    public static Set<String> splitToSet(String value, String splitter) {
        return setOf(value.split(splitter));
    }

}


text:
import logging
from collections import Mapping
from itertools import chain
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.security import (
    Allow,
    Everyone,
)
from pyramid.traversal import resource_path
from .calculated import (
    calculate_properties,
    calculated_property,
)
from .interfaces import (
    COLLECTIONS,
    CONNECTION,
    ROOT,
    TYPES,
    UPGRADER,
)
from .validation import ValidationFailure
from .util import (
    ensurelist,
    quick_deepcopy,
    simple_path_ids,
)

logger = logging.getLogger(__name__)

def includeme(config):
    config.scan(__name__)

class Resource(object):

    @calculated_property(name='@id', schema={
        "title": "ID",
        "type": "string",
    })
    def jsonld_id(self, request):
        return request.resource_path(self)

    @calculated_property(name='@context', category='page')
    def jsonld_context(self, request):
        return request.route_path('jsonld_context')

    @calculated_property(category='page')
    def actions(self, request):
        actions = calculate_properties(self, request, category='action')
        if actions:
            return list(actions.values())

class Root(Resource):
    __name__ = ''
    __parent__ = None
    __acl__ = [
        (Allow, 'remoteuser.INDEXER', ['view', 'list', 'index']),
        (Allow, 'remoteuser.EMBED', ['view', 'expand', 'audit']),
        (Allow, Everyone, ['visible_for_edit']),
    ]

    def __init__(self, registry):
        self.registry = registry

    @reify
    def connection(self):
        return self.registry[CONNECTION]

    @reify
    def collections(self):
        return self.registry[COLLECTIONS]

    def __getitem__(self, name):
        try:
            resource = self.get(name)
        except KeyError:
            # Just in case we get an unexpected KeyError
            # FIXME: exception logging.
            raise HTTPInternalServerError('Traversal raised KeyError')
        if resource is None:
            raise KeyError(name)
        return resource

    def __contains__(self, name):
        return self.get(name, None) is not None

    def get(self, name, default=None):
        resource = self.collections.get(name, None)
        if resource is not None:
            return resource
        resource = self.connection.get_by_uuid(name, None)
        if resource is not None:
            return resource
        return default

    def __json__(self, request=None):
        return self.properties.copy()

    @calculated_property(name='@type', schema={
        "title": "Type",
        "type": "array",
        "items": {
            "type": "string",
        },
    })
    def jsonld_type(self):
        return ['Portal']

class AbstractCollection(Resource, Mapping):
    properties = {}
    unique_key = None

    def __init__(self, registry, name, type_info, properties=None, acl=None, unique_key=None):
        self.registry = registry
        self.__name__ = name
        self.type_info = type_info
        if properties is not None:
            self.properties = properties
        if acl is not None:
            self.__acl__ = acl
        if unique_key is not None:
            self.unique_key = unique_key

    @reify
    def connection(self):
        return self.registry[CONNECTION]

    @reify
    def __parent__(self):
        return self.registry[ROOT]

    def __getitem__(self, name):
        try:
            item = self.get(name)
        except KeyError:
            # Just in case we get an unexpected KeyError
            # FIXME: exception logging.
            raise HTTPInternalServerError('Traversal raised KeyError')
        if item is None:
            raise KeyError(name)
        return item

    def __iter__(self):
        for uuid in self.connection.__iter__(*self.type_info.subtypes):
            yield uuid

    def __len__(self):
        return self.connection.__len__(*self.type_info.subtypes)

    def __hash__(self):
        return object.__hash__(self)

    def __eq__(self, other):
        return self is other

    def _allow_contained(self, resource):
        return resource.__parent__ is self or \
            resource.type_info.name in resource.type_info.subtypes

    def get(self, name, default=None):
        resource = self.connection.get_by_uuid(name, None)
        if resource is not None:
            if not self._allow_contained(resource):
                return default
            return resource
        if self.unique_key is not None:
            # Give the storage a hint of which index to search.
            # If this is a collection of an abstract type,
            # the item_type will be None and we'll search all snovault indices.
            index = getattr(self.type_info, 'item_type', None)
            resource = self.connection.get_by_unique_key(
                self.unique_key, name, index=index)
            if resource is not None:
                if not self._allow_contained(resource):
                    return default
                return resource
        return default

    def __json__(self, request):
        return self.properties.copy()

    @calculated_property(name='@type', schema={
        "title": "Type",
        "type": "array",
        "items": {
            "type": "string",
        },
    })
    def jsonld_type(self):
        return [
            '{type_name}Collection'.format(type_name=self.type_info.name),
            'Collection',
        ]

class Collection(AbstractCollection):
    ''' Separate class so add views do not apply to AbstractCollection '''

class Item(Resource):
    item_type = None
    base_types = ['Item']
    name_key = None
    rev = {}
    embedded = ()
    embedded_with_frame = ()
    audit_inherit = []
    schema = None
    AbstractCollection = AbstractCollection
    Collection = Collection

    def __init__(self, registry, model):
        self.registry = registry
        self.model = model

    def __repr__(self):
        return '<%s at %s>' % (type(self).__name__, resource_path(self))

    @reify
    def type_info(self):
        return self.registry[TYPES][type(self)]

    @reify
    def collection(self):
        collections = self.registry[COLLECTIONS]
        return collections[self.type_info.name]

    @property
    def __parent__(self):
        return self.collection

    @property
    def __name__(self):
        if self.name_key is None:
            return str(self.uuid)
        return self.properties.get(self.name_key, None) or str(self.uuid)

    @property
    def properties(self):
        return self.model.properties

    @property
    def propsheets(self):
        return self.model.propsheets

    @property
    def uuid(self):
        return self.model.uuid

    @property
    def tid(self):
        return self.model.tid

    @classmethod
    def embedded_paths(cls):
        return list(
            chain(
                cls.embedded,
                (
                    p.path
                    for p in cls.embedded_with_frame
                )
            )
        )

    def links(self, properties):
        return {
            path: set(simple_path_ids(properties, path))
            for path in self.type_info.schema_links
        }

    def get_rev_links(self, name):
        types = self.registry[TYPES]
        type_name, rel = self.rev[name]
        types = types[type_name].subtypes
        return self.registry[CONNECTION].get_rev_links(self.model, rel, *types)

    def unique_keys(self, properties):
        return {
            name: [v for prop in props for v in ensurelist(properties.get(prop, ()))]
            for name, props in self.type_info.schema_keys.items()
        }

    def upgrade_properties(self):
        properties = quick_deepcopy(self.properties)
        current_version = properties.get('schema_version', '')
        target_version = self.type_info.schema_version
        if target_version is not None and current_version != target_version:
            upgrader = self.registry[UPGRADER]
            try:
                properties = upgrader.upgrade(
                    self.type_info.name, properties, current_version, target_version,
                    context=self, registry=self.registry)
            except RuntimeError:
                raise
            except Exception:
                logger.warning(
                    'Unable to upgrade %s from %r to %r',
                    resource_path(self.__parent__, self.uuid),
                    current_version, target_version, exc_info=True)
        return properties

    def __json__(self, request):
        # Record embedding objects
        request._embedded_uuids.add(str(self.uuid))
        return self.upgrade_properties()

    def __resource_url__(self, request, info):
        # Record linking objects
        request._linked_uuids.add(str(self.uuid))
        return None

    @classmethod
    def create(cls, registry, uuid, properties, sheets=None):
        model = registry[CONNECTION].create(cls.__name__, uuid)
        self = cls(registry, model)
        self._update(properties, sheets)
        return self

    def update(self, properties, sheets=None):
        self._update(properties, sheets)

    def _update(self, properties, sheets=None):
        unique_keys = None
        links = None
        if properties is not None:
            if 'uuid' in properties:
                properties = properties.copy()
                del properties['uuid']

            unique_keys = self.unique_keys(properties)
            for k, values in unique_keys.items():
                if len(set(values)) != len(values):
                    msg = "Duplicate keys for %r: %r" % (k, values)
                    raise ValidationFailure('body', [], msg)

            links = self.links(properties)

        connection = self.registry[CONNECTION]
        connection.update(self.model, properties, sheets, unique_keys, links)

    @calculated_property(name='@type', schema={
        "title": "Type",
        "type": "array",
        "items": {
            "type": "string",
        },
    })
    def jsonld_type(self):
        return [self.type_info.name] + self.base_types

    @calculated_property(name='uuid')
    def prop_uuid(self):
        return str(self.uuid)


text:
#include <unordered_set>

#include <boost/variant.hpp>
#include <gtest/gtest.h>

#include <osquery/sql/sqlite_util.h>

namespace osquery {

class IntMinMaxCheck final {
 public:
  explicit IntMinMaxCheck(int64_t min, int64_t max) : min_(min), max_(max){};
  bool operator()(const std::string& string) const;

 private:
  const int64_t min_;
  const int64_t max_;
};

class SpecificValuesCheck final {
 public:
  explicit SpecificValuesCheck(std::initializer_list<std::string> list)
      : set_(list) {}
  bool operator()(const std::string& string) const;

 private:
  const std::unordered_set<std::string> set_;
};

class CronValuesCheck final {
 public:
  explicit CronValuesCheck(int64_t min,
                           int64_t max,
                           std::unordered_set<std::string> values = {})
      : min_(min), max_(max), values_(std::move(values)){};
  bool operator()(const std::string& string) const;

 private:
  const int64_t min_;
  const int64_t max_;
  const std::unordered_set<std::string> values_;
};

bool verifyIpAddress(std::string const& value);

bool verifyEmptyStringOrIpAddress(std::string const& value);

bool verifyMacAddress(std::string const& value);

class IntegrationTableTest : public ::testing::Test {
 protected:
  enum {
    NormalType = 0 << 0,
    IntType = 1 << 1,
    NonEmpty = 1 << 2,
    NonNull = 1 << 3,
    NonZero = 1 << 4,
    FileOnDisk = 1 << 5,
    DirectoryOnDisk = 1 << 6,
    ValidUUID = 1 << 7,
    MD5 = 1 << 8,
    SHA256 = 1 << 9,
    SHA1 = 1 << 10,
    Bool = 1 << 11,
    NonNegativeInt = IntType | NonEmpty | NonNull | (1 << 12),
    NonNegativeOrErrorInt = IntType | NonEmpty | NonNull | (1 << 13),
    NonEmptyString = NonEmpty | NormalType | NonNull,
  };

  using CustomCheckerType = std::function<bool(const std::string&)>;
  using ValidatatioDataType = boost::variant<int, CustomCheckerType>;
  using ValidatatioMap = std::unordered_map<std::string, ValidatatioDataType>;

  virtual void SetUp() {}

  virtual void TearDown() {}

  QueryData execute_query(std::string query);

  static void validate_row(const Row& row,
                           const ValidatatioMap& validation_map);
  static void validate_rows(const std::vector<Row>& rows,
                            const ValidatatioMap& validation_map);
  static bool validate_value_using_flags(const std::string& value, int flags);
  static bool is_valid_hex(const std::string& value);
};

} // namespace osquery


text:
package library

import (
	"context"
	"net/http"

	"github.com/vmware/govmomi/vapi/internal"
)

// Checksum provides checksum information on library item files.
type Checksum struct {
	Algorithm string `json:"algorithm,omitempty"`
	Checksum  string `json:"checksum"`
}

// File provides methods to get information on library item files.
type File struct {
	Cached   *bool     `json:"cached,omitempty"`
	Checksum *Checksum `json:"checksum_info,omitempty"`
	Name     string    `json:"name,omitempty"`
	Size     *int64    `json:"size,omitempty"`
	Version  string    `json:"version,omitempty"`
}

// ListLibraryItemFiles returns a list of all the files for a library item.
func (c *Manager) ListLibraryItemFiles(ctx context.Context, id string) ([]File, error) {
	url := c.Resource(internal.LibraryItemFilePath).WithParam("library_item_id", id)
	var res []File
	return res, c.Do(ctx, url.Request(http.MethodGet), &res)
}

// GetLibraryItemFile returns a file with the provided name for a library item.
func (c *Manager) GetLibraryItemFile(ctx context.Context, id, fileName string) (*File, error) {
	url := c.Resource(internal.LibraryItemFilePath).WithID(id).WithAction("get")
	spec := struct {
		Name string `json:"name"`
	}{fileName}
	var res File
	return &res, c.Do(ctx, url.Request(http.MethodPost, spec), &res)
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/popup"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/background_light">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_margin="1dp"
        android:background="@android:color/darker_gray">
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_margin="20dp">
            <TextView
                android:id="@+id/textview"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="@string/help_instructions" />

        </LinearLayout>
    </LinearLayout>
</LinearLayout>


text:
import * as React from 'react'

export class WizardMain extends React.Component<any, any> {
    render(): React.ReactElement<any> {
        return

            {this.props.children}

    }
}


text:
#pragma once
#include <aws/customer-profiles/CustomerProfiles_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace CustomerProfiles
{
namespace Model
{
  class AWS_CUSTOMERPROFILES_API GetIntegrationResult
  {
  public:
    GetIntegrationResult();
    GetIntegrationResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    GetIntegrationResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The unique name of the domain.

     */
    inline const Aws::String& GetDomainName() const{ return m_domainName; }

    /**
     *
The unique name of the domain.

     */
    inline void SetDomainName(const Aws::String& value) { m_domainName = value; }

    /**
     *
The unique name of the domain.

     */
    inline void SetDomainName(Aws::String&& value) { m_domainName = std::move(value); }

    /**
     *
The unique name of the domain.

     */
    inline void SetDomainName(const char* value) { m_domainName.assign(value); }

    /**
     *
The unique name of the domain.

     */
    inline GetIntegrationResult& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}

    /**
     *
The unique name of the domain.

     */
    inline GetIntegrationResult& WithDomainName(Aws::String&& value) { SetDomainName(std::move(value)); return *this;}

    /**
     *
The unique name of the domain.

     */
    inline GetIntegrationResult& WithDomainName(const char* value) { SetDomainName(value); return *this;}

    /**
     *
The URI of the S3 bucket or any other type of data source.

     */
    inline const Aws::String& GetUri() const{ return m_uri; }

    /**
     *
The URI of the S3 bucket or any other type of data source.

     */
    inline void SetUri(const Aws::String& value) { m_uri = value; }

    /**
     *
The URI of the S3 bucket or any other type of data source.

     */
    inline void SetUri(Aws::String&& value) { m_uri = std::move(value); }

    /**
     *
The URI of the S3 bucket or any other type of data source.

     */
    inline void SetUri(const char* value) { m_uri.assign(value); }

    /**
     *
The URI of the S3 bucket or any other type of data source.

     */
    inline GetIntegrationResult& WithUri(const Aws::String& value) { SetUri(value); return *this;}

    /**
     *
The URI of the S3 bucket or any other type of data source.

     */
    inline GetIntegrationResult& WithUri(Aws::String&& value) { SetUri(std::move(value)); return *this;}

    /**
     *
The URI of the S3 bucket or any other type of data source.

     */
    inline GetIntegrationResult& WithUri(const char* value) { SetUri(value); return *this;}

    /**
     *
The name of the profile object type.

     */
    inline const Aws::String& GetObjectTypeName() const{ return m_objectTypeName; }

    /**
     *
The name of the profile object type.

     */
    inline void SetObjectTypeName(const Aws::String& value) { m_objectTypeName = value; }

    /**
     *
The name of the profile object type.

     */
    inline void SetObjectTypeName(Aws::String&& value) { m_objectTypeName = std::move(value); }

    /**
     *
The name of the profile object type.

     */
    inline void SetObjectTypeName(const char* value) { m_objectTypeName.assign(value); }

    /**
     *
The name of the profile object type.

     */
    inline GetIntegrationResult& WithObjectTypeName(const Aws::String& value) { SetObjectTypeName(value); return *this;}

    /**
     *
The name of the profile object type.

     */
    inline GetIntegrationResult& WithObjectTypeName(Aws::String&& value) { SetObjectTypeName(std::move(value)); return *this;}

    /**
     *
The name of the profile object type.

     */
    inline GetIntegrationResult& WithObjectTypeName(const char* value) { SetObjectTypeName(value); return *this;}

    /**
     *
The timestamp of when the domain was created.

     */
    inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; }

    /**
     *
The timestamp of when the domain was created.

     */
    inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAt = value; }

    /**
     *
The timestamp of when the domain was created.

     */
    inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAt = std::move(value); }

    /**
     *
The timestamp of when the domain was created.

     */
    inline GetIntegrationResult& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;}

    /**
     *
The timestamp of when the domain was created.

     */
    inline GetIntegrationResult& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;}

    /**
     *
The timestamp of when the domain was most recently edited.

     */
    inline const Aws::Utils::DateTime& GetLastUpdatedAt() const{ return m_lastUpdatedAt; }

    /**
     *
The timestamp of when the domain was most recently edited.

     */
    inline void SetLastUpdatedAt(const Aws::Utils::DateTime& value) { m_lastUpdatedAt = value; }

    /**
     *
The timestamp of when the domain was most recently edited.

     */
    inline void SetLastUpdatedAt(Aws::Utils::DateTime&& value) { m_lastUpdatedAt = std::move(value); }

    /**
     *
The timestamp of when the domain was most recently edited.

     */
    inline GetIntegrationResult& WithLastUpdatedAt(const Aws::Utils::DateTime& value) { SetLastUpdatedAt(value); return *this;}

    /**
     *
The timestamp of when the domain was most recently edited.

     */
    inline GetIntegrationResult& WithLastUpdatedAt(Aws::Utils::DateTime&& value) { SetLastUpdatedAt(std::move(value)); return *this;}

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; }

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tags = value; }

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tags = std::move(value); }

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline GetIntegrationResult& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;}

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline GetIntegrationResult& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline GetIntegrationResult& AddTags(const Aws::String& key, const Aws::String& value) { m_tags.emplace(key, value); return *this; }

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline GetIntegrationResult& AddTags(Aws::String&& key, const Aws::String& value) { m_tags.emplace(std::move(key), value); return *this; }

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline GetIntegrationResult& AddTags(const Aws::String& key, Aws::String&& value) { m_tags.emplace(key, std::move(value)); return *this; }

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline GetIntegrationResult& AddTags(Aws::String&& key, Aws::String&& value) { m_tags.emplace(std::move(key), std::move(value)); return *this; }

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline GetIntegrationResult& AddTags(const char* key, Aws::String&& value) { m_tags.emplace(key, std::move(value)); return *this; }

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline GetIntegrationResult& AddTags(Aws::String&& key, const char* value) { m_tags.emplace(std::move(key), value); return *this; }

    /**
     *
The tags used to organize, track, or control access for this resource.

     */
    inline GetIntegrationResult& AddTags(const char* key, const char* value) { m_tags.emplace(key, value); return *this; }

  private:

    Aws::String m_domainName;

    Aws::String m_uri;

    Aws::String m_objectTypeName;

    Aws::Utils::DateTime m_createdAt;

    Aws::Utils::DateTime m_lastUpdatedAt;

    Aws::Map<Aws::String, Aws::String> m_tags;
  };

} // namespace Model
} // namespace CustomerProfiles
} // namespace Aws


text:
require 'feature_spec_helper'

feature 'Accept answer', %q{
  In order to show which answer helped me to solve my task
  As a registered user
  I want to be able accept answer
} do

  given!(:author) { create :user }
  given!(:user) { create(:user) }
  given!(:question) { create :question, user: author }
  given!(:answer) { create(:answer, body: 'First answer', question: question) }
  given!(:one_more_answer) { create(:answer, body: 'Second answer', question: question) }

  describe 'Author of question' do
    before do
       page.reset_session!
      sign_in(author)
      visit question_path(question)
    end

    scenario 'sees acceptance links for the answers' do
      expect(page).to have_selector('.accept-answer-link', count: 2)
    end

    scenario 'accept answer', js: true do
      last_answer = question.answers.last

      within("#answer-#{last_answer.id}") do
        find(:css, 'a.accept-answer-link').trigger('click')

        expect(page).to have_selector('.accepted')
        expect(page).to_not have_selector('.not-accepted')
      end

      expect(first('.answer')).to have_content('Second answer')
    end

    scenario 'accept and cancel acceptation', js: true do
      some_answer = question.answers.last
      expect(page).to_not have_selector('.accepted')

      within("#answer-#{some_answer.id}") do
        find(:css, 'a.accept-answer-link').trigger('click')

        expect(page).to have_selector('.accepted')
      end

      find(:css, 'a.accept-answer-link.accepted').trigger('click')

      expect(page).to_not have_selector('.accepted')
    end
  end

  describe "Failed to accept someone's answer by" do
    before { logout(:user) }

    scenario 'authenticated user', js: true do
      sign_in(user)
      visit question_path(question)

      expect(page).to_not have_selector('a.accept-answer-link')
    end

    scenario 'non-authenticated user', js: true do
      visit question_path(question)

      expect(page).to_not have_selector('a.accept-answer-link')
    end
  end
end


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

/** @file iothub_client.h
*	@brief Extends the IoTHubCLient_LL module with additional features.
*
*	@details IoTHubClient is a module that extends the IoTHubCLient_LL
*			 module with 2 features:
*				- scheduling the work for the IoTHubCLient from a
*				  thread, so that the user does not need to create their
*				  own thread
*				- thread-safe APIs
*/

#ifndef IOTHUB_CLIENT_H
#define IOTHUB_CLIENT_H

#include "iothub_client_ll.h"

#ifdef __cplusplus
extern "C"
{
#endif

    typedef struct IOTHUB_CLIENT_INSTANCE_TAG* IOTHUB_CLIENT_HANDLE;

    /**
    * @brief	Creates a IoT Hub client for communication with an existing
    * 			IoT Hub using the specified connection string parameter.
    *
    * @param	connectionString	Pointer to a character string
    * @param	protocol			Function pointer for protocol implementation
    *
    *			Sample connection string:
    *

    *
HostName=[IoT Hub name goes here].[IoT Hub suffix goes here, e.g., private.azure-devices-int.net];DeviceId=[Device ID goes here];SharedAccessKey=[Device key goes here];

    *

    *
    * @return	A non-NULL @c IOTHUB_CLIENT_HANDLE value that is used when
    * 			invoking other functions for IoT Hub client and @c NULL on failure.
    */
    extern IOTHUB_CLIENT_HANDLE IoTHubClient_CreateFromConnectionString(const char* connectionString, IOTHUB_CLIENT_TRANSPORT_PROVIDER protocol);

    /**
    * @brief	Creates a IoT Hub client for communication with an existing IoT
    * 			Hub using the specified parameters.
    *
    * @param	config	Pointer to an @c IOTHUB_CLIENT_CONFIG structure
    *
    *			The API does not allow sharing of a connection across multiple
    *			devices. This is a blocking call.
    *
    * @return	A non-NULL @c IOTHUB_CLIENT_HANDLE value that is used when
    * 			invoking other functions for IoT Hub client and @c NULL on failure.
    */
    extern IOTHUB_CLIENT_HANDLE IoTHubClient_Create(const IOTHUB_CLIENT_CONFIG* config);

    /**
    * @brief	Disposes of resources allocated by the IoT Hub client. This is a
    * 			blocking call.
    *
    * @param	iotHubClientHandle	The handle created by a call to the create function.
    */
    extern void IoTHubClient_Destroy(IOTHUB_CLIENT_HANDLE iotHubClientHandle);

    /**
    * @brief	Asynchronous call to send the message specified by @p eventMessageHandle.
    *
    * @param	iotHubClientHandle		   	The handle created by a call to the create function.
    * @param	eventMessageHandle		   	The handle to an IoT Hub message.
    * @param	eventConfirmationCallback  	The callback specified by the device for receiving
    * 										confirmation of the delivery of the IoT Hub message.
    * 										This callback can be expected to invoke the
    * 										::IoTHubClient_SendEventAsync function for the
    * 										same message in an attempt to retry sending a failing
    * 										message. The user can specify a @c NULL value here to
    * 										indicate that no callback is required.
    * @param	userContextCallback			User specified context that will be provided to the
    * 										callback. This can be @c NULL.
    *
    *			@b NOTE: The application behavior is undefined if the user calls
    *			the ::IoTHubClient_Destroy function from within any callback.
    *
    * @return	IOTHUB_CLIENT_OK upon success or an error code upon failure.
    */
    extern IOTHUB_CLIENT_RESULT IoTHubClient_SendEventAsync(IOTHUB_CLIENT_HANDLE iotHubClientHandle, IOTHUB_MESSAGE_HANDLE eventMessageHandle, IOTHUB_CLIENT_EVENT_CONFIRMATION_CALLBACK eventConfirmationCallback, void* userContextCallback);

    /**
    * @brief	This function returns the current sending status for IoTHubClient.
    *
    * @param	iotHubClientHandle		The handle created by a call to the create function.
    * @param	iotHubClientStatus		The sending state is populated at the address pointed
    * 									at by this parameter. The value will be set to
    * 									@c IOTHUBCLIENT_SENDSTATUS_IDLE if there is currently
    * 								    no item to be sent and @c IOTHUBCLIENT_SENDSTATUS_BUSY
    * 								    if there are.
    *
    * @return	IOTHUB_CLIENT_OK upon success or an error code upon failure.
    */
    extern IOTHUB_CLIENT_RESULT IoTHubClient_GetSendStatus(IOTHUB_CLIENT_HANDLE iotHubClientHandle, IOTHUB_CLIENT_STATUS *iotHubClientStatus);

    /**
    * @brief	Sets up the message callback to be invoked when IoT Hub issues a
    * 			message to the device. This is a blocking call.
    *
    * @param	iotHubClientHandle		   	The handle created by a call to the create function.
    * @param	messageCallback     	   	The callback specified by the device for receiving
    * 										messages from IoT Hub.
    * @param	userContextCallback			User specified context that will be provided to the
    * 										callback. This can be @c NULL.
    *
    *			@b NOTE: The application behavior is undefined if the user calls
    *			the ::IoTHubClient_Destroy function from within any callback.
    *
    * @return	IOTHUB_CLIENT_OK upon success or an error code upon failure.
    */
    extern IOTHUB_CLIENT_RESULT IoTHubClient_SetMessageCallback(IOTHUB_CLIENT_HANDLE iotHubClientHandle, IOTHUB_CLIENT_MESSAGE_CALLBACK_ASYNC messageCallback, void* userContextCallback);

    /**
    * @brief	This function returns in the out parameter @p lastMessageReceiveTime
    * 			what was the value of the @c time function when the last message was
    * 			received at the client.
    *
    * @param	iotHubClientHandle				The handle created by a call to the create function.
    * @param	lastMessageReceiveTime  		Out parameter containing the value of @c time function
    * 											when the last message was received.
    *
    * @return	IOTHUB_CLIENT_OK upon success or an error code upon failure.
    */
    extern IOTHUB_CLIENT_RESULT IoTHubClient_GetLastMessageReceiveTime(IOTHUB_CLIENT_HANDLE iotHubClientHandle, time_t* lastMessageReceiveTime);

    /**
    * @brief	This API sets a runtime option identified by parameter @p optionName
    * 			to a value pointed to by @p value. @p optionName and the data type
    * 			@p value is pointing to are specific for every option.
    *
    * @param	iotHubClientHandle	The handle created by a call to the create function.
    * @param	optionName		  	Name of the option.
    * @param	value			  	The value.
    *
    *			The options that can be set via this API are:
    *				- @b timeout - the maximum time in milliseconds a communication is
    *				  allowed to use. @p value is a pointer to an @c unsigned @c int with
    *				  the timeout value in milliseconds. This is only supported for the HTTP
    *				  protocol as of now. When the HTTP protocol uses CURL, the meaning of
    *				  the parameter is total request time. When the HTTP protocol uses
    *				  winhttp, the meaning is the same as the @c dwSendTimeout and
    *				  @c dwReceiveTimeout parameters of the
    *
    *				  WinHttpSetTimeouts API.
    *				- @b CURLOPT_LOW_SPEED_LIMIT - only available for HTTP protocol and only
    *				  when CURL is used. It has the same meaning as CURL's option with the same
    *				  name. @p value is pointer to a long.
    *				- @b CURLOPT_LOW_SPEED_TIME - only available for HTTP protocol and only
    *				  when CURL is used. It has the same meaning as CURL's option with the same
    *				  name. @p value is pointer to a long.
    *				- @b CURLOPT_FORBID_REUSE - only available for HTTP protocol and only
    *				  when CURL is used. It has the same meaning as CURL's option with the same
    *				  name. @p value is pointer to a long.
    *				- @b CURLOPT_FRESH_CONNECT - only available for HTTP protocol and only
    *				  when CURL is used. It has the same meaning as CURL's option with the same
    *				  name. @p value is pointer to a long.
    *				- @b CURLOPT_VERBOSE - only available for HTTP protocol and only
    *				  when CURL is used. It has the same meaning as CURL's option with the same
    *				  name. @p value is pointer to a long.
    *
    * @return	IOTHUB_CLIENT_OK upon success or an error code upon failure.
    */
    extern IOTHUB_CLIENT_RESULT IoTHubClient_SetOption(IOTHUB_CLIENT_HANDLE iotHubClientHandle, const char* optionName, const void* value);

#ifdef __cplusplus
}
#endif

#endif /* IOTHUB_CLIENT_H */


text:
import { authLogin, authLogout } from './auth.actions';

describe('Auth Actions', () => {
  it('should create ActionAuthLogin action', () => {
    const action = authLogin();
    expect(action.type).toEqual('[Auth] Login');
  });

  it('should create ActionAuthLogout action', () => {
    const action = authLogout();
    expect(action.type).toEqual('[Auth] Logout');
  });
});


text:
package com.google.gerrit.server.account;

import static com.google.gerrit.server.account.GetPreferences.KEY_ID;
import static com.google.gerrit.server.account.GetPreferences.KEY_TARGET;
import static com.google.gerrit.server.account.GetPreferences.KEY_URL;
import static com.google.gerrit.server.account.GetPreferences.MY;

import com.google.common.base.Strings;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.extensions.webui.TopMenu;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences.ChangeScreen;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences.CommentVisibilityStrategy;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences.ReviewCategoryStrategy;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences.DateFormat;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences.DiffView;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences.DownloadCommand;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences.DownloadScheme;
import com.google.gerrit.reviewdb.client.AccountGeneralPreferences.TimeFormat;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.account.SetPreferences.Input;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Singleton
public class SetPreferences implements RestModifyView<AccountResource, Input> {
  public static class Input {
    public Short changesPerPage;
    public Boolean showSiteHeader;
    public Boolean useFlashClipboard;
    public DownloadScheme downloadScheme;
    public DownloadCommand downloadCommand;
    public Boolean copySelfOnEmail;
    public DateFormat dateFormat;
    public TimeFormat timeFormat;
    public Boolean reversePatchSetOrder;
    public Boolean relativeDateInChangeTable;
    public Boolean sizeBarInChangeTable;
    public Boolean legacycidInChangeTable;
    public CommentVisibilityStrategy commentVisibilityStrategy;
    public ReviewCategoryStrategy reviewCategoryStrategy;
    public DiffView diffView;
    public ChangeScreen changeScreen;
    public List<TopMenu.MenuItem> my;
  }

  private final Provider<CurrentUser> self;
  private final AccountCache cache;
  private final Provider<ReviewDb> db;
  private final MetaDataUpdate.User metaDataUpdateFactory;
  private final AllUsersName allUsersName;

  @Inject
  SetPreferences(Provider<CurrentUser> self, AccountCache cache,
      Provider<ReviewDb> db, MetaDataUpdate.User metaDataUpdateFactory,
      AllUsersName allUsersName) {
    this.self = self;
    this.cache = cache;
    this.db = db;
    this.metaDataUpdateFactory = metaDataUpdateFactory;
    this.allUsersName = allUsersName;
  }

  @Override
  public GetPreferences.PreferenceInfo apply(AccountResource rsrc, Input i)
      throws AuthException, ResourceNotFoundException, OrmException,
      IOException, ConfigInvalidException {
    if (self.get() != rsrc.getUser()
        && !self.get().getCapabilities().canModifyAccount()) {
      throw new AuthException("restricted to members of Modify Accounts");
    }
    if (i == null) {
      i = new Input();
    }

    Account.Id accountId = rsrc.getUser().getAccountId();
    AccountGeneralPreferences p;
    VersionedAccountPreferences versionedPrefs;
    MetaDataUpdate md = metaDataUpdateFactory.create(allUsersName);
    db.get().accounts().beginTransaction(accountId);
    try {
      Account a = db.get().accounts().get(accountId);
      if (a == null) {
        throw new ResourceNotFoundException();
      }

      versionedPrefs = VersionedAccountPreferences.forUser(accountId);
      versionedPrefs.load(md);

      p = a.getGeneralPreferences();
      if (p == null) {
        p = new AccountGeneralPreferences();
        a.setGeneralPreferences(p);
      }

      if (i.changesPerPage != null) {
        p.setMaximumPageSize(i.changesPerPage);
      }
      if (i.showSiteHeader != null) {
        p.setShowSiteHeader(i.showSiteHeader);
      }
      if (i.useFlashClipboard != null) {
        p.setUseFlashClipboard(i.useFlashClipboard);
      }
      if (i.downloadScheme != null) {
        p.setDownloadUrl(i.downloadScheme);
      }
      if (i.downloadCommand != null) {
        p.setDownloadCommand(i.downloadCommand);
      }
      if (i.copySelfOnEmail != null) {
        p.setCopySelfOnEmails(i.copySelfOnEmail);
      }
      if (i.dateFormat != null) {
        p.setDateFormat(i.dateFormat);
      }
      if (i.timeFormat != null) {
        p.setTimeFormat(i.timeFormat);
      }
      if (i.reversePatchSetOrder != null) {
        p.setReversePatchSetOrder(i.reversePatchSetOrder);
      }
      if (i.relativeDateInChangeTable != null) {
        p.setRelativeDateInChangeTable(i.relativeDateInChangeTable);
      }
      if (i.sizeBarInChangeTable != null) {
        p.setSizeBarInChangeTable(i.sizeBarInChangeTable);
      }
      if (i.legacycidInChangeTable != null) {
        p.setLegacycidInChangeTable(i.legacycidInChangeTable);
      }
      if (i.reviewCategoryStrategy != null) {
        p.setReviewCategoryStrategy(i.reviewCategoryStrategy);
      }
      if (i.commentVisibilityStrategy != null) {
        p.setCommentVisibilityStrategy(i.commentVisibilityStrategy);
      }
      if (i.diffView != null) {
        p.setDiffView(i.diffView);
      }
      if (i.changeScreen != null) {
        p.setChangeScreen(i.changeScreen);
      }

      db.get().accounts().update(Collections.singleton(a));
      db.get().commit();
      storeMyMenus(versionedPrefs, i.my);
      versionedPrefs.commit(md);
      cache.evict(accountId);
      return new GetPreferences.PreferenceInfo(
          p, versionedPrefs,
          md.getRepository());
    } finally {
      md.close();
      db.get().rollback();
    }
  }

  public static void storeMyMenus(VersionedAccountPreferences prefs,
      List<TopMenu.MenuItem> my) {
    Config cfg = prefs.getConfig();
    if (my != null) {
      unsetSection(cfg, MY);
      for (TopMenu.MenuItem item : my) {
        set(cfg, item.name, KEY_URL, item.url);
        set(cfg, item.name, KEY_TARGET, item.target);
        set(cfg, item.name, KEY_ID, item.id);
      }
    }
  }

  private static void set(Config cfg, String section, String key, String val) {
    if (Strings.isNullOrEmpty(val)) {
      cfg.unset(MY, section, key);
    } else {
      cfg.setString(MY, section, key, val);
    }
  }

  private static void unsetSection(Config cfg, String section) {
    cfg.unsetSection(section, null);
    for (String subsection: cfg.getSubsections(section)) {
      cfg.unsetSection(section, subsection);
    }
  }
}


text:
{% extends "jqueryuibootstrap_base.html" %}
{% import 'macros/messages.html' as messages_macros with context -%}

{% block body %}

  <form class="form-signin" method="post">
    {{ form.hidden_tag() if form.hidden_tag }}

Please sign in

    {{ messages_macros.messages() }}

    {% for f in form if f.type != 'CSRFTokenField' %}

      {% if f.errors %}
        {% for e in f.errors %}

{{ e }}

        {% endfor %}
      {% endif %}
      {% if f.type == 'TextField' %}
      <input type="text" class="input-block-level" placeholder="{{ f.label.text }}" name="{{ f.name }}" {% if f.raw_data != None %} value="{{ f.data }}"{% endif %}>
      {% endif %}
      {% if f.type == 'PasswordField' %}
      <input type="password" class="input-block-level" placeholder="{{ f.label.text }}" name="{{ f.name }}">
      {% endif %}

    {% endfor %}
    <button class="btn btn-large btn-primary" type="submit">Sign in</button>
  </form>

{%- block bootstrap_js_bottom %}
{{super()}}
{%- endblock bootstrap_js_bottom %}
{% endblock %}

{%- block style_navbar_padding %}
{%- endblock style_navbar_padding %}

{% block style -%}
{{super()}}

{%- endblock style %}


text:
"""
Module containing data structures for representing datasets.
"""
from __future__ import print_function
from __future__ import division

from builtins import range
from past.utils import old_div
from builtins import object
from future.utils import with_metaclass
__author__ = 'wittawat'

from abc import ABCMeta, abstractmethod
import autograd.numpy as np
import kgof.util as util
import scipy.stats as stats

class Data(object):
    """
    Class representing a dataset i.e., en encapsulation of a data matrix
    whose rows are vectors drawn from a distribution.
    """

    def __init__(self, X):
        """
        :param X: n x d numpy array for dataset X
        """
        self.X = X

        if not np.all(np.isfinite(X)):
            print('X:')
            print(util.fullprint(X))
            raise ValueError('Not all elements in X are finite.')

    def __str__(self):
        mean_x = np.mean(self.X, 0)
        std_x = np.std(self.X, 0)
        prec = 4
        desc = ''
        desc += 'E[x] = %s \n'%(np.array_str(mean_x, precision=prec ) )
        desc += 'Std[x] = %s \n' %(np.array_str(std_x, precision=prec))
        return desc

    def dim(self):
        """Return the dimension of the data."""
        dx = self.X.shape[1]
        return dx

    def sample_size(self):
        return self.X.shape[0]

    def n(self):
        return self.sample_size()

    def data(self):
        """Return the data matrix."""
        return self.X

    def split_tr_te(self, tr_proportion=0.5, seed=820, return_tr_ind = False):
        """Split the dataset into training and test sets.

        Return (Data for tr, Data for te)"""
        X = self.X
        nx, dx = X.shape
        Itr, Ite = util.tr_te_indices(nx, tr_proportion, seed)
        tr_data = Data(X[Itr, :])
        te_data = Data(X[Ite, :])
        if return_tr_ind:
            return (tr_data, te_data, Itr)
        else:
            return (tr_data, te_data)

    def subsample(self, n, seed=87, return_ind = False):
        """Subsample without replacement. Return a new Data. """
        if n > self.X.shape[0]:
            raise ValueError('n should not be larger than sizes of X')
        ind_x = util.subsample_ind( self.X.shape[0], n, seed )
        if return_ind:
            return Data(self.X[ind_x, :]), ind_x
        else:
            return Data(self.X[ind_x, :])

    def clone(self):
        """
        Return a new Data object with a separate copy of each internal
        variable, and with the same content.
        """
        nX = np.copy(self.X)
        return Data(nX)

    def __add__(self, data2):
        """
        Merge the current Data with another one.
        Create a new Data and create a new copy for all internal variables.
        """
        copy = self.clone()
        copy2 = data2.clone()
        nX = np.vstack((copy.X, copy2.X))
        return Data(nX)

### end Data class

class DataSource(with_metaclass(ABCMeta, object)):
    """
    A source of data allowing resampling. Subclasses may prefix
    class names with DS.
    """

    @abstractmethod
    def sample(self, n, seed):
        """Return a Data. Returned result should be deterministic given
        the input (n, seed)."""
        raise NotImplementedError()

    def dim(self):
       """
       Return the dimension of the data.  If possible, subclasses should
       override this. Determining the dimension by sampling may not be
       efficient, especially if the sampling relies on MCMC.
       """
       dat = self.sample(n=1, seed=3)
       return dat.dim()

#  end DataSource

class DSIsotropicNormal(DataSource):
    """
    A DataSource providing samples from a mulivariate isotropic normal
    distribution.
    """
    def __init__(self, mean, variance):
        """
        mean: a numpy array of length d for the mean
        variance: a positive floating-point number for the variance.
        """
        assert len(mean.shape) == 1
        self.mean = mean
        self.variance = variance

    def sample(self, n, seed=2):
        with util.NumpySeedContext(seed=seed):
            d = len(self.mean)
            mean = self.mean
            variance = self.variance
            X = np.random.randn(n, d)*np.sqrt(variance) + mean
            return Data(X)

class DSNormal(DataSource):
    """
    A DataSource implementing a multivariate Gaussian.
    """
    def __init__(self, mean, cov):
        """
        mean: a numpy array of length d.
        cov: d x d numpy array for the covariance.
        """
        self.mean = mean
        self.cov = cov
        assert mean.shape[0] == cov.shape[0]
        assert cov.shape[0] == cov.shape[1]

    def sample(self, n, seed=3):
        with util.NumpySeedContext(seed=seed):
            mvn = stats.multivariate_normal(self.mean, self.cov)
            X = mvn.rvs(size=n)
            if len(X.shape) ==1:
                # This can happen if d=1
                X = X[:, np.newaxis]
            return Data(X)

class DSIsoGaussianMixture(DataSource):
    """
    A DataSource implementing a Gaussian mixture in R^d where each component
    is an isotropic multivariate normal distribution.

    Let k be the number of mixture components.
    """
    def __init__(self, means, variances, pmix=None):
        """
        means: a k x d 2d array specifying the means.
        variances: a one-dimensional length-k array of variances
        pmix: a one-dimensional length-k array of mixture weights. Sum to one.
        """
        k, d = means.shape
        if k != len(variances):
            raise ValueError('Number of components in means and variances do not match.')

        if pmix is None:
            pmix = old_div(np.ones(k),float(k))

        if np.abs(np.sum(pmix) - 1) > 1e-8:
            raise ValueError('Mixture weights do not sum to 1.')

        self.pmix = pmix
        self.means = means
        self.variances = variances

    def sample(self, n, seed=29):
        pmix = self.pmix
        means = self.means
        variances = self.variances
        k, d = self.means.shape
        sam_list = []
        with util.NumpySeedContext(seed=seed):
            # counts for each mixture component
            counts = np.random.multinomial(n, pmix, size=1)

            # counts is a 2d array
            counts = counts[0]

            # For each component, draw from its corresponding mixture component.
            for i, nc in enumerate(counts):
                # Sample from ith component
                sam_i = np.random.randn(nc, d)*np.sqrt(variances[i]) + means[i]
                sam_list.append(sam_i)
            sample = np.vstack(sam_list)
            assert sample.shape[0] == n
            np.random.shuffle(sample)
        return Data(sample)

# end of class DSIsoGaussianMixture

class DSGaussianMixture(DataSource):
    """
    A DataSource implementing a Gaussian mixture in R^d where each component
    is an arbitrary Gaussian distribution.

    Let k be the number of mixture components.
    """
    def __init__(self, means, variances, pmix=None):
        """
        means: a k x d 2d array specifying the means.
        variances: a k x d x d numpy array containing k covariance matrices,
            one for each component.
        pmix: a one-dimensional length-k array of mixture weights. Sum to one.
        """
        k, d = means.shape
        if k != variances.shape[0]:
            raise ValueError('Number of components in means and variances do not match.')

        if pmix is None:
            pmix = old_div(np.ones(k),float(k))

        if np.abs(np.sum(pmix) - 1) > 1e-8:
            raise ValueError('Mixture weights do not sum to 1.')

        self.pmix = pmix
        self.means = means
        self.variances = variances

    def sample(self, n, seed=29):
        pmix = self.pmix
        means = self.means
        variances = self.variances
        k, d = self.means.shape
        sam_list = []
        with util.NumpySeedContext(seed=seed):
            # counts for each mixture component
            counts = np.random.multinomial(n, pmix, size=1)

            # counts is a 2d array
            counts = counts[0]

            # For each component, draw from its corresponding mixture component.
            for i, nc in enumerate(counts):
                # construct the component
                # https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.multivariate_normal.html
                cov = variances[i]
                mnorm = stats.multivariate_normal(means[i], cov)
                # Sample from ith component
                sam_i = mnorm.rvs(size=nc)
                sam_list.append(sam_i)
            sample = np.vstack(sam_list)
            assert sample.shape[0] == n
            np.random.shuffle(sample)
        return Data(sample)

# end of DSGaussianMixture

class DSLaplace(DataSource):
    """
    A DataSource for a multivariate Laplace distribution.
    """
    def __init__(self, d, loc=0, scale=1):
        """
        loc: location
        scale: scale parameter.
        Described in https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace
        """
        assert d > 0
        self.d = d
        self.loc = loc
        self.scale = scale

    def sample(self, n, seed=4):
        with util.NumpySeedContext(seed=seed):
            X = np.random.laplace(loc=self.loc, scale=self.scale, size=(n, self.d))
            return Data(X)

class DSTDistribution(DataSource):
    """
    A DataSource for a univariate T-distribution.
    """
    def __init__(self, df):
        """
        df: degrees of freedom
        """
        assert df > 0
        self.df = df

    def sample(self, n, seed=5):
        with util.NumpySeedContext(seed=seed):
            X = stats.t.rvs(df=self.df, size=n)
            X = X[:, np.newaxis]
            return Data(X)

# end class DSTDistribution

class DSGaussBernRBM(DataSource):
    """
    A DataSource implementing a Gaussian-Bernoulli Restricted Boltzmann Machine.
    The probability of the latent vector h is controlled by the vector c.
    The parameterization of the Gaussian-Bernoulli RBM is given in
    density.GaussBernRBM.

    - It turns out that this is equivalent to drawing a vector of {-1, 1} for h
        according to h ~ Discrete(sigmoid(2c)).
    - Draw x | h ~ N(B*h+b, I)
    """
    def __init__(self, B, b, c, burnin=2000):
        """
        B: a dx x dh matrix
        b: a numpy array of length dx
        c: a numpy array of length dh
        burnin: burn-in iterations when doing Gibbs sampling
        """
        assert burnin >= 0
        dh = len(c)
        dx = len(b)
        assert B.shape[0] == dx
        assert B.shape[1] == dh
        assert dx > 0
        assert dh > 0
        self.B = B
        self.b = b
        self.c = c
        self.burnin = burnin

    @staticmethod
    def sigmoid(x):
        """
        x: a numpy array.
        """
        return old_div(1.0,(1+np.exp(-x)))

    def _blocked_gibbs_next(self, X, H):
        """
        Sample from the mutual conditional distributions.
        """
        dh = H.shape[1]
        n, dx = X.shape
        B = self.B
        b = self.b

        # Draw H.
        XB2C = np.dot(X, self.B) + 2.0*self.c
        # Ph: n x dh matrix
        Ph = DSGaussBernRBM.sigmoid(XB2C)
        # H: n x dh
        H = (np.random.rand(n, dh) <= Ph)*2 - 1.0
        assert np.all(np.abs(H) - 1 <= 1e-6 )
        # Draw X.
        # mean: n x dx
        mean = old_div(np.dot(H, B.T),2.0) + b
        X = np.random.randn(n, dx) + mean
        return X, H

    def sample(self, n, seed=3, return_latent=False):
        """
        Sample by blocked Gibbs sampling
        """
        B = self.B
        b = self.b
        c = self.c
        dh = len(c)
        dx = len(b)

        # Initialize the state of the Markov chain
        with util.NumpySeedContext(seed=seed):
            X = np.random.randn(n, dx)
            H = np.random.randint(1, 2, (n, dh))*2 - 1.0

            # burn-in
            for t in range(self.burnin):
                X, H = self._blocked_gibbs_next(X, H)
            # sampling
            X, H = self._blocked_gibbs_next(X, H)
        if return_latent:
            return Data(X), H
        else:
            return Data(X)

    def dim(self):
        return self.B.shape[0]

# end class DSGaussBernRBM

class DSISIPoissonLinear(DataSource):
    """
    A DataSource implementing non homogenous poisson process.
    """
    def __init__(self, b):
        """
        b: slope in of the linear function
        lambda_X = 1 + bX
        """
        if b < 0:
            raise ValueError('Parameter b must be non-negative.')
        self.b = b

    def nonhom_linear(self,size):
        b = self.b
        u = np.random.rand(size)
        if np.abs(b) <= 1e-8:
            F_l = -np.log(1-u)
        else:
            F_l = np.sqrt(-2.0/b*np.log(1-u)+old_div(1.0,(b**2)))-old_div(1.0,b)
        return F_l

    def sample(self, n, seed=3):
        with util.NumpySeedContext(seed=seed):
            X = self.nonhom_linear(size=n)
            if len(X.shape) ==1:
                # This can happen if d=1
                X = X[:, np.newaxis]
            return Data(X)

# end class DSISIPoissonLinear

class DSISIPoissonSine(DataSource):
    """
    A DataSource implementing non homogenous poisson process with sine intensity.
    lambda = b*(1+sin(w*X))
    """
    def __init__(self, w, b, delta=0.001):
        """
        w: the frequency of sine function
        b: amplitude of intensity function
        """
        self.b = b
        self.w = w
        self.delta = delta

    def func(self,t):
        val = (t + old_div((1-np.cos(self.w*t)),self.w) )*self.b
        return val

    # slow step-by-step increment by assigned delta
    def find_time(self, x):
        t = 0.0
        while self.func(t) < x:
            t += self.delta
        return t

    # bisection search to find t value with accuracy delta
    def search_time(self, x):
        b = self.b
        w = self.w
        delta = self.delta
        t_old = 0.0
        t_new = b
        val_old = self.func(t_old)
        val_new = self.func(t_new)
        while np.abs(val_new-x) > delta:
            if val_new < x and t_old < t_new:
                t_old = t_new
                t_new = t_new * 2.0
                val_old = val_new
                val_new = self.func(t_new)
            elif val_new < x and t_old > t_new:
                temp = old_div((t_old + t_new), 2.0)
                t_old = t_new
                t_new = temp
                val_old = val_new
                val_new = self.func(t_new)
            elif val_new > x and t_old > t_new:
                t_old = t_new
                t_new = old_div(t_new, 2.0)
                val_old = val_new
                val_new = self.func(t_new)
            elif val_new > x and t_old < t_new:
                temp = old_div((t_old + t_new), 2.0)
                t_old = t_new
                t_new = temp
                val_old = val_new
                val_new = self.func(t_new)
        t = t_new
        return t

    def nonhom_sine(self,size=1000):
        u = np.random.rand(size)
        x = -np.log(1-u)
        t = np.zeros(size)
        for i in range(size):
            t[i] = self.search_time(x[i])
        return t

    def sample(self, n, seed=3):
        with util.NumpySeedContext(seed=seed):
            X = self.nonhom_sine(size=n)
            if len(X.shape) ==1:
                # This can happen if d=1
                X = X[:, np.newaxis]
            return Data(X)

# end class DSISIPoissonSine

class DSGamma(DataSource):
    """
    A DataSource implementing gamma distribution.
    """
    def __init__(self, alpha, beta=1.0):
        """
        alpha: shape of parameter
        beta: scale
        """
        self.alpha = alpha
        self.beta = beta

    def sample(self, n, seed=3):
        with util.NumpySeedContext(seed=seed):
            X = stats.gamma.rvs(self.alpha, size=n, scale = old_div(1.0,self.beta))
            if len(X.shape) ==1:
                # This can happen if d=1
                X = X[:, np.newaxis]
            return Data(X)

# end class DSGamma

class DSLogGamma(DataSource):
    """
    A DataSource implementing the transformed gamma distribution.
    """
    def __init__(self, alpha, beta=1.0):
        """
        alpha: shape of parameter
        beta: scale
        """
        self.alpha = alpha
        self.beta = beta

    def sample(self, n, seed=3):
        with util.NumpySeedContext(seed=seed):
            X = np.log(stats.gamma.rvs(self.alpha, size=n, scale = old_div(1.0,self.beta)))
            if len(X.shape) ==1:
                # This can happen if d=1
                X = X[:, np.newaxis]
            return Data(X)

# end class DSLogGamma

class DSISILogPoissonLinear(DataSource):
    """
    A DataSource implementing non homogenous poisson process.
    """
    def __init__(self, b):
        """
        b: slope in of the linear function
        lambda_X = 1 + bX
        """
        if b < 0:
            raise ValueError('Parameter b must be non-negative.')
        self.b = b

    def nonhom_linear(self,size):
        b = self.b
        u = np.random.rand(size)
        if np.abs(b) <= 1e-8:
            F_l = -np.log(1-u)
        else:
            F_l = np.sqrt(-2.0/b*np.log(1-u)+old_div(1.0,(b**2)))-old_div(1.0,b)
        return F_l

    def sample(self, n, seed=3):
        with util.NumpySeedContext(seed=seed):
            X = np.log(self.nonhom_linear(size=n))
            if len(X.shape) ==1:
                # This can happen if d=1
                X = X[:, np.newaxis]
            return Data(X)

# end class DSISILogPoissonLinear

class DSISIPoisson2D(DataSource):
    """
     A DataSource implementing non homogenous poisson process.
    """
    def __init__(self, intensity = 'quadratic', w=1.0):
        """
        lambda_(X,Y) = X^2 + Y^2
        lamb_bar: upper-bound used in rejection sampling
        """
        self.w = w
        if intensity == 'quadratic':
            self.intensity = self.quadratic_intensity
        elif intensity == 'sine':
            self.intensity = self.sine_intensity
        elif intensity == 'xsine':
            self.intensity = self.cross_sine_intensity
        else:
            raise ValueError('Not intensity function found')

    def quadratic_intensity(self, X):
        intensity = self.lamb_bar*np.sum(X**2,1)
        return intensity

    def sine_intensity(self, X):
        intensity = self.lamb_bar*np.sum(np.sin(self.w*X*np.pi),1)
        return intensity

    def cross_sine_intensity(self, X):
        intensity = self.lamb_bar*np.prod(np.sin(self.w*X*np.pi),1)
        return intensity

    def inh2d(self, lamb_bar = 100000):
        self.lamb_bar = lamb_bar
        N = np.random.poisson(2*self.lamb_bar)
        X = np.random.rand(N,2)
        intensity = self.intensity(X)
        u = np.random.rand(N)
        lamb_T = old_div(intensity,lamb_bar)
        X_acc = X[u < lamb_T]
        return X_acc

    def sample(self, n, seed=3):
        with util.NumpySeedContext(seed=seed):
            X = self.inh2d(lamb_bar=n)
            if len(X.shape) ==1:
                # This can happen if d=1
                X = X[:, np.newaxis]
            return Data(X)

# end class DSISIPoisson2D

class DSISISigmoidPoisson2D(DataSource):
    """
     A DataSource implementing non homogenous poisson process.
    """
    def __init__(self, intensity = 'quadratic', w=1.0, a=1.0):
        """
        lambda_(X,Y) = a*X^2 + Y^2
        X = 1/(1+exp(s))
        Y = 1/(1+exp(t))
        X, Y \in [0,1], s,t \in R
        """
        self.a = a
        self.w = w
        if intensity == 'quadratic':
            self.intensity = self.quadratic_intensity
        elif intensity == 'sine':
            self.intensity = self.sine_intensity
        elif intensity == 'xsine':
            self.intensity = self.cross_sine_intensity
        else:
            raise ValueError('Not intensity function found')

    def quadratic_intensity(self, X):
        intensity = self.lamb_bar*np.average(X**2, axis=1, weights=[self.a,1])
        return intensity

    def cross_sine_intensity(self, X):
        intensity = self.lamb_bar*np.prod(np.sin(self.w*X*np.pi),1)
        return intensity

    def sine_intensity(self, X):
        intensity = self.lamb_bar*np.sum(np.sin(self.w*X*np.pi),1)
        return intensity

    def inh2d(self, lamb_bar = 100000):
        self.lamb_bar = lamb_bar
        N = np.random.poisson(2*self.lamb_bar)
        X = np.random.rand(N,2)
        intensity = self.intensity(X)
        u = np.random.rand(N)
        lamb_T = old_div(intensity,lamb_bar)
        X_acc = X[u < lamb_T]
        return X_acc

    def sample(self, n, seed=3):
        with util.NumpySeedContext(seed=seed):
            X = np.log(old_div(1,self.inh2d(lamb_bar=n))-1)
            if len(X.shape) ==1:
                # This can happen if d=1
                X = X[:, np.newaxis]
            return Data(X)
# end class DSISISigmoidPoisson2D

class DSPoisson2D(DataSource):
    """
     A DataSource implementing non homogenous poisson process.
    """
    def __init__(self, w = 1.0):
        """
        2D spatial poission process with default lambda_(X,Y) = sin(w*pi*X)+sin(w*pi*Y)
        """
        self.w = w

    def gmm_sample(self, mean=None, w=None, N=10000,n=10,d=2,seed=10):
        np.random.seed(seed)
        self.d = d
        if mean is None:
            mean = np.random.randn(n,d)*10
        if w is None:
            w = np.random.rand(n)
        w = old_div(w,sum(w))
        multi = np.random.multinomial(N,w)
        X = np.zeros((N,d))
        base = 0
        for i in range(n):
            X[base:base+multi[i],:] = np.random.multivariate_normal(mean[i,:], np.eye(self.d), multi[i])
            base += multi[i]

        llh = np.zeros(N)
        for i in range(n):
            llh += w[i] * stats.multivariate_normal.pdf(X, mean[i,:], np.eye(self.d))
        #llh = llh/sum(llh)
        return X, llh

    def const(self, X):
        return np.ones(len(X))*8

    def lamb_sin(self, X):
        return np.prod(np.sin(self.w*np.pi*X),1)*15

    def rej_sample(self, X, llh, func = None):
        if func is None:
            self.func = self.lamb_sin
        rate = old_div(self.func(X),llh)
        u = np.random.rand(len(X))
        X_acc = X[u < rate]
        return X_acc

    def sample(self, n, seed=3):
        with util.NumpySeedContext(seed=seed):
            X_gmm, llh = self.gmm_sample(N=n)
            X = X_gmm
            if len(X.shape) ==1:
                # This can happen if d=1
                X = X[:, np.newaxis]
            return Data(X)

# end class DSPoisson2D

class DSResample(DataSource):
    """
    A DataSource which subsamples without replacement from the specified
    numpy array (n x d).
    """

    def __init__(self, X):
        """
        X: n x d numpy array. n = sample size. d = input dimension
        """
        self.X = X

    def sample(self, n, seed=900, return_ind = False):
        X = self.X
        if n > X.shape[0]:
            # Sample more than what we have
            raise ValueError('Cannot subsample n={0} from only {1} points.'.format(n, X.shape[0]))
        dat = Data(self.X)
        return dat.subsample(n, seed=seed, return_ind = return_ind)

    def dim(self):
        return self.X.shape[1]

# end class DSResample

class DSGaussCosFreqs(DataSource):
    """
    A DataSource to sample from the density
    p(x) \propto exp(-||x||^2/2sigma^2)*(1+ prod_{i=1}^d cos(w_i*x_i))

    where w1,..wd are frequencies of each dimension.
    sigma^2 is the overall variance.
    """
    def __init__(self, sigma2, freqs):
        """
        sigma2: overall scale of the distribution. A positive scalar.
        freqs: a 1-d array of length d for the frequencies.
        """
        self.sigma2 = sigma2
        if sigma2 <= 0 :
            raise ValueError('sigma2 must be > 0')
        self.freqs = freqs

    def sample(self, n, seed=872):
        """
        Rejection sampling.
        """
        d = len(self.freqs)
        sigma2 = self.sigma2
        freqs = self.freqs
        with util.NumpySeedContext(seed=seed):
            # rejection sampling
            sam = np.zeros((n, d))
            # sample block_size*d at a time.
            block_size = 500
            from_ind = 0
            while from_ind < n:
                # The proposal q is N(0, sigma2*I)
                X = np.random.randn(block_size, d)*np.sqrt(sigma2)
                q_un = np.exp(old_div(-np.sum(X**2, 1),(2.0*sigma2)))
                # unnormalized density p
                p_un = q_un*(1+np.prod(np.cos(X*freqs), 1))
                c = 2.0
                I = stats.uniform.rvs(size=block_size) < old_div(p_un,(c*q_un))

                # accept
                accepted_count = np.sum(I)
                to_take = min(n - from_ind, accepted_count)
                end_ind = from_ind + to_take

                AX = X[I, :]
                X_take = AX[:to_take, :]
                sam[from_ind:end_ind, :] = X_take
                from_ind = end_ind
        return Data(sam)

    def dim(self):
        return len(self.freqs)


text:
'use strict';

const models = require('./index');

/**
 * Unencrypted secrets for accessing device.
 *
 */
class UnencryptedSecrets {
  /**
   * Create a UnencryptedSecrets.
   * @member {string} jobName Name of the job.
   * @member {string} [deviceType] The Device Type used in the job. Possible
   * values include: 'Pod', 'Disk', 'Cabinet'
   * @member {object} [jobSecrets] Secrets related to this job.
   * @member {string} [jobSecrets.jobSecretsType] Polymorphic Discriminator
   */
  constructor() {
  }

  /**
   * Defines the metadata of UnencryptedSecrets
   *
   * @returns {object} metadata of UnencryptedSecrets
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'UnencryptedSecrets',
      type: {
        name: 'Composite',
        className: 'UnencryptedSecrets',
        modelProperties: {
          jobName: {
            required: true,
            serializedName: 'jobName',
            type: {
              name: 'String'
            }
          },
          deviceType: {
            required: false,
            serializedName: 'deviceType',
            type: {
              name: 'Enum',
              allowedValues: [ 'Pod', 'Disk', 'Cabinet' ]
            }
          },
          jobSecrets: {
            required: false,
            serializedName: 'jobSecrets',
            type: {
              name: 'Composite',
              polymorphicDiscriminator: {
                serializedName: 'jobSecretsType',
                clientName: 'jobSecretsType'
              },
              uberParent: 'JobSecrets',
              className: 'JobSecrets'
            }
          }
        }
      }
    };
  }
}

module.exports = UnencryptedSecrets;