text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

if (!defined('MOODLE_INTERNAL')) {
    die('Direct access to this script is forbidden.');    //  It must be included from a Moodle page.
}

require_once($CFG->dirroot.'/lib/formslib.php');

/**
 * Class user_edit_forum_form.
 *
 * @copyright 1999 Martin Dougiamas  http://dougiamas.com
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class user_edit_forum_form extends moodleform {

    /**
     * Define the form.
     */
    public function definition () {
        global $CFG, $COURSE;

        $mform = $this->_form;

        $choices = array();
        $choices['0'] = get_string('emaildigestoff');
        $choices['1'] = get_string('emaildigestcomplete');
        $choices['2'] = get_string('emaildigestsubjects');
        $mform->addElement('select', 'maildigest', get_string('emaildigest'), $choices);
        $mform->setDefault('maildigest', core_user::get_property_default('maildigest'));
        $mform->addHelpButton('maildigest', 'emaildigest');

        $choices = array();
        $choices['1'] = get_string('autosubscribeyes');
        $choices['0'] = get_string('autosubscribeno');
        $mform->addElement('select', 'autosubscribe', get_string('autosubscribe'), $choices);
        $mform->setDefault('autosubscribe', core_user::get_property_default('autosubscribe'));

        if (!empty($CFG->forum_trackreadposts)) {
            $mform->addElement('header', 'trackreadposts', get_string('trackreadposts_header', 'mod_forum'));
            $choices = array();
            $choices['0'] = get_string('trackforumsno');
            $choices['1'] = get_string('trackforumsyes');
            $mform->addElement('select', 'trackforums', get_string('trackforums'), $choices);
            $mform->setDefault('trackforums', core_user::get_property_default('trackforums'));

            $choices = [
                1   => get_string('markasreadonnotificationyes', 'mod_forum'),
                0   => get_string('markasreadonnotificationno', 'mod_forum'),
            ];
            $mform->addElement('select', 'markasreadonnotification', get_string('markasreadonnotification', 'mod_forum'), $choices);
            $mform->addHelpButton('markasreadonnotification', 'markasreadonnotification', 'mod_forum');
            $mform->disabledIf('markasreadonnotification', 'trackforums', 'eq', "0");
            $mform->setDefault('markasreadonnotification', 1);
        }

        // Add some extra hidden fields.
        $mform->addElement('hidden', 'id');
        $mform->setType('id', PARAM_INT);
        $mform->addElement('hidden', 'course', $COURSE->id);
        $mform->setType('course', PARAM_INT);

        $this->add_action_buttons(true, get_string('savechanges'));
    }
}


text:
class Timer
{
public:
  void start();
  void finish();

  double elapsedTime() const;

private:
  clock_t m_beginTime;
  double m_elapsedTime;
};

// Inlines methods for Timer:
// --------------------------

#endif  // TIMER_H

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ReferenceMap (Sigar API)
</TITLE>

<META NAME="date" CONTENT="2010-04-28">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.hyperic.sigar.util

Class ReferenceMap

java.lang.Object
  java.util.AbstractMap
      org.hyperic.sigar.util.ReferenceMap

All Implemented Interfaces:
java.util.Map

Direct Known Subclasses:
WeakReferenceMap

public class ReferenceMap
extends java.util.AbstractMap

Nested Class Summary

protected static interface
ReferenceMap.MapReference

protected static class
ReferenceMap.SoftValue

protected static class
ReferenceMap.WeakValue

Nested classes/interfaces inherited from class java.util.AbstractMap

java.util.AbstractMap.SimpleEntry<K,V>, java.util.AbstractMap.SimpleImmutableEntry<K,V>

Nested classes/interfaces inherited from interface java.util.Map

java.util.Map.Entry<K,V>

Field Summary

protected  java.util.Map
map

protected  java.lang.ref.ReferenceQueue
queue

Constructor Summary

ReferenceMap()

ReferenceMap(java.util.Map map)

Method Summary

 void
clear()

 java.util.Set
entrySet()

 java.lang.Object
get(java.lang.Object key)

static java.util.Map
newInstance()

static java.util.Map
newInstance(java.util.Map map)

protected  void
poll()

 java.lang.Object
put(java.lang.Object key,
    java.lang.Object value)

 java.lang.Object
remove(java.lang.Object key)

 int
size()

static java.util.Map
synchronizedMap()

Methods inherited from class java.util.AbstractMap

clone, containsKey, containsValue, equals, hashCode, isEmpty, keySet, putAll, toString, values

Methods inherited from class java.lang.Object

finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

queue

protected java.lang.ref.ReferenceQueue queue

map

protected java.util.Map map

Constructor Detail

ReferenceMap

public ReferenceMap()

ReferenceMap

public ReferenceMap(java.util.Map map)

Method Detail

synchronizedMap

public static java.util.Map synchronizedMap()

newInstance

public static java.util.Map newInstance()

newInstance

public static java.util.Map newInstance(java.util.Map map)

get

public java.lang.Object get(java.lang.Object key)

Specified by:
get in interface java.util.Map
Overrides:
get in class java.util.AbstractMap

put

public java.lang.Object put(java.lang.Object key,
                            java.lang.Object value)

Specified by:
put in interface java.util.Map
Overrides:
put in class java.util.AbstractMap

remove

public java.lang.Object remove(java.lang.Object key)

Specified by:
remove in interface java.util.Map
Overrides:
remove in class java.util.AbstractMap

clear

public void clear()

Specified by:
clear in interface java.util.Map
Overrides:
clear in class java.util.AbstractMap

size

public int size()

Specified by:
size in interface java.util.Map
Overrides:
size in class java.util.AbstractMap

entrySet

public java.util.Set entrySet()

Specified by:
entrySet in interface java.util.Map
Specified by:
entrySet in class java.util.AbstractMap

poll

protected void poll()

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright ? 2004-2009 Hyperic. All Rights Reserved.


text:
package pl.morecraft.dev.datagrammer.commands;

import pl.morecraft.dev.datagrammer.engine.Command;
import pl.morecraft.dev.datagrammer.misc.Consoler;

import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Exit extends Command {

    @SuppressWarnings("Duplicates")
    @Override
    public void setup() {
        addAlias("exit", true);
        addAlias("e", true);
        setArgsCount(0);
        setArgsInfo("");
        setShortInfo("Exit program");
        mustBeBound(false);
        mustBeConnected(false);
        mustBeNotClosed(false);
        mustBeNotNull(false);
    }

    @Override
    public DatagramSocket execute(DatagramSocket socket, Consoler out) throws UnknownHostException, SocketException {
        out.println("Exiting...", false);
        System.exit(0);
        return socket;
    }

}


text:
"""
size_compare.py

Compare the compiled size of two revisions.

Usage: size_compare.py [-h|--help] [target_ref] [base_ref]

if no arguments are passed, compares HEAD to master.
if just `target_ref` is set, compares HEAD to `target_ref`
if `base_ref` is set, compares `target_ref` to `base_ref`."""

import subprocess
import sys
import os

RUST_TARGET_NAME = 'xi-core'

def main():
    if not os.path.exists('./target'):
        print("no target directory found, are you running this in \
              xi-editor/rust?")
        return 1

    args = sys.argv[1:]
    if len(args) > 2 or len(args) == 1 and args[0] in ("-h", "--help", "help"):
        return print_help()

    base_rev = "master"
    cur_rev = "HEAD"

    if len(args) == 1:
        base_rev = args[0]
    if len(args) == 2:
        cur_rev = args[1]

    if not working_directory_is_clean():
        print("Your working directory has unsaved changes. Stash or commit \
              your changes and try again")
        return 2

    return compare_revs(base_rev, cur_rev)

def print_help():
    print(__doc__)
    return 2

def resolve_rev(rev_id):
    """Given an arbitrary git revision id, returns the commit's hash"""
    try:
        output = subprocess.check_output("git rev-parse {}".format(rev_id), shell=True)
        return output.decode('utf-8').strip()
    except subprocess.CalledProcessError as err:
        print("failed to resolve rev_id {}: {}".format(rev_id, err))
        return None

def compare_revs(base_rev, cur_rev):
    base_sha = resolve_rev(base_rev)
    cur_sha = resolve_rev(cur_rev)

    if base_sha is None:
        print("could not resolve ref '{}'".format(base_rev))
        return print_help()
    if cur_sha is None:
        print("could not resolve ref '{}'".format(cur_rev))
        return print_help()
    if base_sha == cur_sha:
        print("refs are the same: {}, {}".format(base_rev, cur_rev))
        return print_help()

    cur_size = compile_size_for_commit(cur_sha)
    base_size = compile_size_for_commit(base_sha)

    base_str = base_rev + " " + base_sha[:8]
    cur_str = cur_rev + " " + cur_sha[:8]
    print_compare(base_str, cur_str, base_size, cur_size)

def print_compare(base_str, cur_str, base_size, cur_size):
    size_delta = base_size - cur_size
    delta_change = "smaller" if size_delta > 0 else "bigger"
    pad_size = max(len(base_str), len(cur_str)) + 4
    fmt_string = '{:<' + str(pad_size) + '}{}'
    print(fmt_string.format(base_str, sizeof_fmt(base_size)))
    print(fmt_string.format(cur_str, sizeof_fmt(cur_size)))
    if base_size != cur_size:
        print("{} is {} {} than {}".format(cur_str, sizeof_fmt(abs(size_delta)), delta_change, base_str))
    else:
        print("revisions are equal")

# https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.3f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

def compile_size_for_commit(sha):
    subprocess.check_output("git checkout {}".format(sha), shell=True)
    try:
        subprocess.check_output("cargo build --release".format(sha), shell=True)
    except subprocess.CalledProcessError as err:
        return "{} exited with {}: {}".format(sha, err.returncode, err.output or "")
    ls_output = subprocess.check_output("ls -l target/release/{}".format(RUST_TARGET_NAME), shell=True)
    file_size = int(ls_output.split()[4].decode('utf-8'))
    return file_size

def working_directory_is_clean():
    try:
        subprocess.check_call("git diff-index --quiet HEAD --", shell=True)
        return True
    except subprocess.CalledProcessError:
        return False

if __name__ == "__main__":
    main()


text:
package io.opentracing.propagation;

import java.nio.ByteBuffer;
import org.junit.Test;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class BinaryAdaptersTest {

    @Test
    public void testExtractBinary() {
        ByteBuffer buff = ByteBuffer.wrap(new byte[0]);
        BinaryExtract binary = BinaryAdapters.extractionCarrier(buff);
        assertEquals(buff, binary.extractionBuffer());
    }

    @Test(expected = NullPointerException.class)
    public void testExtractBinaryNull() {
        BinaryAdapters.extractionCarrier(null);
    }

    @Test
    public void testInjectBinary() {
        ByteBuffer buffer = ByteBuffer.allocate(1);
        BinaryInject binary = BinaryAdapters.injectionCarrier(buffer);
        assertEquals(buffer, binary.injectionBuffer(1));
        assertEquals(0, buffer.position());
    }

    @Test(expected = IllegalArgumentException.class)
    public void testInjectBinaryInvalidLength() {
        BinaryInject binary = BinaryAdapters.injectionCarrier(ByteBuffer.allocate(1));
        binary.injectionBuffer(0);
    }

    @Test(expected = AssertionError.class)
    public void testInjectBinaryLargerLength() {
        BinaryInject binary = BinaryAdapters.injectionCarrier(ByteBuffer.allocate(1));
        binary.injectionBuffer(2);
    }
}


text:
class PrefService;
class PrefRegistrySimple;

namespace metrics {

class SystemProfileProto;

// Stores system profile information to prefs for creating stability logs
// in the next launch of chrome, and reads data from previous launches.
class EnvironmentRecorder {
 public:
  explicit EnvironmentRecorder(PrefService* local_state);
  ~EnvironmentRecorder();

  // Serializes the system profile and records it in prefs for the next
  // session.  Returns the uncompressed serialized proto for passing to crash
  // reports, or the empty string if the proto can't be serialized.
  std::string SerializeAndRecordEnvironmentToPrefs(
      const SystemProfileProto& system_profile);

  // Loads the system_profile data stored in a previous chrome session, and
  // stores it in the |system_profile| object.
  // Returns true iff a system profile was successfully read.
  bool LoadEnvironmentFromPrefs(SystemProfileProto* system_profile);

  // Deletes system profile data from prefs.
  void ClearEnvironmentFromPrefs();

  // Stores the buildtime of the current binary and version in prefs.
  void SetBuildtimeAndVersion(int64_t buildtime, const std::string& version);

  // Gets the buildtime stored in prefs.
  int64_t GetLastBuildtime();

  // Gets the version stored in prefs.
  std::string GetLastVersion();

  static void RegisterPrefs(PrefRegistrySimple* registry);

 private:
  PrefService* local_state_;

  DISALLOW_COPY_AND_ASSIGN(EnvironmentRecorder);
};

}  // namespace metrics

#endif  // COMPONENTS_METRICS_ENVIRONMENT_RECORDER_H_


text:
<?php

namespace tests\app\libraries;

use app\libraries\Core;

class CoreTester extends \PHPUnit\Framework\TestCase {
    /**
     * This function should always return false unless we've mocked it so that we can bypass something that
     * is a huge pain to otherwise get around (generally writing tests in phpt).
     */
    public function testIsTesting() {
        $core = new Core();
        $this->assertFalse($core->isTesting());
    }

    public function testErrorDatabaseBeforeConfig() {
        $core = new Core();
        $this->expectException(\Exception::class);
        /** @noinspection PhpUnhandledExceptionInspection */
        $core->loadMasterDatabase();
    }
}


text:
An [sbt](http://www.scala-sbt.org/) (Simple Build Tool) plugin for generating [Git Hooks](http://git-scm.com/docs/githooks) to force mandate JIRA-ID in commit's.

## Add Plugin

To add sbt-jira-mandate functionality to your project add the following to your `project/plugins.sbt` file:

```scala
resolvers += Resolver.url("kinshuk-bintray", url("https://dl.bintray.com/kingster/sbt-plugins"))(Resolver.ivyStylePatterns)

addSbtPlugin("com.flipkart.jira" % "sbt-jira-mandate" % "1.0.2")
```

If you want to use it for more than one project, you can add it to your global plugins file, usually found at: `~/.sbt/plugins/plugins.sbt` and then have it available for all sbt projects. See [Using Plugins](http://www.scala-sbt.org/release/docs/Getting-Started/Using-Plugins.html) for additional information on sbt plugins.

## Enabling Plugin

On your project root add the following to your `built.sbt` file :

```scala
import JiraIdPlugin.autoImport._

jira := "BRO"
seq(JiraIdPlugin.settings: _*)
```

### Requirements

* sbt 0.13.5+ (requires `AutoPlugin`)
* Scala 2.10.x

## Committing Changes

```bash
git commit -m "BRO-XX <commit message>"
git commit -m "BRO-XX: <commit message>"
```


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Roman Rabinovich
////////////////////////////////////////////////////////////////////////////////

#include "HITSKleinberg.h"
#include <cmath>
#include <utility>
#include "Pregel/Aggregator.h"
#include "Pregel/Algorithm.h"
#include "Pregel/GraphStore.h"
#include "Pregel/MasterContext.h"
#include "Pregel/VertexComputation.h"

using namespace arangodb::pregel::algos;
using namespace arangodb;
using namespace arangodb::pregel;

static std::string const authAggregator = "auth";
static std::string const hubAggregator = "hub";
static std::string const maxDiffAuthAggregator = "diffA";
static std::string const maxDiffHubAggregator = "diffH";
static std::string const isLastIterationAggregator = "stop";

using VertexType = HITSKleinbergValue;

namespace {
double const epsilon = 0.00001;

/**
 * If userParams has a threshold value, return it, otherwise return epsilon.
 * @param userParams
 * @return
 */
double getThreshold(VPackSlice userParams) {
  if (userParams.hasKey(Utils::threshold)) {
    if (!userParams.get(Utils::threshold).isNumber()) {
      THROW_ARANGO_EXCEPTION_MESSAGE(
          TRI_ERROR_BAD_PARAMETER,
          "The threshold parameter should be a number.");
    }
    return userParams.get(Utils::threshold).getNumber<double>();
  }
  return epsilon;
}
}  // namespace

enum class State {
  sendInitialHubs,
  updateAuth,
  updateAuthNormalizeHub,
  updateHubNormalizeAuth,
  finallyNormalizeHubs,
  finallyNormalizeAuths
};

struct HITSKleinbergWorkerContext : public WorkerContext {
  HITSKleinbergWorkerContext(size_t maxGSS, size_t numIterations,
                             double threshold)
      : numIterations(numIterations), threshold(threshold){};

  double authDivisor = 0;
  double hubDivisor = 0;
  State state = State::sendInitialHubs;
  size_t numIterations;
  size_t currentIteration = 0;
  double const threshold;

  void preGlobalSuperstep(uint64_t gss) override {
    // todo: we only need this if the global super-step is odd
    //  difficulty: the parent class WorkerContext doesn't know the current gss
    auto const* authNorm = getAggregatedValue<double>(authAggregator);
    auto const* hubNorm = getAggregatedValue<double>(hubAggregator);
    ADB_PROD_ASSERT(authNorm != nullptr);
    ADB_PROD_ASSERT(hubNorm != nullptr);
    authDivisor = std::sqrt(*authNorm);
    hubDivisor = std::sqrt(*hubNorm);

    double const authMaxDiff =
        *getAggregatedValue<double>(maxDiffAuthAggregator);
    double const hubMaxDiff = *getAggregatedValue<double>(maxDiffHubAggregator);
    double const diff = std::max(authMaxDiff, hubMaxDiff);

    if (diff < threshold) {
      if (state == State::updateAuthNormalizeHub) {
        state = State::finallyNormalizeHubs;
      } else if (state == State::updateHubNormalizeAuth) {
        state = State::finallyNormalizeAuths;
      }
    }
  }

  void postGlobalSuperstep(uint64_t gss) override {
    switch (state) {
      case State::sendInitialHubs: {
        state = State::updateAuth;
      } break;
      case State::updateAuth:
      case State::updateAuthNormalizeHub: {
        state = State::updateHubNormalizeAuth;
      } break;
      case State::updateHubNormalizeAuth: {
        ++currentIteration;
        if (currentIteration == numIterations) {
          state = State::finallyNormalizeHubs;
        } else {
          state = State::updateAuthNormalizeHub;
        }
      } break;
      case State::finallyNormalizeHubs:
      case State::finallyNormalizeAuths: {
        aggregate(isLastIterationAggregator, true);
      } break;
    }
  }
};

struct HITSKleinbergComputation
    : public VertexComputation<VertexType, int8_t, SenderMessage<double>> {
  HITSKleinbergComputation() = default;

  // sends auth to all in-neighbors. note that all vertices send messages
  // to all out-neighbors in all iterations (there are no inactive vertices),
  // so the set of in-neighbors can be determined by iterating over received
  // messages
  void sendAuthToInNeighbors(
      MessageIterator<SenderMessage<double>> const& receivedMessages,
      double auth) {
    SenderMessage<double> authData(this->pregelId(), auth);
    for (SenderMessage<double> const* message : receivedMessages) {
      sendMessage(message->senderId, authData);
    }
  }

  void sendHubToOutNeighbors(double hub) {
    SenderMessage<double> hubData(this->pregelId(), hub);
    sendMessageToAllNeighbours(hubData);
  }

  void compute(
      MessageIterator<SenderMessage<double>> const& messages) override {
    auto const* ctx =
        dynamic_cast<HITSKleinbergWorkerContext const*>(context());
    switch (ctx->state) {
      case State::sendInitialHubs: {
        // these are not normalized, but according to the description of the
        // algorithm in the paper, the 1.0's are used in place of normalized
        // values
        mutableVertexData()->normalizedAuth = 1.0;
        mutableVertexData()->normalizedHub = 1.0;
        reportFakeDifference(ctx->threshold);

        sendHubToOutNeighbors(1.0);
      } break;

      case State::updateAuth: {
        // We enter this state when all authorities and all hubs are 1.0
        updateStoreAndSendAuth(messages, 1.0);
        reportFakeDifference(ctx->threshold);
        // authorities are one iteration before hubs
        // authorities are not normalized, hubs are 1.0

        // Next state: updateHubNormalizeAuth
      } break;

      case State::updateHubNormalizeAuth: {
        // authorities are updated one iteration more than hubs,
        // authorities are not normalized, hubs are normalized

        // update local hub
        double nonNormalizedHub = 0.0;
        for (SenderMessage<double> const* message : messages) {
          TRI_ASSERT(message != nullptr);
          nonNormalizedHub += message->value;  // auth from our out-neighbors
        }
        mutableVertexData()->nonNormalizedHub = nonNormalizedHub;

        aggregate<double>(hubAggregator, nonNormalizedHub * nonNormalizedHub);

        // normalize auth (hubDivisor is not ready yet, cannot normalize hubs)
        auto const nonNormalizedAuth = mutableVertexData()->nonNormalizedAuth;
        auto const normalizedUpdatedAuth = nonNormalizedAuth / ctx->authDivisor;
        auto const diff =
            fabs(mutableVertexData()->normalizedAuth - normalizedUpdatedAuth);
        mutableVertexData()->normalizedAuth = normalizedUpdatedAuth;

        aggregate<double>(maxDiffAuthAggregator, diff);
        sendHubToOutNeighbors(nonNormalizedHub);

        // authorities and hubs are updated to the same iteration,
        // authorities are normalized, hubs are not normalized

        // Next state: updateAuthNormalizeHub or finallyNormalizeHubs
      } break;

      case State::updateAuthNormalizeHub: {
        // authorities and hubs are updated to the same iteration,
        // authorities are normalized, hubs are not normalized
        updateStoreAndSendAuth(messages, ctx->hubDivisor);
        auto const nonNormalizedHub = mutableVertexData()->nonNormalizedHub;
        auto const normalizedUpdatedHub = nonNormalizedHub / ctx->hubDivisor;
        auto const diff =
            fabs(mutableVertexData()->normalizedHub - normalizedUpdatedHub);
        mutableVertexData()->normalizedHub = normalizedUpdatedHub;
        aggregate<double>(maxDiffHubAggregator, diff);

        // authorities are updated one iteration more than hubs,
        // authorities are not normalized, hubs are normalized

        // next state: updateHubNormalizeAuth
      } break;

      case State::finallyNormalizeHubs: {
        // authorities and hubs are updated to the same iteration,
        // authorities are normalized, hubs are not normalized
        // last iteration
        mutableVertexData()->normalizedHub =
            mutableVertexData()->nonNormalizedHub / ctx->hubDivisor;
      } break;

      case State::finallyNormalizeAuths: {
        // authorities and hubs are updated to the same iteration,
        // authorities are not normalized, hubs are normalized
        // last iteration
        mutableVertexData()->normalizedAuth =
            mutableVertexData()->nonNormalizedAuth / ctx->authDivisor;
      } break;
    }
  }

 private:
  // At the beginning, we don't have differences between the current and the
  // previous values yet. If we don't report any difference, the default
  // difference 0 will be taken and the process terminates.
  void reportFakeDifference(double threshold) {
    // so that 0 != diff < threshold
    aggregate(maxDiffAuthAggregator, threshold + 1000.0);
  }

  void updateStoreAndSendAuth(
      MessageIterator<SenderMessage<double>> const& messages,
      double hubDivisor) {
    // compute the new auth
    double auth = 0.0;
    for (SenderMessage<double> const* message : messages) {
      TRI_ASSERT(message != nullptr);
      auth += message->value / hubDivisor;  // normalized hub from in-neighbors
    }
    // note: auth are preliminary values of an iteration of the
    // HITS algorithm, the correct ranks will be obtained in the next
    // global super-step when the norms based on the current values are
    // computed and we can divide the current values by the norms to
    // obtain the scores of the iteration

    mutableVertexData()->nonNormalizedAuth = auth;
    aggregate<double>(authAggregator, auth * auth);
    sendAuthToInNeighbors(messages, auth);
  }
};

VertexComputation<VertexType, int8_t, SenderMessage<double>>*
HITSKleinberg::createComputation(WorkerConfig const* config) const {
  return new HITSKleinbergComputation();
}

struct HITSKleinbergGraphFormat : public GraphFormat<VertexType, int8_t> {
  std::string const _resultField;

  explicit HITSKleinbergGraphFormat(
      application_features::ApplicationServer& server, std::string result)
      : GraphFormat<VertexType, int8_t>(server),
        _resultField(std::move(result)) {}

  [[nodiscard]] size_t estimatedEdgeSize() const override { return 0; }

  void copyVertexData(arangodb::velocypack::Options const&,
                      std::string const& /*documentId*/,
                      arangodb::velocypack::Slice /*document*/,
                      VertexType& /*targetPtr*/,
                      uint64_t& /*vertexIdRange*/) override {}

  bool buildVertexDocument(arangodb::velocypack::Builder& b,
                           VertexType const* value) const override {
    b.add(_resultField + "_auth", VPackValue(value->normalizedAuth));
    b.add(_resultField + "_hub", VPackValue(value->normalizedHub));
    return true;
  }
};

GraphFormat<VertexType, int8_t>* HITSKleinberg::inputFormat() const {
  return new HITSKleinbergGraphFormat(_server, _resultField);
}

WorkerContext* HITSKleinberg::workerContext(VPackSlice userParams) const {
  double const threshold = getThreshold(userParams);
  return new HITSKleinbergWorkerContext(maxGSS, numIterations, threshold);
}

struct HITSKleinbergMasterContext : public MasterContext {
  double const threshold;

  explicit HITSKleinbergMasterContext(VPackSlice userParams)
      : threshold(getThreshold(userParams)) {}

  bool postGlobalSuperstep() override {
    double const authMaxDiff =
        *getAggregatedValue<double>(maxDiffAuthAggregator);
    double const hubMaxDiff = *getAggregatedValue<double>(maxDiffHubAggregator);
    double const diff = std::max(authMaxDiff, hubMaxDiff);

    bool const converged = diff < threshold;

    // default (if no messages have been sent) is false
    bool const stop = *getAggregatedValue<bool>(isLastIterationAggregator);
    return !converged && !stop;
  }
};

MasterContext* HITSKleinberg::masterContext(VPackSlice userParams) const {
  return new HITSKleinbergMasterContext(userParams);
}

IAggregator* HITSKleinberg::aggregator(std::string const& name) const {
  if (name == hubAggregator || name == authAggregator) {
    return new SumAggregator<double>(false);  // non-permanent
  }
  if (name == maxDiffAuthAggregator) {
    return new MaxAggregator<double>(false);  // non-permanent
  }
  if (name == maxDiffHubAggregator) {
    return new MaxAggregator<double>(false);  // non-permanent
  }
  // this is a temporary hack (until MasterContext is available from the
  // algorithm) to report from WorkerContext to MasterContext that we have to
  // stop
  if (name == isLastIterationAggregator) {
    return new BoolOrAggregator(false);  // non-permanent
  }
  return nullptr;
}


text:
tko
===

Code Example for the TypeScript with knockout.js session held on CodeCamp 2013

The application is online on: http://monaco-swekster.azurewebsites.net/Roles.tko.html


text:
from zPE.util.global_config import SP_DEFAULT, SP_DEFAULT_OUT, SP_DEFAULT_OUT_STEP, SPOOL, SPOOL_CTRL_MAP

def empty():
    return (len(SPOOL) == 0)

def sz():
    return len(SPOOL)

def dict():
    return SPOOL.items()

def list():
    return SPOOL.keys()

def retrieve(key):
    if key in SPOOL:
        return SPOOL[key]
    else:
        return None

def mode_of(key):
    if key in SPOOL:
        return SPOOL[key].mode
    else:
        return None

def type_of(key):
    if key in SPOOL:
        return SPOOL[key].f_type
    else:
        return None

def path_of(key):
    if key in SPOOL:
        return SPOOL[key].virtual_path
    else:
        return None

def real_path_of(key):
    if key in SPOOL:
        return SPOOL[key].real_path
    else:
        return None


text:
DELETE FROM Reports
WHERE StatusId = 4

SELECT * FROM Status


text:
package org.kaaproject.kaa.client.event.registration;

import java.util.Map;

import org.kaaproject.kaa.client.event.EndpointAccessToken;
import org.kaaproject.kaa.client.event.EndpointKeyHash;

/**
 * Callback interface for attached endpoint list change notifications
 *
 * @author Taras Lemkin
 *
 */
public interface ChangedAttachedEndpointListCallback {
    /**
     * Callback on attached endpoints list changed
     *
     * @param attachedEndpoints the attached endpoints
     *
     * @see EndpointAccessToken
     * @see EndpointKeyHash
     */
    void onAttachedEndpointListChanged(Map<EndpointAccessToken, EndpointKeyHash> attachedEndpoints);
}


text:
> Do not forget to import `MonacoEditorModule` in the `imports` section of your module !

> Do not forget to edit your webpack configuration :

```javascript
var CopyWebpackPlugin = require('copy-webpack-plugin');
// ...
plugins: [
        new CopyWebpackPlugin([{
            from: 'node_modules/monaco-editor/min/vs',
            to: 'vs'
        }])
    ]
```

### How to use
```html
<monaco-editor [(value)]="code" [(valueToCompare)]="codeToCompare" language="xml"></monaco-editor>
```

```typescript
export class MonacoEditorDemoComponent implements OnInit {
    protected code: string;

    public constructor() {
    }

    public ngOnInit(): void {
		this.code = `<GROUP ID="GROUP_PROBE_UPSRV">
        <LABEL><![CDATA[UserProfile]]></LABEL>
        <TAG>up upsrv</TAG>
        <PROBE ID="LOG_SLOW_COMPONENT_UPSRV"/>
        <PROBE ID="LOG_ERROR_COMPONENT_UPSRV"/>
        <PROBE ID="LOG_UPSERVER_SQL_PERF"/>
        <PROBE ID="PERF_DATABASE_UPSRV"/>
        <PROBE ID="PING_DATABASE_UPSRV"/>
        <PROBE ID="LOG_PROBLEM_WITH_SERVER_COMPONENT_UPSRV"/>
        <JAVACODE>
            <![CDATA[
			]]>
        </JAVACODE>
    </GROUP>`
    }
}
```

You can pass in param every options coming from monaco editor ([see here](https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditoroptions.html#readonly))
```html
<monaco-editor [(value)]="code" language="json" [readOnly]="true" [automaticLayout]="true"></monaco-editor>
```

### Supported language
```typescript
    @Input() public language: 'bat' | 'c' | 'cpp' | 'csharp' | 'css' | 'dockerfile' | 'fsharp' | 'go' | 'graphql' | 'handlebars' | 'html' | 'ini' | 'jade' | 'javascript' | 'json' | 'less' | 'lua' | 'markdown' | 'objective-c' | 'php' | 'csharp' | 'plaintext' | 'postiats' | 'powershell' | 'python' | 'r' | 'razor' | 'ruby' | 'scss' | 'sql' | 'swift' | 'typescript' | 'vb' | 'xml' | 'yaml';
```


text:
namespace fs = std::experimental::filesystem;
using json = nlohmann::json;

class ProfileManager
{
public:
    ProfileManager() = delete;

    ProfileManager(std::wstring userHomePath);

    virtual ~ProfileManager();

    static ProfileManager *getInstance();

    bool isFirstTime();

    fs::path getUserDataDir();

    std::string getUserDataDirString();

    std::wstring getUserDataDirWstring();

    std::string getDownloadDir();

    json getConfigJson();

    void writeConfigJson(const json &input);

    json getMallRepositoryJson();

    void writeMallRepositoryJson(const json &input);

    json getPerformanceJson();

    void writePerformanceJson(const json &input);

    json getMachinesJson();

    void writeMachinesJson(const json &input);

    void resetMachinesJson();

private:
    static ProfileManager *instance;
    bool firstTime;
    fs::path userHomeDir;
    fs::path userDataDir;
    fs::path configFilePath;
    fs::path mallRepositoryPath;
    fs::path performanceFilePath;
    fs::path downloadDir;
    fs::path machinesFilePath;

    void initDataDir();

    void initHomePath(std::__cxx11::wstring &userHomePath);

    void initJsonFilePath();

    json getJsonFromFile(fs::path &filePath);

    json createJsonToFile(json j, fs::path &filePath);
};

#endif //SERVANTBASE_PROFILEMANAGER_HPP


text:
#include "mbed_assert.h"
#include "pinmap.h"
#include "PortNames.h"
#include "mbed_error.h"

/**
 * Configure pin multi-function
 */
void pin_function(PinName pin, int data)
{
    MBED_ASSERT(pin != (PinName)NC);
    uint32_t pin_index = NU_PINNAME_TO_PIN(pin);
    uint32_t port_index = NU_PINNAME_TO_PORT(pin);
    __IO uint32_t *Px_x_MFP = ((__IO uint32_t *) &SYS->PA_L_MFP) + port_index * 2 + (pin_index / 8);
    uint32_t MFP_Msk = NU_MFP_MSK(pin_index);

    // E.g.: SYS->PA_L_MFP  = (SYS->PA_L_MFP & (~SYS_PA_L_MFP_PA0_MFP_Msk) ) | SYS_PA_L_MFP_PA0_MFP_SC0_CD  ;
    *Px_x_MFP  = (*Px_x_MFP & (~MFP_Msk)) | data;
}

/**
 * Configure pin pull-up/pull-down
 */
void pin_mode(PinName pin, PinMode mode)
{
    MBED_ASSERT(pin != (PinName)NC);
    uint32_t pin_index = NU_PINNAME_TO_PIN(pin);
    uint32_t port_index = NU_PINNAME_TO_PORT(pin);
    GPIO_T *gpio_base = NU_PORT_BASE(port_index);

    uint32_t mode_intern;

    switch (mode) {
        case InputOnly:
            mode_intern = GPIO_PMD_INPUT;
            break;

        case PushPullOutput:
            mode_intern = GPIO_PMD_OUTPUT;
            break;

        case OpenDrain:
            mode_intern = GPIO_PMD_OPEN_DRAIN;
            break;

        default:
            /* H/W doesn't support separate configuration for input pull mode/direction.
             * We expect upper layer would have translated input pull mode/direction
             * to I/O mode */
            return;
    }

    GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern);

    /* Invalid combinations of PinMode/PinDirection
     *
     * We assume developer would avoid the following combinations of PinMode/PinDirection
     * which are invalid:
     * 1. InputOnly/PIN_OUTPUT
     * 2. PushPullOutput/PIN_INPUT
     */
}


text:
module Azure::ApiManagement::Mgmt::V2018_06_01_preview
  module Models
    #
    # The response of the List API Management services operation.
    #
    class ApiManagementServiceListResult

      include MsRestAzure

      include MsRest::JSONable
      # @return [Array<ApiManagementServiceResource>] Result of the List API
      # Management services operation.
      attr_accessor :value

      # @return [String] Link to the next set of results. Not empty if Value
      # contains incomplete list of API Management services.
      attr_accessor :next_link

      # return [Proc] with next page method call.
      attr_accessor :next_method

      #
      # Gets the rest of the items for the request, enabling auto-pagination.
      #
      # @return [Array<ApiManagementServiceResource>] operation results.
      #
      def get_all_items
        items = @value
        page = self
        while page.next_link != nil && !page.next_link.strip.empty? do
          page = page.get_next_page
          items.concat(page.value)
        end
        items
      end

      #
      # Gets the next page of results.
      #
      # @return [ApiManagementServiceListResult] with next page content.
      #
      def get_next_page
        response = @next_method.call(@next_link).value! unless @next_method.nil?
        unless response.nil?
          @next_link = response.body.next_link
          @value = response.body.value
          self
        end
      end

      #
      # Mapper for ApiManagementServiceListResult class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ApiManagementServiceListResult',
          type: {
            name: 'Composite',
            class_name: 'ApiManagementServiceListResult',
            model_properties: {
              value: {
                client_side_validation: true,
                required: true,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'ApiManagementServiceResourceElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'ApiManagementServiceResource'
                      }
                  }
                }
              },
              next_link: {
                client_side_validation: true,
                required: false,
                serialized_name: 'nextLink',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
> Collaboration and analytics platform

## Guidelines for using waffle, making a commit and pull-request

1. Fork to your github repo
2. Clone to your local machine
3. Set upstream master: "git remote add upstream https://github.com/paperMacheTortoise/Hive.git"

## Branch names
feat/ fix/ refactor/ cleanup/ doc/

## Commit msgs: start with () and close waffle issue accordingly
(feat) (fix) (refactor) (cleanup) (test) (doc)

## branching, commit, pull-request checklist
1. Create a new branch: 'git checkout -b 'doc/readme "
2. Review the waffle issues before making your commit: https://waffle.io/paperMacheTortoise/Hive
3. Commit with waffle issue number (if applicable): "(doc) update readme close #8"
4. Make sure to rebase: "git pull --rebase upstream master"
5. Push to your fork: "git push origin doc/readme"
6. Make a pull request from your fork.
7. Notify the team on slack. Please don't merge your own pull request, let another team member review the change and merge.

## Team

  - __Product Owner__: Austin Worachet, Danielle Blank
  - __Scrum Master__: Liam Gallivan
  - __Development Team Members__: Richard Stanley, Karianne Burns

## Table of Contents

1. [Usage](#Usage)
2. [Requirements](#requirements)
3. [Development](#development)
    4. [Installing Dependencies](#installing-dependencies)
    5. [Setting up the database environemnt](#setting-up-the-database-environment)
    6. [Database development support](#database-development-support)
    7. [Working with the database](#working-with-the-database)
    8. [Emulating in the browser](#emulating-in-the-brower)
    9. [Emulating for iOS](#emulating-for-ios)
    10. [Emulating for Android](#emulating-for-android)
11. [Contributing](#contributing)
12. [API Documentation](#api-documentation)

## Usage

Platform for a team to collaborate.
Less email. More productivity.
Managers can generate report visualization from QuickBooks, social media.

## Requirements

- Node
- Express
- Firebase
- AngularJS
- React
- D3

## Development

### Installing Dependencies

From within the root directory:

### Database Development Support

### Roadmap

View the project roadmap [here](https://github.com/paperMacheTortoise/Hive/issues)

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines.


text:
module AccountDetails

  class SettlementTypeRenderer < AccountDetailRenderer

    def initialize( account )
      super( account )
    end

    def get_template(controller_name)
      controller_name + '/account_details/settlement_type'
    end

  end

end


text:
package org.balloon_project.overflight.task.endpointSource;

import com.google.common.base.Stopwatch;
import com.google.gson.Gson;
import org.balloon_project.overflight.model.Endpoint;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * This class is responsible for endpoint loading from the datahub.io database
 */
@Component
@Scope(value = "singleton")
public class CKANLoader {

    public static final String DATAHUB_QUERY_LODCLOUD = "http://datahub.io/api/3/action/package_search?rows=1000&q=organization:lodcloud";
    public static final String DATAHUB_QUERY_LOD = "http://datahub.io/api/3/action/package_search?rows=1000&q=organization:lod";
    public static final String DATAHUB_FORMAT_SPARQL = "api/sparql";
    public static final String DATAHUB_RESOURCE_NAMESPACE = "namespace";

    private Logger logger = LoggerFactory.getLogger(CKANLoader.class);

    /**
     * Loads all Linked Open Data endpoints from Datahub.io which offer a SPARQL endpoint
     * @return List of Linked Open Data SPARQL endpoints
     */
    public List<Endpoint> loadEndpoints() throws IOException {
        logger.info("CKAN endpoint loading started");
        Stopwatch timer = Stopwatch.createStarted();

        List<Endpoint> result = new LinkedList<>();
        result.addAll(queryCKAN(DATAHUB_QUERY_LODCLOUD));
        result.addAll(queryCKAN(DATAHUB_QUERY_LOD));

        logger.info(result.size() + " CKAN endpoints loaded. (Duration: " + timer.stop().elapsed(TimeUnit.SECONDS) + "s)");

        return result;
    }

    private List<Endpoint> queryCKAN(String url) throws IOException {
        List<Endpoint> result = new LinkedList<>();
        Gson gson = new Gson();
        ClientResource datahubQuery = new ClientResource(url);
        Representation datahubRepresentation = datahubQuery.get();

        if (datahubQuery.getStatus().isSuccess()) {
            DatahubReponse datahubReponse = gson.fromJson(datahubRepresentation.getText(), DatahubReponse.class);

            // navigate the entry to get all endpoints which offer a sparql endpoint
            if(datahubReponse != null) {
                ResultEntry resultEntry = datahubReponse.getResult();
                if(resultEntry != null) {
                    List<EndpointEntry> endpointEntries = resultEntry.getResults();
                    if(endpointEntries !=null) {
                        for(EndpointEntry endpointEntry : endpointEntries) {
                            List<ResourceEntry> resourceEntries = endpointEntry.getResources();
                            if(resourceEntries != null) {
                                for(ResourceEntry resourceEntry : resourceEntries) {
                                    if(DATAHUB_FORMAT_SPARQL.equals(resourceEntry.getFormat())) {
                                        Endpoint endpoint = new Endpoint();
                                        endpoint.setEndpointID(endpointEntry.getName());
                                        endpoint.setTitle(endpointEntry.getTitle());
                                        endpoint.setUrl(endpointEntry.getUrl());
                                        endpoint.setSparqlEndpoint(resourceEntry.getUrl());

                                        // search for resource namespace
                                        List<ExtraEntry> extrasEntries = endpointEntry.getExtras();
                                        if(extrasEntries != null) {
                                            for(ExtraEntry extraEntry : extrasEntries) {
                                                if(DATAHUB_RESOURCE_NAMESPACE.equals(extraEntry.getKey())) {
                                                    endpoint.setNamespace(extraEntry.getValue());
                                                    break;
                                                }
                                            }
                                        }

                                        result.add(endpoint);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return result;
    }

    /**
     * GSON Bean for response deserialization
     */
    private class DatahubReponse {
        private ResultEntry result;

        private DatahubReponse() {
        }

        public ResultEntry getResult() {
            return result;
        }

        public void setResult(ResultEntry result) {
            this.result = result;
        }

    }

    /**
     * GSON Bean for response deserialization
     */
    private class ResultEntry {
        private List<EndpointEntry> results;

        private ResultEntry() {
        }

        public List<EndpointEntry> getResults() {
            return results;
        }

        public void setResults(List<EndpointEntry> results) {
            this.results = results;
        }
    }

    /**
     * GSON Bean for response deserialization
     */
    private class EndpointEntry {
        private List<ResourceEntry> resources;
        private List<ExtraEntry> extras;
        private String title;
        private String name;
        private String url;

        private EndpointEntry() {

        }

        public List<ResourceEntry> getResources() {
            return resources;
        }

        public void setResources(List<ResourceEntry> resources) {
            this.resources = resources;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public List<ExtraEntry> getExtras() { return extras; }

        public void setExtras(List<ExtraEntry> extras) { this.extras = extras; }
    }

    /**
     * GSON Bean for response deserialization
     */
    private class ResourceEntry {
        private String format;
        private String url;

        private ResourceEntry() {
        }

        public String getFormat() {
            return format;
        }

        public void setFormat(String format) {
            this.format = format;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }

    /**
     * GSON Bean for response deserialization
     */
    private class ExtraEntry {
        private String key;
        private String value;

        private ExtraEntry() {
        }

        public String getKey() { return key; }

        public void setKey(String key) { this.key = key; }

        public String getValue() { return value; }

        public void setValue(String value) { this.value = value; }
    }
}


text:
layout: default
title: 5. Recommendations
permalink: /recommendations/
---

The purpose of this paper has been to provide context for, and recommend the adoption of, a shared agenda for regional civic innovation in the Sacramento Metropolitan Area. The recommendations listed below fall into two categories (1) *core recommendations* to set the vision and structure for civic innovation to flourish, and (2) a set of *future considerations* that may accelerate the growth of our regional civic innovation ecosystem.

### Core Recommendations

1. The region's local government bodies should adopt a resolution in support of a regional agenda modeled after the Draft Regional Civic Technology, Innovation and Entrepreneurship Agenda in [Appendix A](/resolution).

2. The region should establish a multi-sector stakeholder advisory body to advise the region's local, state, and federal agencies on open data and civic innovation. The advisory body should:

a. Consist of local government staff, leaders of civic organizations, representatives from academia, and members of the entrepreneurship community;

b. Be charged with coordinating open data initiatives and developing civic data standards to support interoperability across all levels of government;

c. Develop and adopt a one-year action plan for the purposes of achieving quick and early wins;

d. Identify areas in which state statute or regulations inhibit civic innovation; and,

e. Identify ways in which civic startups and social enterprises can more easily do business with government through procurement reform.

3. The region's local government bodies should commit to allocating a finite set of resources to support civic innovation activities. Such resources might include:

* Financial resources to establish and support a regional civic innovation fund;

* Staff support to carry out special projects within interagency and multi-sector delivery teams;

* Physical space to support experimentation;

* Knowledge sharing about opportunities to reduce costs and improve outcomes in the delivery of public services; and,

* Opportunities for the public to solve community problems in partnership with government.

### Future Considerations

Actions for future consideration by the advisory body, along with state and local agencies, include:

* Develop and adopt a regional approach to publishing open data;

* Create an entrepreneurs-in-residence program that would bring entrepreneurs into government who would propose, develop, and deploy solutions to reduce costs, improve outcomes, and boost local economic development;

* Develop initiatives to facilitate ethnography, user research, and usability testing to improve citizen-government interaction;

* Explore opportunities to build open application programming interfaces (APIs) that reduce the number of interagency friction points, including those between the state-local relationship;

* Encourage the state to create an advisory body that would explore the state's role in supporting civic innovation at the state-level;

* Adopt design principles to guide the development of interfaces to government and service delivery;

* Create positions in government that require skill sets from the new economy such as user experience,  visual design, and product management;

* Build capacity for the pursuit of side projects by public servants that have the potential to reduce costs and improve outcomes;

* Identify the role of universities in supporting regional civic innovation;

* Create a marketplace for government to post problems and citizens to propose cost-effective solutions; and,

* Fundamentally redesign the public meeting experience and recommend changes to state law in areas that would otherwise prevent the vision from being fully realized.

[Appendix B](/innovative-jurisdiction-framework) contains a comprehensive framework put forth by the Harvard Kennedy's School of Government's Ash Center for Democratic Governance and Innovation, as reference.

[Appendix C](/new-urban-mechanics) contains the executive order that created Philadelphia's Mayor's Office of New Urban Mechanics – a public sector innovation lab, also as reference.

Help Improve these Recommendations

Prev
Next


text:
nano::network_filter::network_filter (size_t size_a) :
items (size_a, nano::uint128_t{ 0 })
{
	nano::random_pool::generate_block (key, key.size ());
}

bool nano::network_filter::apply (uint8_t const * bytes_a, size_t count_a, nano::uint128_t * digest_a)
{
	// Get hash before locking
	auto digest (hash (bytes_a, count_a));

	nano::lock_guard<std::mutex> lock (mutex);
	auto & element (get_element (digest));
	bool existed (element == digest);
	if (!existed)
	{
		// Replace likely old element with a new one
		element = digest;
	}
	if (digest_a)
	{
		*digest_a = digest;
	}
	return existed;
}

void nano::network_filter::clear (nano::uint128_t const & digest_a)
{
	nano::lock_guard<std::mutex> lock (mutex);
	auto & element (get_element (digest_a));
	if (element == digest_a)
	{
		element = nano::uint128_t{ 0 };
	}
}

void nano::network_filter::clear (std::vector<nano::uint128_t> const & digests_a)
{
	nano::lock_guard<std::mutex> lock (mutex);
	for (auto const & digest : digests_a)
	{
		auto & element (get_element (digest));
		if (element == digest)
		{
			element = nano::uint128_t{ 0 };
		}
	}
}

void nano::network_filter::clear (uint8_t const * bytes_a, size_t count_a)
{
	clear (hash (bytes_a, count_a));
}

template <typename OBJECT>
void nano::network_filter::clear (OBJECT const & object_a)
{
	clear (hash (object_a));
}

void nano::network_filter::clear ()
{
	nano::lock_guard<std::mutex> lock (mutex);
	items.assign (items.size (), nano::uint128_t{ 0 });
}

template <typename OBJECT>
nano::uint128_t nano::network_filter::hash (OBJECT const & object_a) const
{
	std::vector<uint8_t> bytes;
	{
		nano::vectorstream stream (bytes);
		object_a->serialize (stream);
	}
	return hash (bytes.data (), bytes.size ());
}

nano::uint128_t & nano::network_filter::get_element (nano::uint128_t const & hash_a)
{
	debug_assert (!mutex.try_lock ());
	debug_assert (items.size () > 0);
	size_t index (hash_a % items.size ());
	return items[index];
}

nano::uint128_t nano::network_filter::hash (uint8_t const * bytes_a, size_t count_a) const
{
	nano::uint128_union digest{ 0 };
	siphash_t siphash (key, static_cast<unsigned int> (key.size ()));
	siphash.CalculateDigest (digest.bytes.data (), bytes_a, count_a);
	return digest.number ();
}

// Explicitly instantiate
template nano::uint128_t nano::network_filter::hash (std::shared_ptr<nano::block> const &) const;
template void nano::network_filter::clear (std::shared_ptr<nano::block> const &);


text:
package org.cnjava.bigpipe.core.pagelet.service;

import org.cnjava.bigpipe.core.pagelet.model.PageletInfo;

/**
 * pagelet相关接口
 * Created by jiangjk on 16/1/27.
 */
public interface IPageletService {
    /**
     * pagelet查询接口 默认实现为实例化简单的pagelet对象
     * 也可以实现此方法用于数据库查询
     *
     * @param pageletId
     * @return
     */
    PageletInfo getPageletInfo(String pageletId);
}


text:
#ifndef AMBROLIB_BUSY_EVENT_LOOP_H
#define AMBROLIB_BUSY_EVENT_LOOP_H

#include <stdint.h>
#include <stddef.h>

#include <aprinter/meta/TypeList.h>
#include <aprinter/meta/TypeListUtils.h>
#include <aprinter/meta/ChooseInt.h>
#include <aprinter/meta/BitsInInt.h>
#include <aprinter/meta/MinMax.h>
#include <aprinter/meta/BasicMetaUtils.h>
#include <aprinter/meta/ServiceUtils.h>
#include <aprinter/structure/DoubleEndedList.h>
#include <aprinter/base/Object.h>
#include <aprinter/base/DebugObject.h>
#include <aprinter/base/Assert.h>
#include <aprinter/base/Lock.h>
#include <aprinter/base/Hints.h>
#include <aprinter/base/Callback.h>
#include <aprinter/system/InterruptLock.h>
#include <aprinter/misc/ClockUtils.h>

#include <aprinter/BeginNamespace.h>

template <typename> class BusyEventLoopQueuedEvent;
template <typename> class BusyEventLoopTimedEvent;

template <typename Arg>
class BusyEventLoop {
    using ParentObject = typename Arg::ParentObject;
    using ExtraDelay   = typename Arg::ExtraDelay;

public:
    struct Object;
    using Context = typename Arg::Context;
    using Clock = typename Context::Clock;
    using TimeType = typename Clock::TimeType;
    using TheClockUtils = ClockUtils<Context>;
    using QueuedEvent = BusyEventLoopQueuedEvent<BusyEventLoop>;
    using TimedEvent = BusyEventLoopTimedEvent<BusyEventLoop>;
    using FastHandlerType = void (*) (Context);

private:
    using TheDebugObject = DebugObject<Context, Object>;

public:
    static void init (Context c)
    {
        auto *o = Object::self(c);
#ifdef AMBROLIB_SUPPORT_QUIT
        o->m_quitting = false;
#endif
        o->m_event_list.init();
        Delay::extra(c)->m_fast_event_pos = 0;
        for (typename Delay::Extra::FastEventSizeType i = 0; i < Delay::Extra::NumFastEvents; i++) {
            Delay::extra(c)->m_fast_events[i].not_triggered = true;
        }
#ifdef EVENTLOOP_BENCHMARK
        o->m_bench_time = 0;
#endif

        TheDebugObject::init(c);
    }

    static void deinit (Context c)
    {
        auto *o = Object::self(c);
        TheDebugObject::deinit(c);
        AMBRO_ASSERT(o->m_event_list.isEmpty())
    }

    static void run (Context c)
    {
        auto *o = Object::self(c);
        TheDebugObject::access(c);

        while (1) {
            for (typename Delay::Extra::FastEventSizeType i = 0; i < Delay::Extra::NumFastEvents; i++) {
                Delay::extra(c)->m_fast_event_pos++;
                if (AMBRO_UNLIKELY(Delay::extra(c)->m_fast_event_pos == Delay::Extra::NumFastEvents)) {
                    Delay::extra(c)->m_fast_event_pos = 0;
                }
                cli();
                if (!Delay::extra(c)->m_fast_events[Delay::extra(c)->m_fast_event_pos].not_triggered) {
                    Delay::extra(c)->m_fast_events[Delay::extra(c)->m_fast_event_pos].not_triggered = true;
                    sei();
                    bench_start_measuring(c);
                    Delay::extra(c)->m_fast_events[Delay::extra(c)->m_fast_event_pos].handler(c);
                    c.check();
                    bench_stop_measuring(c);
                    break;
                }
                sei();
            }

        again:;
            TimeType now = Clock::getTime(c);
            for (BaseEventStruct *ev = o->m_event_list.first(); ev; ev = o->m_event_list.next(ev)) {
                AMBRO_ASSERT(!EventList::isRemoved(ev))
                if (ev->handler_or_hack || TheClockUtils::timeGreaterOrEqual(now, static_cast<TimedEventStruct *>(ev)->time)) {
                    o->m_event_list.remove(ev);
                    EventList::markRemoved(ev);
                    bench_start_measuring(c);
                    if (ev->handler_or_hack) {
                        ev->handler_or_hack(c);
                    } else {
                        auto handler = EventHandlerType::Make(static_cast<TimedEventStruct *>(ev)->handler_func, ev->handler_or_hack.m_arg);
                        handler(c);
                    }
                    c.check();
                    bench_stop_measuring(c);
#ifdef AMBROLIB_SUPPORT_QUIT
                    if (o->m_quitting) {
                        return;
                    }
#endif
                    goto again;
                }
            }
        }
    }

#ifdef EVENTLOOP_BENCHMARK
    static void resetBenchTime (Context c)
    {
        auto *o = Object::self(c);
        o->m_bench_time = 0;
    }

    static TimeType getBenchTime (Context c)
    {
        auto *o = Object::self(c);
        return o->m_bench_time;
    }
#endif

#ifdef AMBROLIB_SUPPORT_QUIT
    static void quit (Context c)
    {
        auto *o = Object::self(c);
        o->m_quitting = true;
    }
#endif

    template <typename Id>
    struct FastEventSpec {};

    template <typename EventSpec>
    static void initFastEvent (Context c, FastHandlerType handler)
    {
        TheDebugObject::access(c);

        Delay::extra(c)->m_fast_events[Delay::Extra::template get_event_index<EventSpec>()].handler = handler;
    }

    template <typename EventSpec>
    static void resetFastEvent (Context c)
    {
        TheDebugObject::access(c);

        Delay::extra(c)->m_fast_events[Delay::Extra::template get_event_index<EventSpec>()].not_triggered = true;
    }

    template <typename EventSpec, typename ThisContext>
    AMBRO_ALWAYS_INLINE
    static void triggerFastEvent (ThisContext c)
    {
        TheDebugObject::access(c);

        AMBRO_LOCK_T(InterruptTempLock(), c, lock_c) {
            Delay::extra(c)->m_fast_events[Delay::Extra::template get_event_index<EventSpec>()].not_triggered = false;
        }
    }

private:
    template <typename> friend class BusyEventLoopQueuedEvent;
    template <typename> friend class BusyEventLoopTimedEvent;

    using EventHandlerType = Callback<void(Context)>;

    struct BaseEventStruct {
        EventHandlerType handler_or_hack;
        DoubleEndedListNode<BaseEventStruct> list_node;
    };

    struct TimedEventStruct : public BaseEventStruct {
        typename EventHandlerType::FuncType handler_func;
        TimeType time;
    };

    using EventList = DoubleEndedList<BaseEventStruct, &BaseEventStruct::list_node>;

    struct Delay {
        using Extra = typename ExtraDelay::Type;
        static typename Extra::Object * extra (Context c) { return Extra::Object::self(c); }
    };

    static void bench_start_measuring (Context c)
    {
#ifdef EVENTLOOP_BENCHMARK
        auto *o = Object::self(c);
        o->m_bench_enter_time = Clock::getTime(c);
#endif
    }

    static void bench_stop_measuring (Context c)
    {
#ifdef EVENTLOOP_BENCHMARK
        auto *o = Object::self(c);
        o->m_bench_time += (TimeType)(Clock::getTime(c) - o->m_bench_enter_time);
#endif
    }

public:
    struct Object : public ObjBase<BusyEventLoop, ParentObject, MakeTypeList<TheDebugObject>> {
#ifdef AMBROLIB_SUPPORT_QUIT
        bool m_quitting;
#endif
        EventList m_event_list;
#ifdef EVENTLOOP_BENCHMARK
        TimeType m_bench_time;
        TimeType m_bench_enter_time;
#endif
    };
};

APRINTER_ALIAS_STRUCT_EXT(BusyEventLoopArg, (
    APRINTER_AS_TYPE(Context),
    APRINTER_AS_TYPE(ParentObject),
    APRINTER_AS_TYPE(ExtraDelay)
), (
    APRINTER_DEF_INSTANCE(BusyEventLoopArg, BusyEventLoop)
))

template <typename Arg>
class BusyEventLoopExtra {
    using ParentObject  = typename Arg::ParentObject;
    using Loop          = typename Arg::Loop;
    using FastEventList = typename Arg::FastEventList;

    friend Loop;

    static const int NumFastEvents = TypeListLength<FastEventList>::Value;
    using FastEventSizeType = ChooseInt<MaxValue(1, BitsInInt<NumFastEvents>::Value), false>;

    struct FastEventState {
        bool not_triggered;
        typename Loop::FastHandlerType handler;
    };

    template <typename EventSpec>
    static constexpr FastEventSizeType get_event_index ()
    {
        return TypeListIndex<FastEventList, EventSpec>::Value;
    }

public:
    struct Object : public ObjBase<BusyEventLoopExtra, ParentObject, EmptyTypeList> {
        FastEventSizeType m_fast_event_pos;
        FastEventState m_fast_events[NumFastEvents];
    };
};

APRINTER_ALIAS_STRUCT_EXT(BusyEventLoopExtraArg, (
    APRINTER_AS_TYPE(ParentObject),
    APRINTER_AS_TYPE(Loop),
    APRINTER_AS_TYPE(FastEventList)
), (
    APRINTER_DEF_INSTANCE(BusyEventLoopExtraArg, BusyEventLoopExtra)
))

template <typename Loop>
class BusyEventLoopQueuedEvent
: private SimpleDebugObject<typename Loop::Context>, private Loop::BaseEventStruct
{
public:
    using Context = typename Loop::Context;
    using TimeType = typename Loop::TimeType;
    using HandlerType = Callback<void(Context c)>;

    void init (Context c, HandlerType handler)
    {
        AMBRO_ASSERT(handler)

        this->handler_or_hack = handler;
        Loop::EventList::markRemoved(this);

        this->debugInit(c);
    }

    void deinit (Context c)
    {
        this->debugDeinit(c);
        auto *lo = Loop::Object::self(c);

        if (!Loop::EventList::isRemoved(this)) {
            lo->m_event_list.remove(this);
        }
    }

    void unset (Context c)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);

        if (!Loop::EventList::isRemoved(this)) {
            lo->m_event_list.remove(this);
            Loop::EventList::markRemoved(this);
        }
    }

    bool isSet (Context c)
    {
        this->debugAccess(c);

        return !Loop::EventList::isRemoved(this);
    }

    void appendNowNotAlready (Context c)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);
        AMBRO_ASSERT(Loop::EventList::isRemoved(this))

        lo->m_event_list.append(this);
    }

    void appendNow (Context c)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);

        if (!Loop::EventList::isRemoved(this)) {
            lo->m_event_list.remove(this);
        }
        lo->m_event_list.append(this);
    }

    void prependNowNotAlready (Context c)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);
        AMBRO_ASSERT(Loop::EventList::isRemoved(this))

        lo->m_event_list.prepend(this);
    }

    void prependNow (Context c)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);

        if (!Loop::EventList::isRemoved(this)) {
            lo->m_event_list.remove(this);
        }
        lo->m_event_list.prepend(this);
    }
};

template <typename Loop>
class BusyEventLoopTimedEvent
: private SimpleDebugObject<typename Loop::Context>, private Loop::TimedEventStruct
{
public:
    using Context = typename Loop::Context;
    using TimeType = typename Loop::TimeType;
    using HandlerType = Callback<void(Context c)>;

    void init (Context c, HandlerType handler)
    {
        AMBRO_ASSERT(handler)

        this->handler_or_hack = HandlerType::Make(nullptr, handler.m_arg);
        Loop::EventList::markRemoved(this);
        this->handler_func = handler.m_func;

        this->debugInit(c);
    }

    void deinit (Context c)
    {
        this->debugDeinit(c);
        auto *lo = Loop::Object::self(c);

        if (!Loop::EventList::isRemoved(this)) {
            lo->m_event_list.remove(this);
        }
    }

    void unset (Context c)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);

        if (!Loop::EventList::isRemoved(this)) {
            lo->m_event_list.remove(this);
            Loop::EventList::markRemoved(this);
        }
    }

    bool isSet (Context c)
    {
        this->debugAccess(c);

        return !Loop::EventList::isRemoved(this);
    }

    void appendNowNotAlready (Context c)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);
        AMBRO_ASSERT(Loop::EventList::isRemoved(this))

        lo->m_event_list.append(this);
        this->time = Context::Clock::getTime(c);
    }

    void appendAt (Context c, TimeType time)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);

        if (!Loop::EventList::isRemoved(this)) {
            lo->m_event_list.remove(this);
        }
        lo->m_event_list.append(this);
        this->time = time;
    }

    void appendAfter (Context c, TimeType after_time)
    {
        appendAt(c, Context::Clock::getTime(c) + after_time);
    }

    void appendAfterNotAlready (Context c, TimeType after_time)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);
        AMBRO_ASSERT(Loop::EventList::isRemoved(this))

        lo->m_event_list.append(this);
        this->time = Context::Clock::getTime(c) + after_time;
    }

    void appendAfterPrevious (Context c, TimeType after_time)
    {
        this->debugAccess(c);
        auto *lo = Loop::Object::self(c);
        AMBRO_ASSERT(Loop::EventList::isRemoved(this))

        lo->m_event_list.append(this);
        this->time += after_time;
    }

    TimeType getSetTime (Context c)
    {
        this->debugAccess(c);

        return this->time;
    }
};

#include <aprinter/EndNamespace.h>

#endif


text:
import WindowsHandler from './WindowsHandler'

export default [
	WindowsHandler,
];


text:
namespace cimm
{

namespace
{

auto add_integers(const list& l) -> expression
{
    integer sum{0};
    for (auto e = l; not is_empty(e); e = rest(e))
        sum += as_integer(first(e));
    return sum;
}

auto multiply_integers(const list& l) -> expression
{
    integer prod{1};
    for (auto e = l; not is_empty(e); e = rest(e))
        prod *= as_integer(first(e));
    return prod;
}

auto subtract_integers(const list& l) -> expression
{
    if (is_empty(l))
        throw arity_error(count(l), "-");
    if (count(l) == 1)
        return -as_integer(first(l));
    integer d = as_integer(first(l));
    for (auto e = rest(l); not is_empty(e); e = rest(e))
        d -= as_integer(first(e));
    return d;
}

auto is_equal(const list& l) -> boolean
{
    if (is_empty(l))
      throw arity_error(count(l), "=");
    auto c = first(l);
    for (auto e = rest(l); not is_empty(e); e = rest(e))
        if (c != first(e))
            return false;
    return true;
}

auto is_equal_f(const list& l) -> expression
{
    return is_equal(l);
}

auto is_unequal_f(const list& l) -> expression
{
    return not is_equal(l);
}

auto is_less_than_f(const list& l) -> expression
{
    auto x = as_integer(first(l));
    auto it = rest(l);
    while (not is_empty(it))
    {
        auto y = as_integer(first(it));
        if (not (x < y))
            return false;
        x = y;
        it = rest(it);
    }
    return true;
}

struct visit_not : expression::visitor<boolean>
{
    boolean operator()(const boolean& b) const { return not b; }
    boolean operator()(const nil_type& ) const { return true; }

    template <typename T>
    boolean operator()(const T& ) const { return false; }
};

auto not_f(const list& args) -> expression
{
    return is_empty(args) || apply(visit_not(), first(args));
}

struct make_keyword : expression::visitor<expression>
{
    expression operator()(const string& s) const { return keyword(s); }
    expression operator()(const keyword& k) const { return k; }

    template <typename T>
    expression operator()(const T& ) const { return nil; }
};

auto keyword_f(const list& l) -> expression
{
    if (is_empty(l))
        throw arity_error(count(l), "keyword");
    return apply(make_keyword(), first(l));
}

struct make_symbol : expression::visitor<expression>
{
    expression operator()(const string& s) const { return symbol(s); }

    template <typename T>
    expression operator()(const T& e) const { throw cannot_create_symbol(e); }
};

auto symbol_f(const list& l) -> expression
{
    if (is_empty(l))
        throw arity_error(count(l), "symbol");
    return apply(make_symbol(), first(l));
}

auto list_f(const list& l) -> expression
{
    return l;
}

namespace
{

struct first_visitor : expression::visitor<expression>
{
    auto operator()(const list& l) -> expression { return first(l); }
    auto operator()(const vector& v) -> expression { return first(v); }

    template <typename expression_type>
    auto operator()(const expression_type& e) -> expression { throw type_error(e, "a sequence"); }
};

}

auto first_f(const expression& e) -> expression
{
    return apply(first_visitor(), e);
}

auto rest_f(const expression& e) -> expression
{
    if (e == nil)
        return list{};
    return rest(as_list(e));
}

namespace
{

struct count_visitor : expression::visitor<expression>
{
    auto operator()(const list& l) -> expression { return count(l); }
    auto operator()(const vector& v) -> expression { return count(v); }
    auto operator()(const nil_type&) -> expression { return integer(0); }

    template <typename expression_type>
    auto operator()(const expression_type& e) -> expression { throw type_error(e, "a sequence"); }
};

}

auto count_f(const expression& c) -> expression
{
    return apply(count_visitor(), c);
}

auto cons_f(const list& args) -> expression
{
    if (is_empty(args))
        return list{nil};
    auto elem = first(args);
    auto r = rest(args);
    if (is_empty(r))
        return list{elem};
    return cons(elem, as_list(first(r)));
}

auto conj_f(const list& args) -> expression
{
    return conj(first(args), first(rest(args)));
}

auto nth_f(const list& args) -> expression
{
    return *(begin(as_vector(first(args))) + as_integer(first(rest(args))));
}

auto vector_f(const list& args) -> expression
{
    return vector(args);
}

auto vec_f(const list& args) -> expression
{
    return vector(as_list(first(args)));
}

auto throw_f(const expression& e) -> expression
{
    return error{e};
}

auto str_f(const list& args) -> expression
{
    std::string s;
    for (auto l = args; not is_empty(l); l = rest(l))
        s += str(first(l)).c_str();
    return string{s};
}

auto pr_str_f(const list& args) -> expression
{
    std::string s;
    for (auto l = args; not is_empty(l); l = rest(l))
        s += pr_str(first(l)).c_str();
    return string{s};
}

auto print_f(const list& args) -> expression
{
    if (is_empty(args))
        return nil;
    std::cout << str(first(args));
    for (auto l = rest(args); not is_empty(l); l = rest(l))
        std::cout << ' ' << str(first(l));
    std::cout << std::flush;
    return nil;
}

auto exit_f(const expression& exit_code) -> expression
{
    std::exit(as_integer(exit_code));
}

}

auto create_default_environment() -> environment
{
    environment env;

    define_native_function(env, {"+", add_integers});
    define_native_function(env, {"*", multiply_integers});
    define_native_function(env, {"-", subtract_integers});
    define_native_function(env, {"=", is_equal_f});
    define_native_function(env, {"not=", is_unequal_f});
    define_native_function(env, {"<", is_less_than_f});
    define_native_function(env, {"not", not_f});
    define_native_function(env, {"keyword", keyword_f});
    define_native_function(env, {"symbol", symbol_f});
    define_native_function(env, {"list", list_f});
    define_native_function(env, {"first", first_f});
    define_native_function(env, {"rest", rest_f});
    define_native_function(env, {"count", count_f});
    define_native_function(env, {"cons", cons_f});
    define_native_function(env, {"conj", conj_f});
    define_native_function(env, {"nth", nth_f});
    define_native_function(env, {"vector", vector_f});
    define_native_function(env, {"vec", vec_f});
    define_native_function(env, {"throw", throw_f});
    define_native_function(env, {"str", str_f});
    define_native_function(env, {"pr-str", pr_str_f});
    define_native_function(env, {"print", print_f});
    define_native_function(env, {"exit", exit_f});

    return env;
}

}


text:
import jsonPath from 'JSONPath';

export default function (blob, plugin, config) {
  let results = [];
  const json = blob.toJSON();
  Object.entries(config).forEach(([path, linker]) => {
    jsonPath({ json, path, resultType: 'all' }).forEach((result) => {
      if (typeof result.value === 'string') {
        results = results.concat(
          linker.call(plugin, blob, result.parentProperty, result.value),
        );
        return;
      }

      for (const [key, value] of Object.entries(result.value)) {
        results = results.concat(linker.call(plugin, blob, key, value));
      }
    });
  });

  return results;
}


text:
package java.io;

public class UnsupportedEncodingException extends IOException {
  public UnsupportedEncodingException(String message) {
    super(message);
  }

  public UnsupportedEncodingException() {
    this(null);
  }
}


text:
package org.mockito;

import static java.lang.annotation.ElementType.*;

import static org.junit.Assume.assumeTrue;
import static org.mockito.Mockito.mock;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.assertj.core.api.Assertions;
import org.junit.Test;

public class AnnotationsAreCopiedFromMockedTypeTest {

    @Test
    public void mock_should_have_annotations_copied_from_mocked_type_at_class_level() {
        AnnotationWithDefaultValue onClassDefaultValue =
                mock(OnClass.class).getClass().getAnnotation(AnnotationWithDefaultValue.class);
        AnnotationWithCustomValue onClassCustomValue =
                mock(OnClass.class).getClass().getAnnotation(AnnotationWithCustomValue.class);

        assumeTrue(
                "Annotation copying does not apply for inline mocks",
                mock(OnClass.class).getClass() != OnClass.class);

        Assertions.assertThat(onClassDefaultValue.value()).isEqualTo("yup");
        Assertions.assertThat(onClassCustomValue.value()).isEqualTo("yay");
    }

    @Test
    public void mock_should_have_annotations_copied_from_mocked_type_on_methods() {
        AnnotationWithDefaultValue onClassDefaultValue =
                method("method", mock(OnMethod.class))
                        .getAnnotation(AnnotationWithDefaultValue.class);
        AnnotationWithCustomValue onClassCustomValue =
                method("method", mock(OnMethod.class))
                        .getAnnotation(AnnotationWithCustomValue.class);

        Assertions.assertThat(onClassDefaultValue.value()).isEqualTo("yup");
        Assertions.assertThat(onClassCustomValue.value()).isEqualTo("yay");
    }

    @Test
    public void mock_should_have_annotations_copied_from_mocked_type_on_method_parameters() {
        AnnotationWithDefaultValue onClassDefaultValue =
                firstParamOf(method("method", mock(OnMethod.class)))
                        .getAnnotation(AnnotationWithDefaultValue.class);
        AnnotationWithCustomValue onClassCustomValue =
                firstParamOf(method("method", mock(OnMethod.class)))
                        .getAnnotation(AnnotationWithCustomValue.class);

        Assertions.assertThat(onClassDefaultValue.value()).isEqualTo("yup");
        Assertions.assertThat(onClassCustomValue.value()).isEqualTo("yay");
    }

    private AnnotatedElement firstParamOf(Method method) {
        final Annotation[] firstParamAnnotations = method.getParameterAnnotations()[0];

        return new AnnotatedElement() {
            @Override
            public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
                return getAnnotation(annotationClass) != null;
            }

            @Override
            @SuppressWarnings("unchecked")
            public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
                for (Annotation firstParamAnnotation : firstParamAnnotations) {
                    if (annotationClass.isAssignableFrom(firstParamAnnotation.annotationType())) {
                        return (T) firstParamAnnotation;
                    }
                }
                return null;
            }

            @Override
            public Annotation[] getAnnotations() {
                return firstParamAnnotations;
            }

            @Override
            public Annotation[] getDeclaredAnnotations() {
                return firstParamAnnotations;
            }
        };
    }

    private Method method(String methodName, Object mock) {
        for (Method method : mock.getClass().getDeclaredMethods()) {
            if (methodName.equals(method.getName())) {
                return method;
            }
        }
        throw new IllegalArgumentException("method name not found : " + methodName);
    }

    private Field field(String fieldName, Object mock) {
        for (Field field : mock.getClass().getDeclaredFields()) {
            if (fieldName.equals(field.getName())) {
                return field;
            }
        }
        throw new IllegalArgumentException("method name not found : " + fieldName);
    }

    @AnnotationWithDefaultValue
    @AnnotationWithCustomValue("yay")
    public class OnClass {}

    public class OnMethod {
        @AnnotationWithDefaultValue
        @AnnotationWithCustomValue("yay")
        public String method(
                @AnnotationWithDefaultValue @AnnotationWithCustomValue("yay") String ignored) {
            return "";
        }
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({TYPE, METHOD, PARAMETER, FIELD})
    public @interface AnnotationWithDefaultValue {
        String value() default "yup";
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({TYPE, METHOD, PARAMETER, FIELD})
    public @interface AnnotationWithCustomValue {
        String value() default "";
    }
}


text:
The purpose of this ARM Template is to deploy a **Linux Virtual Machine with some Data Science tools** inserting a few parameters.

## The Template

Don't let the size of the template scares you. The structure is very intuitive and once that you get the gist of it, you will see how easier your life will be regarding deploying resources to Azure.

Those are the parameters on the template, most of them are already with the values, the ones that you need to inform are: **adminUsername**, **adminPassword** and **resourceGroup**. All the other parameters will be already informed.

Don't worry about changing anything on the file, either on the portal or using Azure CLI, you need to inform just the following parameters.

- *adminUsername:* Usernames can be a maximum of 20 characters and cannot end in a period (".").

- *adminPassword:* Password requirements between 12 to 72 characters and have lower and upper characters, a digit and a special character (Regex match [\W_])

- *resourceGroup:* The Resource Group that will have your deployment. We go in detail in the next section.

- *cpu-gpu:* Choose between CPU or GPU based virtual machine.

Let's rock with the Deployment.

## Deployment

There are a few ways to deploy your template.
You can use [PowerShell](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-template-deploy), [Azure CLI](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-template-deploy-cli), [Azure Portal](https://docs.microsoft.com/azure/azure-resource-manager/resource-group-template-deploy-portal) or your favorite SDK.

For this task, we going to deploy using Visual Code and the portal and a little surprise for you at the end. :D

For Azure CLI I choose to use the Visual Code with Azure CLI extensions, if you like, you can find more information [here](https://code.visualstudio.com/docs/azure/extensions). But bare in mind that you don't need to use the Visual Code, you can stick with the old good always present **Command Line** on Windows or any **bash terminal**.

### Using Azure CLI with Visual Code

type on the terminal window: **az login**

![Screen](./images/azlogin.png)

You will be redirected to the Azure Portal where you can insert your credentials and log in.

After logged in, you will see your credentials on the terminal.

To set the right subscription, type following command:

#### az account set --subscription "your subscription id"

### Resource Group

Now you need a Resource Group for our deployment. If you haven't yet created a Resource Group, you can do it now. If you are new on Azure and wonder what is a Resource Group? Bare with me! A Resource Group is a container that holds related resources for an Azure solution. The resource group includes those resources that you want to manage as a group. Simply saying, it's like a folder that contains files. Simple as that.

To create a Resource Group, you need a name and a location for your Resource Group.

For a list of locations, type: **az account list-locations**

To create the Resource group, type the command:

#### az group create --name "resource-group" --location "your location"

![Screen](./images/azgroup.png)

Super simple, right? Now that you have your **Resource Group** created, let's deploy the Virtual Machine.

#### az group deployment create --resource-group "resource-group" --template-file "path file"

![Screen](./images/azdeploy.png)

As you can see, it's running. Go grab a cup of coffee, have some fresh air and I'm sure that before you come back you will have your Virtual Machine ready.

And there we go, the deployment is succeeded:

![Screen](./images/azdeploy2.png)

### Using the Portal

At the Portal, in All Services look for **Templates**, you can favourite this service.

Click in **Add** to add your template. On General, type a name and a description for your template, and click on [OK].

![Screen](./images/aztemplate.png)

On ARM Template, replace the contents of the template with your template, and click on [OK].

![Screen](./images/aztemplate2.png)

Click on the refresh button and there is your template:

![Screen](./images/aztemplate3.png)

Open the template and click in [Deploy]

On the screen Custom Deployment, insert the information that you must be already familiar with.

Select [I agree] and click on [Purchase].

![Screen](./images/azportaldeploy3.png)

And voilà, you have your new VM deployed.

**p.s.: Pretty easy to create resources on Azure, right? But if you are the sort of IT guy that always loves automation, here is the surprise. Just click on the button below and it will automatically deploy the VM through the  Azure Portal.**

#### Important disclaimer: Azure charges you for the resources you are using, and you don't want to finish all your credits immediately, right? So, for not running out of credit, don't forget to stop the VM at the portal or even delete the Resource Group you create to avoid any unnecessary charges

## Usage

### Connect

You have two different ways to connect to the DSVM. You can connect to the solution via SSH or using the X2Go Client.

#### Connecting via SSH

You can connect to your virtual machine using SSH.

First, go to your resource (the VM) and click on connect. After that, go to the SSH tab. Finally, copy the command to connect to the VM.

![Screen](./images/connect-ssh.png)

Now, open any **bash terminal** and paste the command.

![Screen](./images/connect-ssh2.png)

It will ask you to type your password. After that, you will be connected to the VM:

![Screen](./images/connect-ssh3.png)

#### Connecting via X2Go Client

You can connect to your virtual machine using the X2Go Client. If you don't have the program, you can download it from [here](https://wiki.x2go.org/doku.php/doc:installation:x2goclient).

Then, go to your resource, and copy the virtual machine's public IP address.

![Screen](./images/connect-x2go.png)

Now, it's time to open the X2Go client. If the "New Session" window does not pop up automatically, go to Session -> New Session.

![Screen](./images/connect-x2go2.png)

On the resulting configuration window, enter the following configuration parameters on the session tab:

- Host: Enter the IP address of your VM.
- Login: Enter the username of the Linux VM.
- SSH port: Leave it at 22, the default value.
- Session Type: Change the value to XFCE.

![Screen](./images/connect-x2go3.png)

Then, click [Ok]. You will see your VM added to the right of the X2Go window. Click on the box of your VM to bring up the log-in screen.

![Screen](./images/connect-x2go4.png)

Then enter the password and select [Ok]. You may have to give X2Go permission to bypass your firewall to finish connecting.

![Screen](./images/connect-x2go5.png)

Now, you should see the graphical interface for your Ubuntu DSVM.

![Screen](./images/connect-x2go6.png)

### How to reset your password

If you forget your password to connect to the virtual machine, you will be able to change this password in a very easy way.

Go to your resource and click on **Reset Password**:

![Screen](./images/resetPassword.png)

Here, select the "Reset password" mode, and type your **username** and the **new password**. Then, update.

### How to remove your resources

#### Using the portal

On the portal, open your Resource Group, if you will not use the service or VM anymore, you can just click on the [Delete] Button.

![Screen](./images/off1.png)

You can also just stop the service or the Virtual Machine in case you need the resource. Open the resource and click on Stop.

![Screen](./images/off2.png)

Just refresh your screen and you are good to go.


text:
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'sdack-extensions' project.
// Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//	  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package de.esoco.gwt.client.ui;

import de.esoco.data.element.DateDataElement;
import de.esoco.data.element.DateListDataElement;
import de.esoco.data.element.DateListDataElement.InteractionType;
import de.esoco.data.element.DateListDataElement.TimetableDisplayStyle;

import de.esoco.ewt.build.ContainerBuilder;
import de.esoco.ewt.build.TimetableBuilder;
import de.esoco.ewt.component.Component;
import de.esoco.ewt.component.Timetable;
import de.esoco.ewt.component.Timetable.TimetableStyle;
import de.esoco.ewt.event.EWTEvent;
import de.esoco.ewt.event.EventType;
import de.esoco.ewt.style.StyleData;

import de.esoco.lib.property.HasProperties;
import de.esoco.lib.property.InteractionEventType;
import de.esoco.lib.property.StandardProperties;
import de.esoco.lib.property.StringProperties;

import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;

import static de.esoco.data.element.DateListDataElement.TIMETABLE_DAYS;
import static de.esoco.data.element.DateListDataElement.TIMETABLE_DAY_START;
import static de.esoco.data.element.DateListDataElement.TIMETABLE_DISPLAY_STYLE;
import static de.esoco.data.element.DateListDataElement.TIMETABLE_FIRST_WORKING_HOUR;
import static de.esoco.data.element.DateListDataElement.TIMETABLE_HOUR_SUBDIVISIONS;
import static de.esoco.data.element.DateListDataElement.TIMETABLE_HOUR_SUBDIVISION_HEIGHT;
import static de.esoco.data.element.DateListDataElement.TIMETABLE_SCROLL_TO_HOUR;
import static de.esoco.data.element.DateListDataElement.TIMETABLE_SHOW_WEEK_NUMBERS;

import static de.esoco.lib.property.StandardProperties.DATE;

/********************************************************************
 * The user interface implementation for date data elements.
 *
 * @author eso
 */
public class DateListDataElementUI extends DataElementUI<DateListDataElement>
{
	//~ Methods ----------------------------------------------------------------

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	protected Component createInputUI(ContainerBuilder<?>		rBuilder,
									  StyleData					rInputStyle,
									  final DateListDataElement rDataElement)
	{
		@SuppressWarnings("boxing")
		int nScrollToHour =
			rDataElement.getProperty(TIMETABLE_SCROLL_TO_HOUR, -1);

		final Timetable aTimetable =
			TimetableBuilder.addTimetable(rBuilder,
										  rInputStyle,
										  null,
										  nScrollToHour);

		updateTimetable(aTimetable, rDataElement);

		return aTimetable;
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	protected DataElementInteractionHandler<DateListDataElement> createInteractionHandler(
		DataElementPanelManager rPanelManager,
		DateListDataElement		rDataElement)
	{
		return new DateListInteractionHandler(rPanelManager, rDataElement);
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	protected void transferDataElementValueToComponent(
		DateListDataElement rElement,
		Component			rComponent)
	{
		if (rComponent instanceof Timetable)
		{
			updateTimetable((Timetable) rComponent, rElement);
		}
		else
		{
			super.transferDataElementValueToComponent(rElement, rComponent);
		}
	}

	/***************************************
	 * {@inheritDoc}
	 */
	@Override
	protected void transferInputToDataElement(
		Component			rComponent,
		DateListDataElement rElement)
	{
		if (rComponent instanceof Timetable)
		{
			Timetable rTimetable = (Timetable) rComponent;

			rElement.setSelection(rTimetable.getSelectedEvent());
			rElement.setProperty(DATE, rTimetable.getDate());
		}
		else
		{
			super.transferInputToDataElement(rComponent, rElement);
		}
	}

	/***************************************
	 * Updates a {@link Timetable} component from the associated data element.
	 *
	 * @param rTimetable   The timetable to update
	 * @param rDataElement The date data element to create the timetable for
	 */
	@SuppressWarnings("boxing")
	private void updateTimetable(
		Timetable			rTimetable,
		DateListDataElement rDataElement)
	{
		List<DateDataElement> rCalendarEvents = rDataElement.getElements();

		TimetableDisplayStyle eStyle =
			rDataElement.getProperty(TIMETABLE_DISPLAY_STYLE,
									 TimetableDisplayStyle.MONTH);

		rTimetable.setDate(rDataElement.getProperty(DATE, new Date()));
		rTimetable.setTimetableStyle(TimetableStyle.valueOf(eStyle.name()));

		if (eStyle == TimetableDisplayStyle.DAY)
		{
			int nDays = rDataElement.getIntProperty(TIMETABLE_DAYS, 1);

			rTimetable.setVisibleDays(nDays);
		}

		if (rDataElement.hasProperty(TIMETABLE_SCROLL_TO_HOUR))
		{
			rTimetable.scrollToHour(rDataElement.getProperty(TIMETABLE_SCROLL_TO_HOUR,
															 0));
		}

		if (rDataElement.hasProperty(TIMETABLE_SHOW_WEEK_NUMBERS))
		{
			rTimetable.showWeekNumbers(rDataElement.hasFlag(TIMETABLE_SHOW_WEEK_NUMBERS));
		}

		if (rDataElement.hasProperty(TIMETABLE_DAY_START))
		{
			rTimetable.setDayStart(rDataElement.getProperty(TIMETABLE_DAY_START,
															6));
		}

		rTimetable.setHourIntervals(rDataElement.getProperty(TIMETABLE_HOUR_SUBDIVISIONS,
															 -1),
									rDataElement.getProperty(TIMETABLE_HOUR_SUBDIVISION_HEIGHT,
															 -1));
		rTimetable.setWorkingHours(rDataElement.getProperty(TIMETABLE_FIRST_WORKING_HOUR,
															-1),
								   rDataElement.getProperty(TIMETABLE_FIRST_WORKING_HOUR,
															-1));

		rTimetable.clear();
		rTimetable.addEvents(rCalendarEvents);
	}

	//~ Inner Classes ----------------------------------------------------------

	/********************************************************************
	 * A date-specific interaction handler subclass.
	 *
	 * @author eso
	 */
	static class DateListInteractionHandler
		extends DataElementInteractionHandler<DateListDataElement>
	{
		//~ Constructors -------------------------------------------------------

		/***************************************
		 * @see DataElementInteractionHandler#DataElementInteractionHandler(DataElementPanelManager,
		 *      de.esoco.data.element.DataElement)
		 */
		public DateListInteractionHandler(
			DataElementPanelManager rPanelManager,
			DateListDataElement		rDataElement)
		{
			super(rPanelManager, rDataElement);
		}

		//~ Methods ------------------------------------------------------------

		/***************************************
		 * {@inheritDoc}
		 */
		@Override
		public void handleEvent(EWTEvent rEvent)
		{
			Object		    rTarget			 = rEvent.getElement();
			HasProperties   rEditedElement   = null;
			InteractionType eInteractionType = null;

			if (rTarget instanceof HasProperties)
			{
				rEditedElement = (HasProperties) rTarget;
			}

			switch (rEvent.getType())
			{
				case ACTION:

					if (rTarget instanceof Date)
					{
						StringProperties aDateElement = new StringProperties();

						aDateElement.setProperty(StandardProperties.START_DATE,
												 (Date) rTarget);
						eInteractionType = InteractionType.DATE_OPEN;
						rEditedElement   = aDateElement;
					}
					else
					{
						eInteractionType = InteractionType.OPEN;
					}

					break;

				case SELECTION:
					eInteractionType = InteractionType.SELECT;

					break;

				case ELEMENT_CREATED:
					eInteractionType = InteractionType.CREATE;

					break;

				case ELEMENT_UPDATED:
					eInteractionType = InteractionType.UPDATE;

					break;

				case ELEMENT_DELETED:
					eInteractionType = InteractionType.DELETE;

					break;

				default:
			}

			getDataElement().setInteraction(eInteractionType, rEditedElement);

			super.handleEvent(rEvent);
		}

		/***************************************
		 * {@inheritDoc}
		 */
		@Override
		protected Set<EventType> getInteractionEventTypes(
			Component				  aComponent,
			Set<InteractionEventType> rInteractionEventTypes)
		{
			return EnumSet.of(EventType.ACTION,
							  EventType.SELECTION,
							  EventType.ELEMENT_CREATED,
							  EventType.ELEMENT_UPDATED,
							  EventType.ELEMENT_DELETED);
		}
	}
}


text:
require 'celes_core'
require 'celes/version'

module Celes
  # Your code goes here...
end