text:
(function () {
    "use strict";

    WinJS.UI.Pages.define("./demos/ui/controls/masterdetailview/masterdetailview.html", {
        ready: function (element, options) {
            // you're not dreaming, no code here...
        }
    });
})();

redpajama_set_name: RedPajamaGithub


text:
package com.spotify.folsom.client;

public interface SetRequest {
  byte[] getValue();

  default OpCode getOpCode() {
    return OpCode.NOOP;
  }

  default boolean withCas() {
    return false;
  }
}


text:
import { Box } from '@rocket.chat/fuselage';
import React, { ComponentProps, FC } from 'react';

const Inner: FC<ComponentProps<typeof Box>> = ({ ...props }) => <Box {...props} />;

export default Inner;


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 2.0.9
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

namespace org.doubango.tinyWRAP {

using System;
using System.Runtime.InteropServices;

public class PublicationEvent : SipEvent {
  private HandleRef swigCPtr;

  internal PublicationEvent(IntPtr cPtr, bool cMemoryOwn) : base(tinyWRAPPINVOKE.PublicationEvent_SWIGUpcast(cPtr), cMemoryOwn) {
    swigCPtr = new HandleRef(this, cPtr);
  }

  internal static HandleRef getCPtr(PublicationEvent obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  ~PublicationEvent() {
    Dispose();
  }

  public override void Dispose() {
    lock(this) {
      if (swigCPtr.Handle != IntPtr.Zero) {
        if (swigCMemOwn) {
          swigCMemOwn = false;
          tinyWRAPPINVOKE.delete_PublicationEvent(swigCPtr);
        }
        swigCPtr = new HandleRef(null, IntPtr.Zero);
      }
      GC.SuppressFinalize(this);
      base.Dispose();
    }
  }

  public tsip_publish_event_type_t getType() {
    tsip_publish_event_type_t ret = (tsip_publish_event_type_t)tinyWRAPPINVOKE.PublicationEvent_getType(swigCPtr);
    return ret;
  }

  public PublicationSession getSession() {
    IntPtr cPtr = tinyWRAPPINVOKE.PublicationEvent_getSession(swigCPtr);
    PublicationSession ret = (cPtr == IntPtr.Zero) ? null : new PublicationSession(cPtr, false);
    return ret;
  }

  public PublicationSession takeSessionOwnership() {
    IntPtr cPtr = tinyWRAPPINVOKE.PublicationEvent_takeSessionOwnership(swigCPtr);
    PublicationSession ret = (cPtr == IntPtr.Zero) ? null : new PublicationSession(cPtr, false);
    return ret;
  }

}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="arrow_size">84dp</dimen>

</resources>


text:
<?php

namespace Festitime\DatabaseBundle\Document;

use Festitime\DatabaseBundle\Traits\SerializerTrait;

/**
 * Festitime\bundles\UserBundle\Document\User
 */
class User
{
    /**
     * Use SerializerTrait to have access
     * to generic methods toArray() & toJSON()
     */
    use SerializerTrait;

    /**
     * @var MongoId $id
     */
    protected $id;

    /**
     * @var string $pseudo
     */
    protected $pseudo;

    /**
     * @var string $email
     */
    protected $email;

    /**
     * @var string $password
     */
    protected $password;

    /**
     * @var date $birthdate
     */
    protected $birthdate;

    /**
     * @var boolean $gender
     */
    protected $gender;

    /**
     * @var string $firstname
     */
    protected $firstname;

    /**
     * @var string $name
     */
    protected $name;

    /**
     * @var string $address
     */
    protected $address;

    /**
     * @var string $city
     */
    protected $city;

    /**
     * @var string $zipcode
     */
    protected $zipcode;

    /**
     * @var string $country
     */
    protected $country;

    /**
     * @var string $picture
     */
    protected $picture;

    /**
     * @var date $created_at
     */
    protected $created_at;

    /**
     * @var date $updated_at
     */
    protected $updated_at;

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

    /**
     * Set pseudo
     *
     * @param string $pseudo
     * @return self
     */
    public function setPseudo($pseudo)
    {
        $this->pseudo = $pseudo;
        return $this;
    }

    /**
     * Get pseudo
     *
     * @return string $pseudo
     */
    public function getPseudo()
    {
        return $this->pseudo;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return self
     */
    public function setEmail($email)
    {
        $this->email = $email;
        return $this;
    }

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

    /**
     * Set password
     *
     * @param string $password
     * @return self
     */
    public function setPassword($password)
    {
        $this->password = $password;
        return $this;
    }

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

    /**
     * Set birthdate
     *
     * @param date $birthdate
     * @return self
     */
    public function setBirthdate($birthdate)
    {
        $this->birthdate = $birthdate;
        return $this;
    }

    /**
     * Get birthdate
     *
     * @return date $birthdate
     */
    public function getBirthdate()
    {
        return $this->birthdate;
    }

    /**
     * Set gender
     *
     * @param boolean $gender
     * @return self
     */
    public function setGender($gender)
    {
        $this->gender = $gender;
        return $this;
    }

    /**
     * Get gender
     *
     * @return boolean $gender
     */
    public function getGender()
    {
        return $this->gender;
    }

    /**
     * Set firstname
     *
     * @param string $firstname
     * @return self
     */
    public function setFirstname($firstname)
    {
        $this->firstname = $firstname;
        return $this;
    }

    /**
     * Get firstname
     *
     * @return string $firstname
     */
    public function getFirstname()
    {
        return $this->firstname;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return self
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

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

    /**
     * Set address
     *
     * @param string $address
     * @return self
     */
    public function setAddress($address)
    {
        $this->address = $address;
        return $this;
    }

    /**
     * Get address
     *
     * @return string $address
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * Set city
     *
     * @param string $city
     * @return self
     */
    public function setCity($city)
    {
        $this->city = $city;
        return $this;
    }

    /**
     * Get city
     *
     * @return string $city
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * Set zipcode
     *
     * @param string $zipcode
     * @return self
     */
    public function setZipcode($zipcode)
    {
        $this->zipcode = $zipcode;
        return $this;
    }

    /**
     * Get zipcode
     *
     * @return string $zipcode
     */
    public function getZipcode()
    {
        return $this->zipcode;
    }

    /**
     * Set country
     *
     * @param string $country
     * @return self
     */
    public function setCountry($country)
    {
        $this->country = $country;
        return $this;
    }

    /**
     * Get country
     *
     * @return string $country
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * Set picture
     *
     * @param string $picture
     * @return self
     */
    public function setPicture($picture)
    {
        $this->picture = $picture;
        return $this;
    }

    /**
     * Get picture
     *
     * @return string $picture
     */
    public function getPicture()
    {
        return $this->picture;
    }

    /**
     * Set createdAt
     *
     * @param date $createdAt
     * @return self
     */
    public function setCreatedAt($createdAt)
    {
        $this->created_at = $createdAt;
        return $this;
    }

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

    /**
     * Set updatedAt
     *
     * @param date $updatedAt
     * @return self
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updated_at = $updatedAt;
        return $this;
    }

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


text:
[![Project Status: Active - The project has reached a stable, usable state and is being actively developed.](http://www.repostatus.org/badges/latest/active.svg)](http://www.repostatus.org/#active)
[![Build Status](https://travis-ci.org/hjwylde/werewolf.svg?branch=master)](https://travis-ci.org/hjwylde/werewolf)
[![Release](https://img.shields.io/github/release/hjwylde/werewolf.svg)](https://github.com/hjwylde/werewolf/releases/latest)

A game engine for playing werewolf within an arbitrary chat client.
Werewolf is a well known social party game, commonly also called Mafia.
See the [Wikipedia article](https://en.wikipedia.org/wiki/Mafia_(party_game)) for a rundown on its
    gameplay and history.

If you're here just to play werewolf, you may wish to skip straight to
    [chat interfaces](https://github.com/hjwylde/werewolf#chat-interfaces).

### Game description

Long has the woods been home to wild creatures, both kind and cruel.
Most have faces and are known to the inhabitants of Fougères in Brittany, France; but no-one from
    the village has yet to lay eyes on the merciless Werewolf.

Each night Werewolves attack the village and devour the innocent.
For centuries no-one knew how to fight this scourge, however recently a theory has taken ahold that
    mayhaps the Werewolves walk among the Villagers themselves...

Objective of the game:
For the Loners: complete their own objective.
For the Villagers: lynch all of the Werewolves.
For the Werewolves: devour all of the Villagers.

#### Roles

The implemented roles are split into four categories.

**The Ambiguous:**

No-one knows the true nature of the Ambiguous, sometimes not even the Ambiguous themselves!

The Ambiguous are able to change allegiance throughout the game.

* Orphan
* Village Drunk

**The Loners:**

The Loners look out for themselves and themselves alone.

The Loners must complete their own objective.

* Dullahan
* Fallen Angel
* Necromancer (and Zombie)

**The Villagers:**

Fraught with fear of the unseen enemy, the Villagers must work together to determine the truth and
    eliminate the threat to Fougères.
The task before them will not be easy, but a certain few have learnt some tricks over the years that
    may turn out rather useful.

The Villagers must lynch all of the Werewolves.

* Beholder
* Crooked Senator
* Druid
* Hunter
* Jester
* Lycan
* Medusa
* Oracle
* Protector
* Saint
* Scapegoat
* Seer
* Simple Villager
* Spiteful Villager
* True Villager
* Witch

**The Werewolves:**

Hiding in plain sight, the Werewolves are not a small trifle.

The Werewolves must devour all of the Villagers.

* Alpha Wolf
* Simple Werewolf

#### Variants

Variants alter how the game plays out.

* Standard
* No role knowledge (players are not informed of the roles in play at the start of a game)
* No role knowledge or reveal (players are not informed of the roles in play at the start of a game,
  nor each others roles upon death)
* No role reveal (players are not informed of each others roles upon death)
* Spiteful village (the default Villager role becomes the Spiteful Villager)

### Installing

Installing werewolf is easiest done using either
    [stack](https://github.com/commercialhaskell/stack) (recommended) or
    [Cabal](https://github.com/haskell/cabal).

**Using stack:**

```bash
stack install werewolf
export PATH=$PATH:~/.local/bin
```

**Using Cabal:**

```bash
cabal-install werewolf
export PATH=$PATH:~/.cabal/bin
```

### Usage

This section covers how a chat interface interacts with the werewolf game engine.

All werewolf commands are designed to be run by a user from the chat client.
E.g., to start a game:

```bash
> werewolf --caller @foo --tag werewolf start --extra-roles seer @bar @baz @qux @quux @corge @grault
{"ok":true,"messages":[
    {"to":null,"message":"A new game of werewolf is starting with @foo, @bar, @baz, @qux, @quux, @corge and @grault!"},
    {"to":null,"message":"The roles in play are Seer (1), Simple Villager (4) and Simple Werewolf (2) for a total balance of -2."},
    {"to":"@foo","message":"You're a Simple Villager.\nA simple, ordinary townsperson in every way. Some may be cobblers, others bakers or even nobles. No matter their differences though, the plight of Werewolves in Fougères unites all the Villagers in this unfortunate time.\nThe Simple Villager has no special abilities, they must use their guile to determine whom among them is not who they say they are."},
    ...,
    {"to":null,"message":"Night falls, the village is asleep."},
    {"to":null,"message":"The Seer wakes up."},
    {"to":"@corge","message":"Whose allegiance would you like to `see`?"}
    ]}
```

In this example, user _@foo_ ran the `start` command with the player names as arguments.
Note that the calling user, _@foo_, was passed in to the `--caller` option and a game tag,
    _werewolf_, was passed in to the `--tag` option.
All commands require these options (n.b., the tag option is arbitrary, it just enables multiple
    games of werewolf to be running at once).

Any command ran returns a JSON result.
The result contains a boolean for whether the command was successful and a list of messages.
The `to` header on a message may either be `null`---for a public message---or have an intended
    recipient.

It's the Seer's turn now.

```bash
> werewolf --caller @corge --tag werewolf see @grault
{"ok":true,"messages":[
    {"to":"@corge","message":"@grault is aligned with the Werewolves."},
    {"to":"@quux","message":"You feel restless, like an old curse is keeping you from sleep. It seems you're not the only one... @grault is also emerging from their home."},
    {"to":"@grault","message":"You feel restless, like an old curse is keeping you from sleep. It seems you're not the only one... @quux is also emerging from their home."},
    {"to":null,"message":"The Werewolves wake up, transform and choose a new victim."},
    {"to":"@quux","message":"Whom would you like to `vote` to devour?"},
    {"to":"@grault","message":"Whom would you like to `vote` to devour?"}
    ]}
```

Let's have the Werewolves, _@quux_ and _@grault_, vote to devour a Villager.

```bash
> werewolf --caller @quux --tag werewolf vote @foo
{"ok":true,"messages":[
    {"to":"@grault","message":"@quux voted to devour @foo."}
    ]}
> werewolf --caller @grault --tag werewolf vote @foo
{"ok":true,"messages":[
    {"to":"@quux","message":"@grault voted to devour @foo."},
    {"to":null,"message":"The sun rises. Everybody wakes up and opens their eyes..."},
    {"to":null,"message":"As you open them you notice a door broken down and @foo's guts half devoured and spilling out over the cobblestones. From the look of their personal effects, you deduce they were a Simple Villager."},
    {"to":null,"message":"As the village gathers in the square the Town Clerk calls for a vote."},
    {"to":null,"message":"Whom would you like to `vote` to lynch?"}
    ]}
```

Too bad for _@foo_. Maybe the village can get some vengeance...

```bash
> werewolf --caller @corge --tag werewolf vote @grault
{"ok":true,"messages":[]}
```

This time, even though the command was successful, there are no messages.

```bash
> werewolf --caller @corge --tag werewolf vote @grault
{"ok":false,"messages":[{"to":"@corge","message":"You've already voted!"}]}
```

Here the command was unsuccessful and an error message is sent to _@corge_.
Even though the command was unsuccessful, the chat interface probably won't need to do anything
    special.
Relaying the error message back to the user should suffice.

Thus a chat interface must implement the following:
* The ability to call werewolf commands. This includes passing the `--caller` and `--tag` options
  and arguments correctly. It is possible to only implement the `interpret` command, which
  interprets the caller's input.
* The ability to send resultant messages. Resultant messages may be to everyone or to a specific
  user.

#### Commands

See `werewolf --help`.

#### Chat interfaces

Click through for instructions on how to run a chat interface and play werewolf.

* [Slack](https://github.com/hjwylde/werewolf-slack)


text:
from hoplite.serializer import hoplite_dumps

class StatusCodeTestMixin(object):
    def assertStatusCode(self, response, status_code):
        """Assert the status code of a Flask test client response

        :param response: The test client response object
        :param status_code: The expected status code
        """
        self.assertEquals(status_code, response.status_code)
        return response

    def assertOk(self, response):
        """Test that response status code is 200

        :param response: The test client response object
        """
        return self.assertStatusCode(response, 200)

    def assertBadRequest(self, response):
        """Test that response status code is 400

        :param response: The test client response object
        """
        return self.assertStatusCode(response, 400)

    def assertForbidden(self, response):
        """Test that response status code is 403

        :param response: The test client response object
        """
        return self.assertStatusCode(response, 403)

    def assertNotFound(self, response):
        """Test that response status code is 404

        :param response: The test client response object
        """
        return self.assertStatusCode(response, 404)

    def assertContentType(self, response, content_type):
        """Assert the content-type of a Flask test client response

        :param response: The test client response object
        :param content_type: The expected content type
        """
        self.assertEquals(content_type, response.headers['Content-Type'])
        return response

    def assertOkHtml(self, response):
        """Assert the response status code is 200 and an HTML response

        :param response: The test client response object
        """
        return self.assertOk(
            self.assertContentType(response, 'text/html; charset=utf-8'))

    def assertJson(self, response):
        """Test that content returned is in JSON format

        :param response: The test client response object
        """
        return self.assertContentType(response, 'application/json')

    def assertOkJson(self, response):
        """Assert the response status code is 200 and a JSON response

        :param response: The test client response object
        """
        return self.assertOk(self.assertJson(response))

    def assertBadJson(self, response):
        """Assert the response status code is 400 and a JSON response

        :param response: The test client response object
        """
        return self.assertBadRequest(self.assertJson(response))

class FlaskTestCaseMixin(object):
    def _json_data(self, kwargs, csrf_enabled=True):
        if 'data' in kwargs:
            kwargs['data'] = hoplite_dumps(kwargs['data'])
        if not kwargs.get('content_type'):
            kwargs['content_type'] = 'application/json'
        return kwargs

    def _request(self, method, *args, **kwargs):
        kwargs.setdefault('content_type', 'text/html')
        kwargs.setdefault('follow_redirects', True)
        return method(*args, **kwargs)

    def _jrequest(self, *args, **kwargs):
        return self._request(*args, **kwargs)

    def get(self, *args, **kwargs):
        return self._request(self.client.get, *args, **kwargs)

    def delete(self, *args, **kwargs):
        return self._request(self.client.delete, *args, **kwargs)

    def jget(self, *args, **kwargs):
        return self._jrequest(self.client.get, *args, **kwargs)

    def jpost(self, *args, **kwargs):
        return self._jrequest(self.client.post, *args, **self._json_data(kwargs))

    def jput(self, *args, **kwargs):
        return self._jrequest(self.client.put, *args, **self._json_data(kwargs))

    def jpatch(self, *args, **kwargs):
        return self._jrequest(self.client.patch, *args, **self._json_data(kwargs))

    def jdelete(self, *args, **kwargs):
        return self._jrequest(self.client.delete, *args, **self._json_data(kwargs))


text:
@implementation SampleState4

- (void)start {
    [super start];

    NSLog(@"Fa");

    if (arc4random()%2) {
        [self performDelegateMethodCompletedWithEventName:kFaSuccessEventName error:nil];
    }
    else {
        [self performDelegateMethodCompletedWithEventName:kFaFailedEventName error:nil];
    }
}

@end


text:
<?php

if(!defined('WPINC')) // MUST have WordPress.
	exit('Do not access this file directly.');

if(!class_exists('c_ws_plugin__s2member_getresponse'))
{
	/**
	 * GetResponse
	 *
	 * @since 141004
	 * @package s2Member\List_Servers
	 */
	class c_ws_plugin__s2member_getresponse extends c_ws_plugin__s2member_list_server_base
	{
		/**
		 * Subscribe.
		 *
		 * @since 141004
		 * @package s2Member\List_Servers
		 *
		 * @param array $args Input arguments.
		 *
		 * @return bool True if successful.
		 */
		public static function subscribe($args)
		{
			if(!($args = self::validate_args($args)))
				return FALSE; // Invalid args.

			if(!$args->opt_in) // Double check.
				return FALSE; // Must say explicitly.

			if(!$GLOBALS['WS_PLUGIN__']['s2member']['o']['getresponse_api_key'])
				return FALSE; // Not possible.

			if(empty($GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$args->level.'_getresponse_list_ids']))
				return FALSE; // No list configured at this level.

			$gr_level_list_ids = $GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$args->level.'_getresponse_list_ids'];

			extract((array)$args); // Extract the arguments for back compat. w/ filters that relied upon them.

			foreach(preg_split('/['."\r\n\t".';,]+/', $gr_level_list_ids, NULL, PREG_SPLIT_NO_EMPTY) as $_gr_list)
			{
				$_gr = array(
					'args'       => $args,
					'function'   => __FUNCTION__,
					'list'       => trim($_gr_list),
					'list_id'    => trim($_gr_list),
					'api_method' => 'add_contact'
				);
				if(!$_gr['list'] || !$_gr['list_id'])
					continue; // List missing.

				$_gr['api_method']  = 'get_contacts'; // Check if exists.
				$_gr['api_headers'] = array('Content-Type' => 'application/json');
				$_gr['api_params']  = array($GLOBALS['WS_PLUGIN__']['s2member']['o']['getresponse_api_key'],
				                            array('campaigns' => array($_gr['list_id']), 'email' => array('EQUALS' => $args->email)));
				$_gr['api_request'] = json_encode(array('method' => $_gr['api_method'], 'params' => $_gr['api_params'], 'id' => uniqid('', TRUE)));
				if(is_object($_gr['api_response'] = json_decode(c_ws_plugin__s2member_utils_urls::remote('https://api2.getresponse.com', $_gr['api_request'], array('headers' => $_gr['api_headers'])))) && empty($_gr['api_response']->error)
				   && ($_gr['api_response_contact_ids'] = array_keys((array)$_gr['api_response']->result)) && ($_gr['api_response_contact_id'] = $_gr['api_response_contact_ids'][0])
				) // They already exist on this list, we need to update the existing subscription here instead of adding a new one.
				{
					$_gr['api_method']  = 'set_contact_name'; // Update.
					$_gr['api_headers'] = array('Content-Type' => 'application/json');
					$_gr['api_params']  = array($GLOBALS['WS_PLUGIN__']['s2member']['o']['getresponse_api_key'],
					                            array('contact' => $_gr['api_response_contact_id'], 'name' => $args->name));
					$_gr['api_request'] = json_encode(array('method' => $_gr['api_method'], 'params' => $_gr['api_params'], 'id' => uniqid('', TRUE)));
					if(is_object($_gr['api_response'] = json_decode(c_ws_plugin__s2member_utils_urls::remote('https://api2.getresponse.com', $_gr['api_request'], array('headers' => $_gr['api_headers'])))) && empty($_gr['api_response']->error))
					{
						$_gr['api_method']  = 'set_contact_customs'; // Update.
						$_gr['api_headers'] = array('Content-Type' => 'application/json');
						$_gr['api_params']  = array($GLOBALS['WS_PLUGIN__']['s2member']['o']['getresponse_api_key'],
						                            array('contact' => $_gr['api_response_contact_id'], 'customs' => apply_filters('ws_plugin__s2member_getresponse_customs_array', array(), get_defined_vars())));
						$_gr['api_request'] = json_encode(array('method' => $_gr['api_method'], 'params' => $_gr['api_params'], 'id' => uniqid('', TRUE)));
						if(is_object($_gr['api_response'] = json_decode(c_ws_plugin__s2member_utils_urls::remote('https://api2.getresponse.com', $_gr['api_request'], array('headers' => $_gr['api_headers'])))) && empty($_gr['api_response']->error))
							$_gr['api_success'] = $success = TRUE; // Flag this as `TRUE`; assists with return value below.
					}
				}
				else // Create a new contact; i.e., they do not exist yet.
				{
					$_gr['api_method']  = 'add_contact'; // Add new contact.
					$_gr['api_headers'] = array('Content-Type' => 'application/json');
					$_gr['api_params']  = array($GLOBALS['WS_PLUGIN__']['s2member']['o']['getresponse_api_key'],
					                            array('name'     => $args->name, 'email' => $args->email, 'ip' => $args->ip,
					                                  'campaign' => $_gr['list_id'], 'action' => 'standard', 'cycle_day' => 0,
					                                  'customs'  => apply_filters('ws_plugin__s2member_getresponse_customs_array', array(), get_defined_vars())));
					if(!$_gr['api_params'][1]['ip'] || $_gr['api_params'][1]['ip'] === 'unknown') unset($_gr['api_params'][1]['ip']);

					$_gr['api_request'] = json_encode(array('method' => $_gr['api_method'], 'params' => $_gr['api_params'], 'id' => uniqid('', TRUE)));
					if(is_object($_gr['api_response'] = json_decode(c_ws_plugin__s2member_utils_urls::remote('https://api2.getresponse.com', $_gr['api_request'], array('headers' => $_gr['api_headers'])))) && empty($_gr['api_response']->error) && $_gr['api_response']->result->queued)
						$_gr['api_success'] = $success = TRUE; // Flag this as `TRUE`; assists with return value below.
				}
				c_ws_plugin__s2member_utils_logs::log_entry('getresponse-api', $_gr);
			}
			unset($_gr_list, $_gr); // Just a little housekeeping.

			return !empty($success); // If one suceeds.
		}

		/**
		 * Unsubscribe.
		 *
		 * @since 141004
		 * @package s2Member\List_Servers
		 *
		 * @param array $args Input arguments.
		 *
		 * @return bool True if successful.
		 */
		public static function unsubscribe($args)
		{
			if(!($args = self::validate_args($args)))
				return FALSE; // Invalid args.

			if(!$args->opt_out) // Double check.
				return FALSE; // Must say explicitly.

			if(!$GLOBALS['WS_PLUGIN__']['s2member']['o']['getresponse_api_key'])
				return FALSE; // Not possible.

			if(empty($GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$args->level.'_getresponse_list_ids']))
				return FALSE; // No list configured at this level.

			$gr_level_list_ids = $GLOBALS['WS_PLUGIN__']['s2member']['o']['level'.$args->level.'_getresponse_list_ids'];

			extract((array)$args); // Extract the arguments for back compat. w/ filters that relied upon them.

			foreach(preg_split('/['."\r\n\t".';,]+/', $gr_level_list_ids, NULL, PREG_SPLIT_NO_EMPTY) as $_gr_list)
			{
				$_gr = array(
					'args'       => $args,
					'function'   => __FUNCTION__,
					'list'       => trim($_gr_list),
					'list_id'    => trim($_gr_list),
					'api_method' => 'delete_contact'
				);
				if(!$_gr['list'] || !$_gr['list_id'])
					continue; // List missing.

				$_gr['api_method']  = 'get_contacts'; // Check if exists.
				$_gr['api_headers'] = array('Content-Type' => 'application/json');
				$_gr['api_params']  = array($GLOBALS['WS_PLUGIN__']['s2member']['o']['getresponse_api_key'],
				                            array('campaigns' => array($_gr['list_id']), 'email' => array('EQUALS' => $args->email)));
				$_gr['api_request'] = json_encode(array('method' => $_gr['api_method'], 'params' => $_gr['api_params'], 'id' => uniqid('', TRUE)));
				if(is_object($_gr['api_response'] = json_decode(c_ws_plugin__s2member_utils_urls::remote('https://api2.getresponse.com', $_gr['api_request'], array('headers' => $_gr['api_headers'])))) && empty($_gr['api_response']->error)
				   && ($_gr['api_response_contact_ids'] = array_keys((array)$_gr['api_response']->result)) && ($_gr['api_response_contact_id'] = $_gr['api_response_contact_ids'][0])
				)// They exist on this list, so we can remove theme here via `delete_contact`.
				{
					$_gr['api_method']  = 'delete_contact'; // Delete.
					$_gr['api_headers'] = array('Content-Type' => 'application/json');
					$_gr['api_params']  = array($GLOBALS['WS_PLUGIN__']['s2member']['o']['getresponse_api_key'],
					                            array('contact' => $_gr['api_response_contact_id']));
					$_gr['api_request'] = json_encode(array('method' => $_gr['api_method'], 'params' => $_gr['api_params'], 'id' => uniqid('', TRUE)));
					if(is_object($_gr['api_response'] = json_decode(c_ws_plugin__s2member_utils_urls::remote('https://api2.getresponse.com', $_gr['api_request'], array('headers' => $_gr['api_headers'])))) && empty($_gr['api_response']->error) && $_gr['api_response']->result->deleted)
						$_gr['api_success'] = $success = TRUE; // Flag this as `TRUE`; assists with return value below.
				}
				c_ws_plugin__s2member_utils_logs::log_entry('getresponse-api', $_gr);
			}
			unset($_gr_list, $_gr); // Just a little housekeeping.

			return !empty($success); // If one suceeds.
		}

		/**
		 * Transition.
		 *
		 * @since 141004
		 * @package s2Member\List_Servers
		 *
		 * @param array $old_args Input arguments.
		 * @param array $new_args Input arguments.
		 *
		 * @return bool True if successful.
		 */
		public static function transition($old_args, $new_args)
		{
			return self::unsubscribe($old_args) && self::subscribe($new_args);
		}
	}
}


text:
from __future__ import division
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import print_function
from __future__ import unicode_literals

from BTrees.OOBTree import OOBTree
from BTrees.IOBTree import IOBTree
from werkzeug import generate_password_hash, check_password_hash
from flaskext.zodb import Model, Timestamp, Mapping, List, BTree

class Users(OOBTree):
    """Collection of user accounts, acts like a :class:`dict`."""

    def new(self, username, password):
        """Create a new account.

        :raises ValueError: For usernames that are already registered.
        :rtype: :class:`Account`

        """
        if username in self:
            raise ValueError('username taken')
        account = Account(username=username, password=password)
        self[username] = account
        return account

    def authenticate(self, username, password):
        """Authenticate a user against the accounts password.

        :raises ValueError: For usernames that are not registered.
        :rtype: :class:`bool`

        """
        if username in self:
            return self[username].authenticate(password)
        raise ValueError('no such username')

class Account(Model):
    """A user account."""

    #: A unique identifier for this account.
    username = None

    password_hash = None

    @property
    def password(self):
        """The account password, automatically hashed with a salt."""
        return self.password_hash

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def authenticate(self, password):
        """Check if a password is valid for this account.

        :rtype: :class:`bool`

        """
        return check_password_hash(self.password, password)

class History(IOBTree):
    """A log of revisions, acts like a :class:`dict` with
    timestamps in ISO 8601 for keys.

    """

    @property
    def newest(self):
        """The most recent revision"""
        return self[self.maxKey()]

    def revise(self, object, author=None, comment=None):
        """Create a new revision and log it in the history.

        :rtype: :class:`Revision`

        """
        revision = Revision(author=author, comment=comment, object=object)
        self[(self.maxKey() if self else 0) + 1] = revision
        return revision

class Revision(Model):
    """Metadata wrapping a version of an object."""

    #: The :class:`Account` that authored this revision.
    author = None

    #: A comment describing the reason for the revision.
    comment = None

    #: An automatic timestamp of when the revision was created.
    timestamp = Timestamp

    #: The wrapped object.
    object = None

class Definition(Model):
    """Definition of an entry in some language."""

    #: The actual definition.
    definition = None

    #: Accompanying notes.
    notes = None

class Entry(Model):
    """Base for dictionary entries."""

    #: The word or sequence of words that this entry defines.
    id = None

    translations = BTree

    def history(self, locale):
        """Get the history of revisions for a locale, create if needed."""
        if locale not in self.translations:
            self.translations[locale] = History()
        return self.translations[locale]

    @property
    def type(self):
        return {
            Root: 'gismu',
            Compound: 'lujvo',
            Particle: 'cmavo',
            Loan: "fu'ivla"
        }[self.__class__]

class AffixesMixin(object):
    """Mixin for words that can have affixes."""

    #: List of affix forms ("rafsi") of this word.
    affixes = List

class ExperimentalMixin(object):
    """Words that can be experimental."""

    #: Whether this word is experimental.
    experimental = False

    @property
    def type(self):
        if self.experimental:
            return 'experimental ' + super(ExperimentalMixin, self).type
        return super(ExperimentalMixin, self).type

class Root(ExperimentalMixin, Entry, AffixesMixin):
    """A root word, aka. "gismu"."""

    #: Map of language codes to words this root is based on.
    etymology = Mapping

class Compound(Entry):
    """Word built with affixes, aka. "lujvo"."""

    #: The metaphor ("tanru") that results in this compound.
    source = None

class Particle(ExperimentalMixin, Entry, AffixesMixin):
    """Grammatical particle, aka. "cmavo"."""

    #: Grammatical class ("selma'o").
    class_ = None

class Loan(Entry, AffixesMixin):
    """Word borrowed from a foreign language, aka. "fu'ivla"."""

    #: The word this loanword is based on.
    base = None

    #: The language code for the language this word was borrowed from.
    origin = None


text:
package com.terremark.api;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for AlertTypeEnum.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="AlertTypeEnum">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="None"/>
 *     <enumeration value="Alarm"/>
 *     <enumeration value="Incident"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "AlertTypeEnum")
@XmlEnum
public enum AlertTypeEnum {

    @XmlEnumValue("None")
    NONE("None"),
    @XmlEnumValue("Alarm")
    ALARM("Alarm"),
    @XmlEnumValue("Incident")
    INCIDENT("Incident");
    private final String value;

    AlertTypeEnum(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static AlertTypeEnum fromValue(String v) {
        for (AlertTypeEnum c: AlertTypeEnum.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
//
//  DiscoveryManager.h
//  Connect SDK
//
//  Created by Jeremy White on 12/2/13.
//  Copyright (c) 2014 LG Electronics.
//
//  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.
//

#import <Foundation/Foundation.h>
#import "DiscoveryManagerDelegate.h"
#import "DevicePicker.h"
#import "ConnectableDeviceStore.h"

/*!
 * ###Overview
 *
 * At the heart of Connect SDK is DiscoveryManager, a multi-protocol service discovery engine with a pluggable architecture. Much of your initial experience with Connect SDK will be with the DiscoveryManager class, as it consolidates discovered service information into ConnectableDevice objects.
 *
 * ###In depth
 * DiscoveryManager supports discovering services of differing protocols by using DiscoveryProviders. Many services are discoverable over [SSDP][0] and are registered to be discovered with the SSDPDiscoveryProvider class.
 *
 * As services are discovered on the network, the DiscoveryProviders will notify DiscoveryManager. DiscoveryManager is capable of attributing multiple services, if applicable, to a single ConnectableDevice instance. Thus, it is possible to have a mixed-mode ConnectableDevice object that is theoretically capable of more functionality than a single service can provide.
 *
 * DiscoveryManager keeps a running list of all discovered devices and maintains a filtered list of devices that have satisfied any of your CapabilityFilters. This filtered list is used by the DevicePicker when presenting the user with a list of devices.
 *
 * Only one instance of the DiscoveryManager should be in memory at a time. To assist with this, DiscoveryManager has singleton accessors at sharedManager and sharedManagerWithDeviceStore:.
 *
 * Example:
 *
 * @capability kMediaControlPlay
 *
 @code
   DiscoveryManager *discoveryManager = [DiscoveryManager sharedManager];
   discoveryManager.delegate = self; // set delegate to listen for discovery events
   [discoveryManager startDiscovery];
 @endcode
 *
 * [0]: http://tools.ietf.org/html/draft-cai-ssdp-v1-03
 */
@interface DiscoveryManager : NSObject <ConnectableDeviceDelegate>

/*!
 * Delegate which should receive discovery updates. It is not necessary to set this delegate property unless you are implementing your own device picker. Connect SDK provides a default DevicePicker which acts as a DiscoveryManagerDelegate, and should work for most cases.
 *
 * If you have provided a capabilityFilters array, the delegate will only receive update messages for ConnectableDevices which satisfy at least one of the CapabilityFilters. If no capabilityFilters array is provided, the delegate will receive update messages for all ConnectableDevice objects that are discovered.
 */
@property (nonatomic, weak) id<DiscoveryManagerDelegate> delegate;

/*!
 * Singleton accessor for DiscoveryManager. This method calls sharedManagerWithDeviceStore: and passes an instance of DefaultConnectableDeviceStore.
 */
+ (instancetype) sharedManager;

/*!
 * Singleton accessor for DiscoveryManager, will initialize singleton with reference to a custom ConnectableDeviceStore object.
 *
 * @param deviceStore (optional) An object which implements the ConnectableDeviceStore protocol to be used for save/load of device information. You may provide nil to completely disable the device store capabilities of the SDK.
 */
+ (instancetype) sharedManagerWithDeviceStore:(id<ConnectableDeviceStore>)deviceStore;

/*!
 * Filtered list of discovered ConnectableDevices, limited to devices that match at least one of the CapabilityFilters in the capabilityFilters array. Each ConnectableDevice object is keyed against its current IP address.
 */
- (NSDictionary *) compatibleDevices;

/*!
 * List of all devices discovered by DiscoveryManager. Each ConnectableDevice object is keyed against its current IP address.
 */
- (NSDictionary *) allDevices;

#pragma mark - Configuration & Device Registration

// @cond INTERNAL

/*
 * Registers a commonly-used set of DeviceServices with DiscoveryManager. This method will be called on first call of startDiscovery if no DeviceServices have been registered.
 *
 * - CastDiscoveryProvider
 *   + CastService
 * - SSDPDiscoveryProvider
 *   + DIALService
 *   + DLNAService (limited to LG TVs, currently)
 *   + NetcastTVService
 *   + RokuService
 *   + WebOSTVService
 */
- (void) registerDefaultServices;

/*
 * Registers a DeviceService with DiscoveryManager and tells it which DiscoveryProvider to use to find it. Each DeviceService has an NSDictionary of discovery parameters that its DiscoveryProvider will use to find it.
 *
 * @param deviceClass Class for object that should be instantiated when DeviceService is found
 * @param discoveryClass Class for object that should discover this DeviceService. If a DiscoveryProvider of this class already exists, then the existing DiscoveryProvider will be used.
 */
- (void) registerDeviceService:(Class)deviceClass withDiscovery:(Class)discoveryClass;

/*
 * Unregisters a DeviceService with DiscoveryManager. If no other DeviceServices are set to being discovered with the associated DiscoveryProvider, then that DiscoveryProvider instance will be stopped and shut down.
 *
 * @param deviceClass Class for DeviceService that should no longer be discovered
 * @param discoveryClass Class for DiscoveryProvider that is discovering DeviceServices of deviceClass type
 */
- (void) unregisterDeviceService:(Class)deviceClass withDiscovery:(Class)discoveryClass;

// @endcond

/*!
 * A ConnectableDevice will be displayed in the DevicePicker and compatibleDevices array if it matches any of the CapabilityFilter objects in this array.
 */
@property (nonatomic, strong) NSArray *capabilityFilters;

/*!
 * The pairingLevel property determines whether capabilities that require pairing (such as entering a PIN) will be available.
 *
 * If pairingLevel is set to ConnectableDevicePairingLevelOn, ConnectableDevices that require pairing will prompt the user to pair when connecting to the ConnectableDevice.
 *
 * If pairingLevel is set to ConnectableDevicePairingLevelOff (the default), connecting to the device will avoid requiring pairing if possible but some capabilities may not be available.
 */
@property (nonatomic) ConnectableDevicePairingLevel pairingLevel;

#pragma mark - Control

/*!
 * Start scanning for devices on the local network.
 */
- (void) startDiscovery;

/*!
 * Stop scanning for devices.
 *
 * This method will be called when your app enters a background state. When your app resumes, startDiscovery will be called.
 */
- (void) stopDiscovery;

#pragma mark - Device Picker

/*!
 * Get a DevicePicker to show compatible ConnectableDevices that have been found by DiscoveryManager.
 *
 * @return DevicePicker DevicePicker singleton for use in picking devices
 */
- (DevicePicker*) devicePicker;

#pragma mark - Device Store

/*!
 * ConnectableDeviceStore object which loads & stores references to all discovered devices. Pairing codes/keys, SSL certificates, recent access times, etc are kept in the device store.
 *
 * ConnectableDeviceStore is a protocol which may be implemented as needed. A default implementation, DefaultConnectableDeviceStore, exists for convenience and will be used if no other device store is provided.
 *
 * In order to satisfy user privacy concerns, you should provide a UI element in your app which exposes the ConnectableDeviceStore removeAll method.
 *
 * To disable the ConnectableDeviceStore capabilities of Connect SDK, set this value to nil. This may be done at the time of instantiation with `[DiscoveryManager sharedManagerWithDeviceStore:nil]`.
 */
@property (nonatomic) id<ConnectableDeviceStore> deviceStore;

/*!
 * Whether pairing state will be automatically loaded/saved in the deviceStore. This property is not available for direct modification. To disable the device store,
 */
@property (nonatomic, readonly) BOOL useDeviceStore;

// @cond INTERNAL

@property (nonatomic, readonly) NSDictionary *deviceClasses;

@property (nonatomic, readonly) NSArray *discoveryProviders;

// @endcond

@end


text:
Imports System
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Linq
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports DotNetNuke
Imports DotNetNuke.Security
Imports MPD

Namespace DotNetNuke.Modules.AgapeConnect
    Partial Class mpdCalc
        Inherits Entities.Modules.PortalModuleBase

        Const GR_MPDGOAL_ID_STAGE = "e5a338f8-0c2b-11e4-b27c-12c37bb2d521"
        Const GR_MPDEXPENSE_ID_STAGE = "1e2bc398-0c2c-11e4-a651-12c37bb2d521"
        Const GR_MPDGOAL_ID = "b63003d2-0d9b-11e4-bcd4-12543788cf06"
        Const GR_MPDEXPENSE_ID = "88077c4c-0d9b-11e4-997d-12543788cf06"

        Private _age1 As Integer = 0
        Public Property Age1() As Integer
            Get
                Return _age1
            End Get
            Set(ByVal value As Integer)
                _age1 = value
            End Set
        End Property

        Private _age2 As Integer = 0
        Public Property Age2() As Integer
            Get
                Return _age2
            End Get
            Set(ByVal value As Integer)
                _age2 = value
            End Set
        End Property

        Private _isCouple As Boolean = False
        Public Property IsCouple() As Boolean
            Get
                Return _isCouple
            End Get
            Set(ByVal value As Boolean)
                _isCouple = value
            End Set
        End Property

        Private _staffType As String = ""
        Public Property StaffType() As String
            Get
                Return _staffType
            End Get
            Set(ByVal value As String)
                _staffType = value
            End Set
        End Property

        Private StaffBudId As Integer = -1
        Public LastSection As Integer = 0
        Public DefaultAccount As String = ""
        Public TagReplacementScript As String = ""

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
            If (Not String.IsNullOrEmpty(Request.QueryString("sb"))) Then
                StaffBudId = Request.QueryString("sb")
            End If

            If Not Page.IsPostBack Then

                Dim ds As New StaffBroker.StaffBrokerDataContext

                pnlInsert.Visible = IsEditMode()

                Dim d As New MPDDataContext()
                Dim theForm = From c In d.AP_mpdCalc_Definitions Where c.TabModuleId = TabModuleId And c.PortalId = PortalId
                Dim Staff = StaffBrokerFunctions.GetStaffMember(UserId)
                Dim thisForm As AP_mpdCalc_Definition
                If theForm.Count > 0 Then
                    thisForm = theForm.First
                Else
                    thisForm = mpdFunctions.CreateNewDef(PortalId, TabModuleId)
                End If

                mpdAdminPanel.mpdDefId = thisForm.mpdDefId
                mpdAdminPanel.Visible = IsEditMode()

                DefaultAccount = thisForm.DefaultAccount

                Dim bud = From c In theForm.First.AP_mpdCalc_StaffBudgets Where c.StaffBudgetId = StaffBudId
                If bud.Count > 0 Then
                    'If Not bud.First.CurrentSupportLevel Is Nothing Then
                    '    itemCurrent.Monthly = bud.First.CurrentSupportLevel.Value.ToString("F0", New CultureInfo("en-US"))
                    'End If

                    Dim FirstBudgetMonth As Integer? = bud.First.AP_mpdCalc_Definition.FirstBudgetPeriod
                    If FirstBudgetMonth Is Nothing Then
                        FirstBudgetMonth = 7

                    End If
                    Dim fpStartDate As Date
                    If FirstBudgetMonth <= Today.Month Then
                        fpStartDate = New Date(Today.Year, FirstBudgetMonth, 1)
                    Else
                        fpStartDate = New Date(Today.Year - 1, FirstBudgetMonth, 1)
                    End If

                    For i As Integer = -1 To 1
                        ddlStartPeriod.Items.Add(New ListItem(fpStartDate.AddYears(i).ToString("MMM yyyy"), fpStartDate.AddYears(i).ToString("yyyyMM")))
                    Next
                    ddlStartPeriod.Items.Clear()
                    ddlStartPeriod.Items.Add(New ListItem("Last Year: " & fpStartDate.AddYears(-1).ToString("MMMM yyyy"), fpStartDate.AddYears(-1).ToString("yyyyMM")))
                    ddlStartPeriod.Items.Add(New ListItem("This Year: " & fpStartDate.AddYears(0).ToString("MMMM yyyy"), fpStartDate.AddYears(0).ToString("yyyyMM")))
                    ddlStartPeriod.Items.Add(New ListItem("Next Year: " & fpStartDate.AddYears(1).ToString("MMMM yyyy"), fpStartDate.AddYears(1).ToString("yyyyMM")))

                    ddlStartPeriod.Items.Add(New ListItem("Custom (Please specify):", ""))

                    ddlStartPeriod.SelectedIndex = 1

                    ddlYear.Items.Clear()
                    ddlYear.Items.Add(New ListItem(fpStartDate.AddYears(-1).ToString("yyyy"), fpStartDate.AddYears(-1).ToString("yyyy")))
                    ddlYear.Items.Add(New ListItem(fpStartDate.AddYears(0).ToString("yyyy"), fpStartDate.AddYears(0).ToString("yyyy")))
                    ddlYear.Items.Add(New ListItem(fpStartDate.AddYears(1).ToString("yyyy"), fpStartDate.AddYears(1).ToString("yyyy")))

                    Select Case bud.First.Status
                        Case StaffRmb.RmbStatus.Draft
                            btnSubmit.Visible = True
                            btnCancel.Visible = False
                        Case StaffRmb.RmbStatus.Submitted
                            btnApprove.Visible = Staff.StaffId <> bud.First.StaffId
                        Case StaffRmb.RmbStatus.Approved
                            btnProcess.Visible = IsEditMode()
                        Case StaffRmb.RmbStatus.Processed
                            btnCancel.Visible = False
                        Case StaffRmb.RmbStatus.Cancelled
                            btnSubmit.Visible = True
                            btnCancel.Visible = False
                    End Select

                    lblStatus.Text = StaffRmb.RmbStatus.StatusName(bud.First.Status)
                    Dim dt = New Date(CInt(Left(bud.First.BudgetPeriodStart, 4)), CInt(Right(bud.First.BudgetPeriodStart, 2)), 1)

                    If ddlStartPeriod.Items.FindByValue(bud.First.BudgetPeriodStart) Is Nothing Then
                        ddlStartPeriod.SelectedValue = ""
                        ddlPeriod.SelectedValue = dt.Month

                        ddlYear.SelectedValue = dt.Year
                        customDate.Attributes.CssStyle.Remove("display")
                    Else
                        ddlPeriod.SelectedValue = bud.First.BudgetPeriodStart

                    End If

                    If bud.First.Status <> StaffRmb.RmbStatus.Draft And bud.First.Status <> StaffRmb.RmbStatus.Cancelled Then
                        cbCompliance.Enabled = False
                        cbCompliance.Checked = True
                        btnSubmit.Enabled = True
                    End If
                    Staff = StaffBrokerFunctions.GetStaffbyStaffId(bud.First.StaffId)

                End If
                'Dim d As New StaffBroker.StaffBrokerDataContext
                Dim staffDefs = From c In ds.AP_StaffBroker_StaffPropertyDefinitions Where c.PortalId = PortalId

                For Each row In staffDefs

                    Dim value = StaffBrokerFunctions.GetStaffProfileProperty(Staff.StaffId, row.PropertyName)
                    If row.Type = 2 Then 'Boolean
                        value = value.ToLower
                        If value = "" Then
                            value = "false"
                        End If
                    ElseIf row.Type = 0 Then 'string
                        value = "'" & value & "'"
                    ElseIf row.Type = 1 And String.IsNullOrEmpty(value) Then
                        value = 0

                    End If
                    TagReplacementScript &= "f = f.replace(/{" & row.PropertyName & "}/g, " & value & ");" & vbNewLine
                Next

                hfTagReplacementScript.Value = TagReplacementScript

                lblStaffName.Text = Translate("BudgetFor").Replace("[NAME]", "<b>" & Staff.DisplayName & "<b>")
                IsCouple = Staff.UserId2 > 0
                StaffType = Staff.AP_StaffBroker_StaffType.Name
                'itemCurrent.Monthly = mpdFunctions.getAverageMonthlyIncomeOver12Periods(Staff.StaffId)
                itemCurrent.Monthly = mpdFunctions.getAverageMonthlyIncome(PortalId, bud.First.StaffId, mpdFunctions.AverageType.Average12)
                If (thisForm.AP_mpdCalc_Sections.Count > 0) Then
                    LastSection = thisForm.AP_mpdCalc_Sections.Max(Function(c) c.Number)
                End If
                rpSections.DataSource = thisForm.AP_mpdCalc_Sections.OrderBy(Function(c) c.Number)
                rpSections.DataBind()

                ddlInsertOrder.DataSource = (From c In thisForm.AP_mpdCalc_Sections Select c.Number + 1)
                ddlInsertOrder.DataBind()

                hfAssessment.Value = thisForm.Assessment
                hfCompentation.Value = thisForm.Compensation

                If theForm.First.ShowComplience Then
                    cbCompliance.Text = thisForm.Complience

                End If
                cbCompliance.Visible = thisForm.ShowComplience
                Try
                    Dim user1 = UserController.GetUserById(PortalId, Staff.UserId1)
                    Age1 = DateDiff(DateInterval.Year, Date.Parse(User1.Profile.GetPropertyValue("Birthday"), New CultureInfo("en-gb")), Today)
                Catch ex As Exception
                    Age1 = 0
                End Try
                If Staff.UserId2 > 0 Then
                    Try
                        Dim user1 = UserController.GetUserById(PortalId, Staff.UserId2)
                        Age2 = DateDiff(DateInterval.Year, Date.Parse(User1.Profile.GetPropertyValue("Birthday"), New CultureInfo("en-gb")), Today)
                    Catch ex As Exception
                        Age2 = 0
                    End Try
                Else
                    Age2 = 0
                End If

            Else
                TagReplacementScript = hfTagReplacementScript.Value

            End If

        End Sub
        Public Function Translate(ByVal ResourceString As String) As String
            Dim rtn As String
            Try
                rtn = DotNetNuke.Services.Localization.Localization.GetString(ResourceString & ".Text", LocalResourceFile)
                If String.IsNullOrEmpty(rtn) Then
                    rtn = DotNetNuke.Services.Localization.Localization.GetString(ResourceString & ".Text", "/DesktopModules/AgapeConnect/mpdCalc/App_LocalResources/mpdCalc.ascx.resx")
                End If
            Catch ex As Exception

                rtn = DotNetNuke.Services.Localization.Localization.GetString(ResourceString & ".Text", "/DesktopModules/AgapeConnect/mpdCalc/App_LocalResources/mpdCalc.ascx.resx")

            End Try

            Return rtn

        End Function

        Private Sub set_if(ByRef prop As Object, ByVal value As Object)
            If Not value Is Nothing Then
                prop = value
            End If
        End Sub

        Public Function GetAnswer(ByVal QuestionId As Integer) As String
            If (StaffBudId > 0) Then
                Dim d As New MPDDataContext

                Dim q = From c In d.AP_mpdCalc_Answers Where c.QuestionId = QuestionId And c.StaffBudgetId = StaffBudId

                If q.Count > 0 Then
                    Return q.First.Value.Value.ToString("n2", New CultureInfo("en-US"))
                End If
            End If
            Return ""
        End Function
        Public Function GetName(ByVal QuestionId As Integer, ByVal DefName As String) As String
            If Not String.IsNullOrEmpty(DefName) Then
                Return DefName
            End If
            If (StaffBudId > 0) Then
                Dim d As New MPDDataContext

                Dim q = From c In d.AP_mpdCalc_Answers Where c.QuestionId = QuestionId And c.StaffBudgetId = StaffBudId

                If q.Count > 0 Then
                    Return "!!" & q.First.Name
                End If
            End If
            Return ""
        End Function

        Private Sub SaveBudget(Optional ByVal ToStatus As Integer = -1)
            Dim d As New MPD.MPDDataContext

            Dim def = From c In d.AP_mpdCalc_Definitions Where c.TabModuleId = TabModuleId And c.PortalId = PortalId
            If def.Count > 0 Then

                Dim bud = From c In d.AP_mpdCalc_StaffBudgets Where c.StaffBudgetId = CInt(Request.QueryString("sb")) ' And c.BudgetYearStart = Today.Year
                Dim budId As Integer = -1
                If bud.Count > 0 Then

                    bud.First.CurrentSupportLevel = itemCurrent.Monthly
                    bud.First.TotalBudget = hfMpdGoal.Value
                    bud.First.Compensation = hfCompensationValue.Value
                    bud.First.ToRaise = bud.First.TotalBudget - bud.First.Compensation

                    bud.First.BudgetPeriodStart = IIf(ddlStartPeriod.SelectedValue = "", New Date(ddlYear.SelectedValue, ddlPeriod.SelectedValue, 1).ToString("yyyyMM"), ddlStartPeriod.SelectedValue)
                    bud.First.BudgetYearStart = Left(bud.First.BudgetPeriodStart, 4)

                    If ToStatus >= 0 Then
                        bud.First.Status = ToStatus
                        Select Case (ToStatus)
                            Case StaffRmb.RmbStatus.Submitted
                                bud.First.SubmittedOn = Now
                                bud.First.ApproveCode = Guid.NewGuid().ToString
                            Case StaffRmb.RmbStatus.Approved
                                bud.First.ApprovedOn = Now
                                bud.First.ApprovedBy = UserId

                            Case StaffRmb.RmbStatus.Processed
                                bud.First.ProcessedOn = Now
                                bud.First.ProcessedBy = UserId
                        End Select

                    End If
                    budId = bud.First.StaffBudgetId

                End If

                d.AP_mpdCalc_Answers.DeleteAllOnSubmit(d.AP_mpdCalc_Answers.Where(Function(c) c.StaffBudgetId = budId))

                Dim budgetvalues As New Dictionary(Of String, Double)
                Dim Staff = StaffBrokerFunctions.GetStaffbyStaffId(bud.First.StaffId)
                For Each s In rpSections.Items
                    Dim rp As Repeater = s.FindControl("rpItems")
                    For Each q In rp.Items
                        Dim m As mpdItem = q.FindControl("theMpdItem")

                        Dim insert As New MPD.AP_mpdCalc_Answer
                        insert.QuestionId = m.QuestionId
                        If m.Monthly = 0 Then

                            insert.Value = m.Yearly / 12
                        Else
                            insert.Value = m.Monthly
                        End If

                        insert.Name = m.ItemName
                        insert.Tax = m.Tax
                        insert.StaffBudgetId = budId

                        d.AP_mpdCalc_Answers.InsertOnSubmit(insert)

                        AddToBudget(budgetvalues, m.AccountCode, insert.Value + insert.Tax)

                    Next
                Next
                d.SubmitChanges()
                If bud.First.Status = StaffRmb.RmbStatus.Processed Then
                    'Send to GR
                    Dim gr_server = StaffBrokerFunctions.GetSetting("gr_api_url", PortalId)
                    Dim gr_api_key = StaffBrokerFunctions.GetSetting("gr_api_key", PortalId)

                    Dim user1 = UserController.GetUserById(PortalId, Staff.UserId1)
                    Dim rel_id = user1.Profile.GetPropertyValue("gr_ministry_membership_id")

                    If Not String.IsNullOrEmpty(gr_server) And Not String.IsNullOrEmpty(rel_id) Then

                        Dim gr = New GR_NET.GR(gr_api_key, gr_server, False)

                        Dim mt_expense As New GR_NET.MeasurementType()

                        Dim mt_goal As New GR_NET.MeasurementType()

                        If (gr_server.Contains("stage")) Then
                            mt_expense.ID = GR_MPDEXPENSE_ID_STAGE
                            mt_goal.ID = GR_MPDGOAL_ID_STAGE
                        Else
                            mt_expense.ID = GR_MPDEXPENSE_ID
                            mt_goal.ID = GR_MPDGOAL_ID
                        End If
                        Dim startDate = New Date(Left(bud.First.BudgetPeriodStart, 4), Right(bud.First.BudgetPeriodStart, 2), 1)

                        For i As Integer = 0 To 18
                            Dim theDate = startDate.AddMonths(i)
                            Dim insert_goal As New GR_NET.Measurement
                            Dim period = theDate.ToString("yyyy-MM")

                            mt_goal.addMeasurement(rel_id, period, mpdFunctions.getBudgetForStaffPeriod(Staff.StaffId, theDate.ToString("yyyyMM")))
                            mt_expense.addMeasurement(rel_id, period, mpdFunctions.getExpenseBudgetForStaffPeriod(Staff.StaffId, theDate.ToString("yyyyMM")))

                        Next
                        gr.AddUpdateMeasurement(mt_goal)
                        gr.AddUpdateMeasurement(mt_expense)

                    End If

                    If Not StaffBrokerFunctions.GetSetting("NonDynamics", PortalId) = "True" Then

                        Dim FirstFiscalMonth = StaffBrokerFunctions.GetSetting("FirstFiscalMonth", PortalId)
                        If String.IsNullOrEmpty(FirstFiscalMonth) Then
                            FirstFiscalMonth = 7
                        End If
                        Dim rc = StaffBrokerFunctions.GetStaffbyStaffId(bud.First.StaffId).CostCenter
                        Dim fy = getFiscalYear(bud.First.BudgetPeriodStart, FirstFiscalMonth)

                        Dim fp = GetFiscalPeriod(bud.First.BudgetPeriodStart, FirstFiscalMonth)

                        For Each row In budgetvalues

                            AddBudgetFromPeriod(StaffBrokerFunctions.GetStaffbyStaffId(bud.First.StaffId).CostCenter, row.Key, fy, row.Value, fp, 12)
                            If fp <> 1 Then
                                AddBudgetFromPeriod(StaffBrokerFunctions.GetStaffbyStaffId(bud.First.StaffId).CostCenter, row.Key, fy + 1, row.Value, 1, fp)
                            End If

                        Next
                    End If
                End If
                d.SubmitChanges()

                If ToStatus = StaffRmb.RmbStatus.Submitted Then
                    'Send Email to Approver

                    'Dim Auth = UserController.GetUserById(PortalId, Settings("AuthUser"))
                    'Dim AuthAuth = UserController.GetUserById(PortalId, Settings("AuthAuthUser"))

                    Dim leaders = StaffBrokerFunctions.GetLeaders(Staff.UserId1)
                    If Staff.UserId2 > 0 Then
                        leaders.AddRange(StaffBrokerFunctions.GetLeaders(Staff.UserId2))
                    End If

                    If leaders.Count = 0 Then
                        leaders.Add(42)
                    End If
                    Dim Message As String = StaffBrokerFunctions.GetTemplate("mpdSubmitted", PortalId)
                    Message = Message.Replace("[STAFFNAME]", Staff.DisplayName).Replace("[BUDGETDETAIL]", GetDetailTable(bud.First))

                    For Each leader In leaders
                        Dim l = UserController.GetUserById(PortalId, leader)

                        DotNetNuke.Services.Mail.Mail.SendMail("donotreply@agapeconnect.me", l.Email, "", "MPD Budget for " & Staff.DisplayName, Message.Replace("[BUTTONS]", GetApproveButtons(bud.First.ApproveCode, leader)).Replace("[APPROVER]", l.FirstName), "", "HTML", "", "", "", "")

                    Next
                    'Dim ConfMessage As String = Server.HtmlDecode(StaffBrokerFunctions.GetTemplate("AdvConfirmation", PortalId))

                ElseIf ToStatus = StaffRmb.RmbStatus.Approved Then
                    'Send Email to Staff Member
                    Dim Emessage As String = StaffBrokerFunctions.GetTemplate("mpdApproved", PortalId)

                    Emessage = Emessage.Replace("[STAFFNAME]", Staff.DisplayName)
                    Emessage = Emessage.Replace("[APPROVER]", UserInfo.DisplayName)
                    Dim dt As New Date(Left(bud.First.BudgetPeriodStart, 4), Right(bud.First.BudgetPeriodStart, 2), 1)
                    Emessage = Emessage.Replace("[STARTPERIOD]", dt.ToString("MMMM yyyy"))
                    Dim toEmail = Staff.User.Email

                    If Staff.UserId2 > 0 Then
                        toEmail &= "; " & Staff.User2.Email
                    End If
                    DotNetNuke.Services.Mail.Mail.SendMail("donotreply@agapeconnect.me", toEmail, "", "Budget Approved", Emessage, "", "HTML", "", "", "", "")

                End If

                Response.Redirect(Request.Url.ToString)

            End If

        End Sub
        Private Function GetApproveButtons(ByVal Code As String, ByVal apprId As String) As String
            Dim encrypt = Server.UrlEncode(AgapeEncryption.AgapeEncrypt.Encrypt(Code & ";" & apprId))

            Dim rtn = "<div style=""width: 100%; text-align: center; font-size: x-large;""><a href='" & Request.Url.Scheme & "://" & Request.Url.Authority & Request.ApplicationPath & "DesktopModules/AgapeConnect/mpdCalc/Approve.aspx?m=" & encrypt & "' target='_blank'>" & "Approve" & "</a>"
            Dim returnURL = NavigateURL() & "?sb=" & Request.QueryString("sb")

            rtn &= "      <a href='" & NavigateURL(PortalSettings.LoginTabId) & "?returnurl=" & Server.UrlEncode(returnURL) & "' target='_blank'>" & "Login" & "</a></div>"
            Return rtn
        End Function

        Private Function GetDetailTable(ByVal theBud As AP_mpdCalc_StaffBudget) As String
            Dim dt As New Date(Left(theBud.BudgetPeriodStart, 4), Right(theBud.BudgetPeriodStart, 2), 1)

            Dim rtn As String = "<div style='float:left; font-style: italic; color: #AAC;'>" & dt.ToString("MMM yyyy") & "</div><div style='clear: both;' />"
            rtn &= "<table style='width: 100%; margin: 10px; text-align: left;'>"
            rtn &= "<tr><th style='text-align: left;'>Name</th><th style='text-align: left;'>Monthly</th><th style='text-align: left;'>Yearly</th></tr>"

            For Each row In theBud.AP_mpdCalc_Answers.Where(Function(c) c.Value <> 0).OrderBy(Function(c) c.AP_mpdCalc_Question.AP_mpdCalc_Section.Number).ThenBy(Function(c) c.AP_mpdCalc_Question.QuestionNumber)
                rtn &= "<tr><td>" & row.Name & "</td><td>" & row.Value.ToString() & "</td><td>" & (row.Value * 12).ToString() & "</td></tr>"
            Next

            rtn &= "<tr><td  style='text-align: right; font-weight: bold;'> Total Budget:</td><td>" & theBud.TotalBudget.Value.ToString("f0") & "</td><td></td></tr>"
            If theBud.ToRaise <> theBud.TotalBudget.Value Then
                rtn &= "<tr><td  style='text-align: right;'> I am responsible to Raise:</td><td>" & theBud.ToRaise.ToString("f0") & "</td><td></td></tr>"

            End If

            rtn &= "</table>"
            Return rtn

        End Function

        Private Sub AddBudgetFromPeriod(ByVal RC As String, ByVal Account As String, ByVal FiscalYear As String, ByVal Value As Double, ByVal FromPeriod As Integer, ByVal ToPeriod As Integer)
            Dim b As New Budget.BudgetDataContext
            Dim q = From c In b.AP_Budget_Summaries Where c.Portalid = PortalId And c.RC = RC And c.Account = Account And c.FiscalYear = FiscalYear

            If q.Count > 0 Then

                q.First.Changed = True
                q.First.Error = False
                q.First.ErrorMessage = "From MPD Calculator"
                q.First.LastUpdated = Now

                q.First.P1 = CDbl(IIf(FromPeriod <= 1 And ToPeriod >= 1, Value, 0))
                q.First.P2 = CDbl(IIf(FromPeriod <= 2 And ToPeriod >= 2, Value, 0))
                q.First.P3 = CDbl(IIf(FromPeriod <= 3 And ToPeriod >= 3, Value, 0))
                q.First.P4 = CDbl(IIf(FromPeriod <= 4 And ToPeriod >= 4, Value, 0))
                q.First.P5 = CDbl(IIf(FromPeriod <= 5 And ToPeriod >= 5, Value, 0))
                q.First.P6 = CDbl(IIf(FromPeriod <= 6 And ToPeriod >= 6, Value, 0))
                q.First.P7 = CDbl(IIf(FromPeriod <= 7 And ToPeriod >= 7, Value, 0))
                q.First.P8 = CDbl(IIf(FromPeriod <= 8 And ToPeriod >= 8, Value, 0))
                q.First.P9 = CDbl(IIf(FromPeriod <= 9 And ToPeriod >= 9, Value, 0))
                q.First.P10 = CDbl(IIf(FromPeriod <= 10 And ToPeriod >= 10, Value, 0))
                q.First.P11 = CDbl(IIf(FromPeriod <= 11 And ToPeriod >= 11, Value, 0))
                q.First.P12 = CDbl(IIf(FromPeriod <= 12 And ToPeriod >= 12, Value, 0))

            ElseIf Value <> 0 Then
                Dim insert As New Budget.AP_Budget_Summary
                insert.Portalid = PortalId
                insert.Account = Account
                insert.Changed = True
                insert.Error = False
                insert.ErrorMessage = "From MPD Calculator"
                insert.LastUpdated = Now
                insert.RC = RC
                insert.FiscalYear = FiscalYear

                insert.P1 = CDbl(IIf(FromPeriod <= 1 And ToPeriod >= 1, Value, 0.0))
                insert.P2 = CDbl(IIf(FromPeriod <= 2 And ToPeriod >= 2, Value, 0))
                insert.P3 = CDbl(IIf(FromPeriod <= 3 And ToPeriod >= 3, Value, 0))
                insert.P4 = CDbl(IIf(FromPeriod <= 4 And ToPeriod >= 4, Value, 0))
                insert.P5 = CDbl(IIf(FromPeriod <= 5 And ToPeriod >= 5, Value, 0))
                insert.P6 = CDbl(IIf(FromPeriod <= 6 And ToPeriod >= 6, Value, 0))
                insert.P7 = CDbl(IIf(FromPeriod <= 7 And ToPeriod >= 7, Value, 0))
                insert.P8 = CDbl(IIf(FromPeriod <= 8 And ToPeriod >= 8, Value, 0))
                insert.P9 = CDbl(IIf(FromPeriod <= 9 And ToPeriod >= 9, Value, 0))
                insert.P10 = CDbl(IIf(FromPeriod <= 10 And ToPeriod >= 10, Value, 0))
                insert.P11 = CDbl(IIf(FromPeriod <= 11 And ToPeriod >= 11, Value, 0))
                insert.P12 = CDbl(IIf(FromPeriod <= 12 And ToPeriod >= 12, Value, 0))

                b.AP_Budget_Summaries.InsertOnSubmit(insert)

            End If
            b.SubmitChanges()
        End Sub

        Private Function getFiscalYear(ByVal CalendarString As String, ByVal FirstFiscalMonth As String) As Integer
            If CInt(Right(CalendarString, 2)) < FirstFiscalMonth Then
                Return CInt(Left(CalendarString, 4)) - 1
            Else
                Return Left(CalendarString, 4)
            End If
        End Function
        Private Function GetFiscalPeriod(ByVal CalendarString As String, ByVal FirstFiscalMonth As String) As Integer

            Dim tmp = CInt(Right(CalendarString, 2)) - ((FirstFiscalMonth) - 1)
            If tmp < 1 Then
                Return tmp + 12
            Else
                Return tmp
            End If

        End Function

        Private Sub AddToBudget(ByRef budgetValues As Dictionary(Of String, Double), ByVal AccountCode As String, ByVal GrossAmount As Double)
            If budgetValues.ContainsKey(AccountCode) Then
                budgetValues(AccountCode) += GrossAmount
            Else
                budgetValues.Add(AccountCode, GrossAmount)
            End If
        End Sub

        Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
            SaveBudget(StaffRmb.RmbStatus.Submitted)

        End Sub
        Public Function GetMaxQuestionNumber(ByVal questions As System.Data.Linq.EntitySet(Of MPD.AP_mpdCalc_Question)) As Integer
            If questions.Count = 0 Then
                Return 1
            Else
                Return questions.Max(Function(c) c.QuestionNumber) + 1
            End If
        End Function

        Protected Sub btnInsertSection_Click(sender As Object, e As EventArgs) Handles btnInsertSection.Click
            Dim d As New MPD.MPDDataContext

            Dim def = From c In d.AP_mpdCalc_Definitions Where c.TabModuleId = TabModuleId And c.PortalId = PortalId
            If def.Count > 0 Then
                Dim i As Integer = 1
                For Each row In def.First.AP_mpdCalc_Sections.OrderBy(Function(c) c.Number)
                    If ddlInsertOrder.SelectedValue = i Then
                        'insert

                        i += 1
                    End If
                    row.Number = i
                    i += 1
                Next
                Dim insert As New MPD.AP_mpdCalc_Section
                insert.mpdDefId = def.First.mpdDefId
                insert.Name = tbInsertSectionName.Text
                insert.TotalMode = "monthly"
                insert.Number = ddlInsertOrder.SelectedValue
                d.AP_mpdCalc_Sections.InsertOnSubmit(insert)
                d.SubmitChanges()
                ReloadPage()
            End If

        End Sub
        Private Sub ReloadPage()
            Response.Redirect(EditUrl("mpdCalc") & "?sb=" & StaffBudId)
        End Sub

        Protected Sub rpSections_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles rpSections.ItemCommand
            If e.CommandName = "EditSectionTitle" Then

                Dim d As New MPD.MPDDataContext
                Dim q = From c In d.AP_mpdCalc_Sections Where c.SectionId = CInt(e.CommandArgument) And c.AP_mpdCalc_Definition.PortalId = PortalId

                If q.Count > 0 Then
                    Dim Title As TextBox = rpSections.Items(e.Item.ItemIndex).FindControl("tbSectionName")
                    q.First.Name = Title.Text
                    d.SubmitChanges()
                    ReloadPage()
                End If
            ElseIf e.CommandName = "UP" Then
                Dim d As New MPD.MPDDataContext

                Dim q = From c In d.AP_mpdCalc_Sections Where c.SectionId = CInt(e.CommandArgument) And c.AP_mpdCalc_Definition.PortalId = PortalId

                If q.Count > 0 Then
                    Dim i As Integer = 1
                    Dim NewViewOrder = Math.Max(q.First.Number - 1, 1)

                    For Each row In q.First.AP_mpdCalc_Definition.AP_mpdCalc_Sections.Where(Function(c) c.SectionId <> q.First.SectionId).OrderBy(Function(c) c.Number)
                        If NewViewOrder = i Then
                            'skip if current index

                            i += 1
                        End If
                        row.Number = i
                        i += 1
                    Next
                    q.First.Number = NewViewOrder

                    d.SubmitChanges()
                    ReloadPage()
                End If

            ElseIf e.CommandName = "DOWN" Then
                Dim d As New MPD.MPDDataContext

                Dim q = From c In d.AP_mpdCalc_Sections Where c.SectionId = CInt(e.CommandArgument) And c.AP_mpdCalc_Definition.PortalId = PortalId

                If q.Count > 0 Then
                    Dim i As Integer = 1
                    Dim NewViewOrder = Math.Min(q.First.Number + 1, q.First.AP_mpdCalc_Definition.AP_mpdCalc_Sections.Max(Function(c) c.Number))

                    For Each row In q.First.AP_mpdCalc_Definition.AP_mpdCalc_Sections.Where(Function(c) c.SectionId <> q.First.SectionId).OrderBy(Function(c) c.Number)
                        If NewViewOrder = i Then
                            'skip if current index

                            i += 1
                        End If
                        row.Number = i
                        i += 1
                    Next

                    q.First.Number = NewViewOrder

                    d.SubmitChanges()
                    ReloadPage()

                End If
            ElseIf e.CommandName = "DeleteSection" Then
                Dim d As New MPD.MPDDataContext

                Dim q = From c In d.AP_mpdCalc_Sections Where c.SectionId = CInt(e.CommandArgument) And c.AP_mpdCalc_Definition.PortalId = PortalId

                Dim defid = q.First.mpdDefId

                d.AP_mpdCalc_Sections.DeleteAllOnSubmit(q)
                d.SubmitChanges()

                Dim i As Integer = 1

                For Each row In d.AP_mpdCalc_Sections.Where(Function(c) c.mpdDefId = defid).OrderBy(Function(c) c.Number)

                    row.Number = i
                    i += 1
                Next

                d.SubmitChanges()

                ReloadPage()
            End If
        End Sub

        Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
            SaveBudget()
        End Sub

        Protected Sub btnApprove_Click(sender As Object, e As EventArgs) Handles btnApprove.Click
            SaveBudget(StaffRmb.RmbStatus.Approved)
        End Sub

        Protected Sub btnProcess_Click(sender As Object, e As EventArgs) Handles btnProcess.Click
            SaveBudget(StaffRmb.RmbStatus.Processed)

        End Sub

        Protected Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
            SaveBudget(StaffRmb.RmbStatus.Cancelled)
        End Sub

        Protected Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
            Response.Redirect(NavigateURL())
        End Sub

    End Class
End Namespace


text:
#=============================================================================
# Copyright 2009 Kitware, Inc.
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
# (To distribute this file outside of CMake, substitute the full
#  License text for the above reference.)

# This file is included in CMakeSystemSpecificInformation.cmake if
# the Eclipse CDT4 extra generator has been selected.

FIND_PROGRAM(CMAKE_ECLIPSE_EXECUTABLE NAMES eclipse DOC "The Eclipse executable")

# The Eclipse generator needs to know the standard include path
# so that Eclipse ca find the headers at runtime and parsing etc. works better
# This is done here by actually running gcc with the options so it prints its
# system include directories, which are parsed then and stored in the cache.
MACRO(_DETERMINE_GCC_SYSTEM_INCLUDE_DIRS _lang _resultIncludeDirs _resultDefines)
  SET(${_resultIncludeDirs})
  SET(_gccOutput)
  FILE(WRITE "${CMAKE_BINARY_DIR}/CMakeFiles/dummy" "\n" )
  EXECUTE_PROCESS(COMMAND ${CMAKE_C_COMPILER} -v -E -x ${_lang} -dD dummy
                  WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/CMakeFiles
                  ERROR_VARIABLE _gccOutput
                  OUTPUT_VARIABLE _gccStdout )
  FILE(REMOVE "${CMAKE_BINARY_DIR}/CMakeFiles/dummy")

  # First find the system include dirs:
  IF( "${_gccOutput}" MATCHES "> search starts here[^\n]+\n *(.+) *\n *End of (search) list" )

    # split the output into lines and then remove leading and trailing spaces from each of them:
    STRING(REGEX MATCHALL "[^\n]+\n" _includeLines "${CMAKE_MATCH_1}")
    FOREACH(nextLine ${_includeLines})
      STRING(STRIP "${nextLine}" _includePath)
      LIST(APPEND ${_resultIncludeDirs} "${_includePath}")
    ENDFOREACH(nextLine)

  ENDIF( "${_gccOutput}" MATCHES "> search starts here[^\n]+\n *(.+) *\n *End of (search) list" )

  # now find the builtin macros:
  STRING(REGEX MATCHALL "#define[^\n]+\n" _defineLines "${_gccStdout}")
# A few example lines which the regexp below has to match properly:
#  #define   MAX(a,b) ((a) > (b) ? (a) : (b))
#  #define __fastcall __attribute__((__fastcall__))
#  #define   FOO (23)
#  #define __UINTMAX_TYPE__ long long unsigned int
#  #define __UINTMAX_TYPE__ long long unsigned int
#  #define __i386__  1

  FOREACH(nextLine ${_defineLines})
    STRING(REGEX MATCH "^#define +([A-Za-z_][A-Za-z0-9_]*)(\\([^\\)]+\\))? +(.+) *$" _dummy "${nextLine}")
    SET(_name "${CMAKE_MATCH_1}${CMAKE_MATCH_2}")
    STRING(STRIP "${CMAKE_MATCH_3}" _value)
    #MESSAGE(STATUS "m1: -${CMAKE_MATCH_1}- m2: -${CMAKE_MATCH_2}- m3: -${CMAKE_MATCH_3}-")

    LIST(APPEND ${_resultDefines} "${_name}")
    IF(_value)
      LIST(APPEND ${_resultDefines} "${_value}")
    ELSE()
      LIST(APPEND ${_resultDefines} " ")
    ENDIF()
  ENDFOREACH(nextLine)

ENDMACRO(_DETERMINE_GCC_SYSTEM_INCLUDE_DIRS _lang)

# Save the current LC_ALL, LC_MESSAGES, and LANG environment variables and set them
# to "C" that way GCC's "search starts here" text is in English and we can grok it.
SET(_orig_lc_all      $ENV{LC_ALL})
SET(_orig_lc_messages $ENV{LC_MESSAGES})
SET(_orig_lang        $ENV{LANG})
IF(_orig_lc_all)
  SET(ENV{LC_ALL}      C)
ENDIF(_orig_lc_all)
IF(_orig_lc_messages)
  SET(ENV{LC_MESSAGES} C)
ENDIF(_orig_lc_messages)
IF(_orig_lang)
  SET(ENV{LANG}        C)
ENDIF(_orig_lang)

# Now check for C, works for gcc and Intel compiler at least
IF (NOT CMAKE_ECLIPSE_C_SYSTEM_INCLUDE_DIRS)
  IF ("${CMAKE_C_COMPILER_ID}" MATCHES GNU  OR  "${CMAKE_C_COMPILER_ID}" MATCHES Intel)
    _DETERMINE_GCC_SYSTEM_INCLUDE_DIRS(c _dirs _defines)
    SET(CMAKE_ECLIPSE_C_SYSTEM_INCLUDE_DIRS "${_dirs}" CACHE INTERNAL "C compiler system include directories")
    SET(CMAKE_ECLIPSE_C_SYSTEM_DEFINED_MACROS "${_defines}" CACHE INTERNAL "C compiler system defined macros")
  ENDIF ("${CMAKE_C_COMPILER_ID}" MATCHES GNU  OR  "${CMAKE_C_COMPILER_ID}" MATCHES Intel)
ENDIF (NOT CMAKE_ECLIPSE_C_SYSTEM_INCLUDE_DIRS)

# And now the same for C++
IF (NOT CMAKE_ECLIPSE_CXX_SYSTEM_INCLUDE_DIRS)
  IF ("${CMAKE_CXX_COMPILER_ID}" MATCHES GNU  OR  "${CMAKE_CXX_COMPILER_ID}" MATCHES Intel)
    _DETERMINE_GCC_SYSTEM_INCLUDE_DIRS(c++ _dirs _defines)
    SET(CMAKE_ECLIPSE_CXX_SYSTEM_INCLUDE_DIRS "${_dirs}" CACHE INTERNAL "CXX compiler system include directories")
    SET(CMAKE_ECLIPSE_CXX_SYSTEM_DEFINED_MACROS "${_defines}" CACHE INTERNAL "CXX compiler system defined macros")
  ENDIF ("${CMAKE_CXX_COMPILER_ID}" MATCHES GNU  OR  "${CMAKE_CXX_COMPILER_ID}" MATCHES Intel)
ENDIF (NOT CMAKE_ECLIPSE_CXX_SYSTEM_INCLUDE_DIRS)

# Restore original LC_ALL, LC_MESSAGES, and LANG
IF(_orig_lc_all)
  SET(ENV{LC_ALL}      ${_orig_lc_all})
ENDIF(_orig_lc_all)
IF(_orig_lc_messages)
  SET(ENV{LC_MESSAGES} ${_orig_lc_messages})
ENDIF(_orig_lc_messages)
IF(_orig_lang)
  SET(ENV{LANG}        ${_orig_lang})
ENDIF(_orig_lang)


text:
{% extends "pretixcontrol/base.html" %}
{% load i18n %}
{% load bootstrap3 %}
{% block title %}{% trans "Add a two-factor authentication device" %}{% endblock %}
{% block content %}

{% trans "Add a two-factor authentication device" %}

    <form action="" method="post" class="form-horizontal">
        {% csrf_token %}
        {% bootstrap_form_errors form %}
        {% bootstrap_field form.name layout='horizontal' %}
        {% bootstrap_field form.devicetype layout='horizontal' %}

            <button type="submit" class="btn btn-primary btn-save">
                {% trans "Continue" %}
            </button>

    </form>
{% endblock %}


text:
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings

from organizations.forms import OrganizationForm, OrganizationUserForm
from organizations.models import Organization
from organizations.tests.utils import request_factory_login

@override_settings(USE_TZ=True)
class OrgFormTests(TestCase):

    fixtures = ['users.json', 'orgs.json']

    def setUp(self):
        self.factory = RequestFactory()
        self.org = Organization.objects.get(name="Nirvana")
        self.admin = self.org.organization_users.get(user__username="krist")
        self.owner = self.org.organization_users.get(user__username="kurt")

    def test_admin_edits_org(self):
        user = self.admin.user
        request = request_factory_login(self.factory, user)
        form = OrganizationForm(request, instance=self.org, data={
            'name': self.org.name, 'slug': self.org.slug,
            'owner': self.owner.id})
        self.assertTrue(form.is_valid())
        form = OrganizationForm(request, instance=self.org, data={
            'name': self.org.name, 'slug': self.org.slug,
            'owner': self.admin.id})
        self.assertFalse(form.is_valid())

    def test_owner_edits_org(self):
        user = self.owner.user
        request = request_factory_login(self.factory, user)
        form = OrganizationForm(request, instance=self.org, data={
            'name': self.org.name, 'slug': self.org.slug,
            'owner': self.owner.id})
        self.assertTrue(form.is_valid())
        form = OrganizationForm(request, instance=self.org, data={
            'name': self.org.name, 'slug': self.org.slug,
            'owner': self.admin.id})
        self.assertTrue(form.is_valid())
        form.save()
        self.assertEqual(self.org.owner.organization_user, self.admin)

    def test_edit_owner_user(self):
        form = OrganizationUserForm(instance=self.owner,
                data={'is_admin': True})
        self.assertTrue(form.is_valid())
        form = OrganizationUserForm(instance=self.owner,
                data={'is_admin': False})
        self.assertFalse(form.is_valid())

    def test_save_org_form(self):
        request = request_factory_login(self.factory, self.owner.user)
        form = OrganizationForm(request, instance=self.org, data={
                'name': self.org.name, 'slug': self.org.slug,
                'owner': self.owner.id})
        self.assertTrue(form.is_valid())
        form.save()

    def test_save_user_form(self):
        form = OrganizationUserForm(instance=self.owner,
                data={'is_admin': True})
        self.assertTrue(form.is_valid())
        form.save()


text:
import React from 'react';
import { connect } from 'react-redux';
import Answers from './Answers';
import Dog_information from './dog_information';
import { browserHistory } from 'react-router';
import * as actions from '../actions';

function sortArray(a, b) {
  if (a.answerQuestion  b.answerQuestion)
    return 1;
  return 0;
}

class App extends React.Component {

	constructor() {
		super();
		this.state = {
			//updateAnswer: []
		}
	}

	componentDidMount() {
		this.props.dispatch(actions.fetchQuiz());
	}

	_handleChange = (e) => {
		console.log(e.target, 'here')
		this.setState({
			[e.target.name]: e.target.value
		})

	}

	_handleFormSubmit = e => {
		e.preventDefault();
		console.log(this.props, "this.props");
		console.log('this.state', this.state);
		this.props.dispatch(actions.submitResults(this.state));
	}

	render() {
		if (this.props.results) return <Dog_information />
		return (

				<form onSubmit={this._handleFormSubmit}>
					<Answers ref="name" onChange={this._handleChange}/>
					<button className="btn-submit" type="submit">Submit</button>
				</form>

		);
	}
};

const mapStateToProps = function(state, props) {
	return {
		results: state.results
	}
}

export default connect(mapStateToProps)(App);


text:
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug?
assignees: bnadlerjr

---

<!--- The GitHub Issue tracker is **ONLY** used for reporting bugs and tracking code changes. Please use StackOverflow or GitHub Discussions for questions or support issues. New features should be discussed on GitHub Discussions **before** creating an issue. For a roadmap of upcoming features, check the GitHub Projects page. --->

<!--- Make sure to add **all the information needed to understand the bug** so that someone can help. If the info is missing we'll add the 'Needs more information' label and close the issue until there is enough information. --->

**Describe the bug**
<!--- A clear and concise description of what the bug is. --->

**To Reproduce**
<!--- Provide a link to a live example, or an unambiguous set of steps to reproduce this bug. Include code to reproduce, if relevant. --->

**Expected behavior**
<!--- A clear and concise description of what you expected to happen. --->

**Screenshots**
<!--- If applicable, add screenshots to help explain your problem. --->

**Environment (please complete the following information):**
 - Hoboken Version: [e.g. 0.8.0]
 - Ruby Version: [e.g. 2.7]
 - OS and Version: [e.g. macOS Big Sur, Windows 10]
 - Browser and Version (if applicable): [e.g. chrome, safari]

**Additional context**
<!--- Add any other context about the problem here. --->


text:
package org.apache.maven.plugin.checkstyle;

import org.apache.maven.plugin.checkstyle.exec.CheckstyleExecutorRequest;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.maven.reporting.MavenReportException;

import java.util.List;

/**
 * A reporting task that performs Checkstyle analysis and generates an aggregate
 * HTML report on the violations that Checkstyle finds in a multi-module reactor
 * build.
 *
 * @version $Id$
 */
@Mojo( name = "checkstyle-aggregate", aggregator = true, requiresDependencyResolution = ResolutionScope.COMPILE,
       threadSafe = true )
public class CheckstyleAggregateReport
    extends AbstractCheckstyleReport
{
    /**
     * The projects in the reactor for aggregation report.
     *
     * @since 2.8
     */
    @Parameter( property = "reactorProjects", readonly = true )
    private List<MavenProject> reactorProjects;

    /** {@inheritDoc} */
    protected MavenProject getProject()
    {
        return project;
    }

    /**
     * {@inheritDoc}
     */
    protected CheckstyleExecutorRequest createRequest()
            throws MavenReportException
    {
        CheckstyleExecutorRequest request = new CheckstyleExecutorRequest();
        request.setAggregate( true )
            .setReactorProjects( reactorProjects )
            .setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput )
            .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes )
            .setIncludeResources( includeResources )
            .setIncludeTestResources( includeTestResources )
            .setResourceIncludes( resourceIncludes )
            .setResourceExcludes( resourceExcludes )
            .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() )
            .setLog( getLog() ).setProject( project ).setSourceDirectories( getSourceDirectories() )
            .setResources( resources ).setTestResources( testResources )
            .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation )
            .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( configLocation )
            .setPropertyExpansion( propertyExpansion ).setHeaderLocation( headerLocation )
            .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression )
            .setEncoding( encoding ).setPropertiesLocation( propertiesLocation );
        return request;
    }

    /** {@inheritDoc} */
    public String getOutputName()
    {
        return "checkstyle-aggregate";
    }

    /** {@inheritDoc} */
    public boolean canGenerateReport()
    {
        // TODO: would be good to scan the files here
        return !skip && project.isExecutionRoot() && reactorProjects.size() > 1;
    }
}


text:
/* FreeRTOS kernel includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "timers.h"
#include "semphr.h"

/* Freescale includes. */
#include "fsl_device_registers.h"
#include "fsl_debug_console.h"
#include "board.h"

#include "trcBase.h"

#include "pin_mux.h"
#include "clock_config.h"
/*******************************************************************************
 * Definitions
 ******************************************************************************/

#define APP_SYSVIEW_APP_NAME    "FRDMK66F System Viewer Demo"
#define APP_SYSVIEW_DEVICE_NAME "Cortex-M4"
#define APP_SYSVIEW_RAM_BASE    (0x1FFF0000)

/* Task priorities. */
#define FIRST_TASK_PRIORITY     (configMAX_PRIORITIES - 1)
#define SECOND_TASK_PRIORITY    (configMAX_PRIORITIES - 2)

/*******************************************************************************
 * Prototypes
 ******************************************************************************/
static void first_task(void *pvParameters);
static void second_task(void *pvParameters);

#define APP_DELAY 100

/*******************************************************************************
 * Code
 ******************************************************************************/

/*!
 * @brief Main function
 */
int main(void)
{
    /* Init board hardware. */
    BOARD_InitPins();
    BOARD_BootClockRUN();
    BOARD_InitDebugConsole();

    vTraceInitTraceData();

    if (!uiTraceStart())
    {
        vTraceConsoleMessage("Could not start recorder!");
    }

    xTaskCreate(first_task, "first_task", configMINIMAL_STACK_SIZE, NULL, FIRST_TASK_PRIORITY, NULL);
    vTaskStartScheduler();
    while(1);
}

/*!
 * @brief First task, higher priority.
 */
static void first_task(void *pvParameters)
{
    traceLabel consoleLabel;
    consoleLabel = xTraceOpenLabel("Messages");

    xTaskCreate(second_task, "second_task", configMINIMAL_STACK_SIZE, NULL, SECOND_TASK_PRIORITY, NULL);

    PRINTF("Please fill Percepio \"Memory Region\" options: \r\n");
    PRINTF("Start address: 0x%x \r\n", RecorderDataPtr);
    PRINTF("Bytes to read: 0x%x \r\n", sizeof(*RecorderDataPtr));

    /* dummy code, print counter and delay */
    for (int counter = 0; ; counter++)
    {
        vTracePrintF(consoleLabel, "first task counter: %d \n", counter++);
        vTaskDelay(APP_DELAY);
    }
}

/*!
 * @brief Second task, lower priority.
 */
static void second_task(void *pvParameters)
{
    traceLabel consoleLabel;

    consoleLabel = xTraceOpenLabel("Messages");
    while(1)
    {
        /* dummy code, notify HOST when int16 underflow */
        for (uint16_t j = (uint16_t)-1; ; j--)
        {
            if (j == 0)
            {
                vTracePrintF(consoleLabel, "second task int underflow");
            }
            __NOP();
        }
    }
}


text:
React Native step counter for iOS and Android.

* iOS uses the HealthKit API.
* Android uses the Google Fit API.

##  Built with :

* [react-native](https://github.com/facebook/react-native)
* [react-native-circular-progress](https://github.com/bgryszko/react-native-circular-progress)
* [react-native-linear-gradient](https://github.com/brentvatne/react-native-linear-gradient)
* [react-native-router-flux](https://github.com/aksonov/react-native-router-flux)
* [react-native-vector-icons](https://github.com/oblador/react-native-vector-icons)
* [react-redux](https://github.com/reactjs/react-redux)

<img src="./images/ios-app-screenshot.png" width=400>