text:
.. _contributing:

Contributing to semver
======================

The semver source code is managed using Git and is hosted on GitHub::

   git clone git://github.com/python-semver/python-semver

Reporting Bugs and Asking Questions
-----------------------------------

If you think you have encountered a bug in semver or have an idea for a new
feature? Great! We like to hear from you!

There are several options to participate:

* Open a new topic on our `GitHub discussion <gh_discussions>`_ page.
  Tell us our ideas or ask your questions.

* Look into our GitHub `issues`_ tracker or open a new issue.

Prerequisites
-------------

Before you make changes to the code, we would highly appreciate if you
consider the following general requirements:

* Make sure your code adheres to the `Semantic Versioning`_ specification.

* Check if your feature is covered by the Semantic Versioning specification.
  If not, ask on its GitHub project https://github.com/semver/semver.

Modifying the Code
------------------

We recommend the following workflow:

#. Fork our project on GitHub using this link:
   https://github.com/python-semver/python-semver/fork

#. Clone your forked Git repository (replace ``GITHUB_USER`` with your
   account name on GitHub)::

    $ git clone git@github.com:GITHUB_USER/python-semver.git

#. Create a new branch. You can name your branch whatever you like, but we
   recommend to use some meaningful name. If your fix is based on a
   existing GitHub issue, add also the number. Good examples would be:

   * ``feature/123-improve-foo`` when implementing a new feature in issue 123
   * ``bugfix/234-fix-security-bar`` a bugfixes for issue 234

   Use this :command:`git` command::

   $ git checkout -b feature/NAME_OF_YOUR_FEATURE

#. Work on your branch and create a pull request:

   a. Write test cases and run the complete test suite, see :ref:`testsuite`
      for details.

   b. Write a changelog entry, see section :ref:`add-changelog`.

   c. If you have implemented a new feature, document it into our
      documentation to help our reader. See section :ref:`doc` for
      further details.

   d. Create a `pull request`_. Describe in the pull request what you did
      and why. If you have open questions, ask.

#. Wait for feedback. If you receive any comments, address these.

#. After your pull request got accepted, delete your branch.

.. _testsuite:

Running the Test Suite
----------------------

We use `pytest`_ and `tox`_ to run tests against all supported Python
versions.  All test dependencies are resolved automatically.

You can decide to run the complete test suite or only part of it:

* To run all tests, use::

     $ tox

  If you have not all Python interpreters installed on your system
  it will probably give you some errors (``InterpreterNotFound``).
  To avoid such errors, use::

     $ tox --skip-missing-interpreters

  It is possible to use one or more specific Python versions. Use the ``-e``
  option and one or more abbreviations (``py36`` for Python 3.6, ``py37`` for
  Python 3.7 etc.)::

      $ tox -e py36
      $ tox -e py36,py37

  To get a complete list and a short description, run::

      $ tox -av

* To run only a specific test, pytest requires the syntax
  ``TEST_FILE::TEST_FUNCTION``.

  For example, the following line tests only the function
  :func:`test_immutable_major` in the file :file:`test_bump.py` for all
  Python versions::

      $ tox -e py36 -- tests/test_bump.py::test_should_bump_major

  By default, pytest prints only a dot for each test function. To
  reveal the executed test function, use the following syntax::

     $ tox -- -v

  You can combine the specific test function with the ``-e`` option, for
  example, to limit the tests for Python 3.6 and 3.7 only::

      $ tox -e py36,py37 -- tests/test_bump.py::test_should_bump_major

Our code is checked against formatting, style, type, and docstring issues
(`black`_, `flake8`_, `mypy`_, and `docformatter`_).
It is recommended to run your tests in combination with :command:`checks`,
for example::

   $ tox -e checks,py36,py37

.. _doc:

Documenting semver
------------------

Documenting the features of semver is very important. It gives our developers
an overview what is possible with semver, how it "feels", and how it is
used efficiently.

.. note::

    To build the documentation locally use the following command::

      $ tox -e docs

    The built documentation is available in :file:`docs/_build/html`.

A new feature is *not* complete if it isn't proberly documented. A good
documentation includes:

  * **A docstring**

    Each docstring contains a summary line, a linebreak, an optional
    directive (see next item), the description of its arguments in
    `Sphinx style`_, and an optional doctest.
    The docstring is extracted and reused in the :ref:`api` section.
    An appropriate docstring should look like this::

         def to_tuple(self) -> VersionTuple:
            """
            Convert the Version object to a tuple.

            .. versionadded:: 2.10.0
               Renamed ``VersionInfo._astuple`` to ``VersionInfo.to_tuple`` to
               make this function available in the public API.

            :return: a tuple with all the parts

            >>> semver.Version(5, 3, 1).to_tuple()
            (5, 3, 1, None, None)
            """

  * **An optional directive**

    If you introduce a new feature, change a function/method, or remove something,
    it is a good practice to introduce Sphinx directives into the docstring.
    This gives the reader an idea what version is affected by this change.

    The first required argument, ``VERSION``, defines the version when this change
    was introduced. You can choose from:

    * ``.. versionadded:: VERSION``

      Use this directive to describe a new feature.

    * ``.. versionchanged:: VERSION``

      Use this directive to describe when something has changed, for example,
      new parameters were added, changed side effects, different return values, etc.

    * ``.. deprecated:: VERSION``

      Use this directive when a feature is deprecated. Describe what should
      be used instead, if appropriate.

    Add such a directive *after* the summary line, as shown above.

  * **The documentation**

    A docstring is good, but in most cases it's too dense. API documentation
    cannot replace a good user documentation. Describe how
    to use your new feature in our documentation. Here you can give your
    readers more examples, describe it in a broader context or show
    edge cases.

.. _add-changelog:

Adding a Changelog Entry
------------------------

.. include:: ../changelog.d/README.rst
    :start-after: -text-begin-

.. _black: https://black.rtfd.io
.. _docformatter: https://pypi.org/project/docformatter/
.. _flake8: https://flake8.rtfd.io
.. _mypy: http://mypy-lang.org/
.. _issues:  https://github.com/python-semver/python-semver/issues
.. _pull request: https://github.com/python-semver/python-semver/pulls
.. _pytest: http://pytest.org/
.. _Semantic Versioning: https://semver.org
.. _Sphinx style: https://sphinx-rtd-tutorial.rtfd.io/en/latest/docstrings.html
.. _tox: https://tox.rtfd.org/
.. _gh_discussions: https://github.com/python-semver/python-semver/discussions


text:
module.exports = function (grunt) {

  const srcFile = 'build/kibana/src/optimize/babel_options.js';
  const buildFile = 'build/kibana/src/optimize/babel_options.build.js';
  const rename = require('fs').renameSync;
  const unlink = require('fs').unlinkSync;

  grunt.registerTask('_build:babelOptions', function () {
    unlink(srcFile);
    rename(buildFile, srcFile);
    grunt.file.mkdir('build/kibana/optimize');
  });

};

redpajama_set_name: RedPajamaGithub


text:
package parquet.schema;

import static parquet.schema.OriginalType.*;
import parquet.schema.PrimitiveType.PrimitiveTypeName;
import parquet.schema.Type.Repetition;

/**
 * Utility functions to convert from Java-like map and list types
 * to equivalent Parquet types.
 *
 * TODO(julien): this class appears to be unused. Is it dead code?
 */
public abstract class ConversionPatterns {
  /**
   * to preserve the difference between empty list and null when optional
   * @param repetition
   * @param alias name of the field
   * @param originalType
   * @param nested the nested repeated field
   * @return a group type
   */
  private static GroupType listWrapper(Repetition repetition, String alias, OriginalType originalType, Type nested) {
    if (!nested.isRepetition(Repetition.REPEATED)) {
      throw new IllegalArgumentException("Nested type should be repeated: " + nested);
    }
    return new GroupType(repetition, alias, originalType, nested);
  }

  public static GroupType mapType(Repetition repetition, String alias, Type keyType, Type valueType) {
    return mapType(repetition, alias, "map", keyType, valueType);
  }

  public static GroupType stringKeyMapType(Repetition repetition, String alias, String mapAlias, Type valueType) {
    return mapType(repetition, alias, mapAlias, new PrimitiveType(Repetition.REQUIRED, PrimitiveTypeName.BINARY, "key", OriginalType.UTF8), valueType);
  }

  public static GroupType stringKeyMapType(Repetition repetition, String alias, Type valueType) {
    return stringKeyMapType(repetition, alias, "map", valueType);
  }

  public static GroupType mapType(Repetition repetition, String alias, String mapAlias, Type keyType, Type valueType) {
    if (!valueType.getName().equals("value")) {
      throw new RuntimeException(valueType.getName() + " should be value");
    }
    return listWrapper(
        repetition,
        alias,
        MAP,
        new GroupType(
            Repetition.REPEATED,
            mapAlias,
            MAP_KEY_VALUE,
            keyType,
            valueType)
        );
  }

  /**
   *
   * @param repetition
   * @param alias name of the field
   * @param nestedType
   * @return
   */
  public static GroupType listType(Repetition repetition, String alias, Type nestedType) {
    return listWrapper(
        repetition,
        alias,
        LIST,
        nestedType
        );
  }
}


text:
NS_ASSUME_NONNULL_BEGIN

@protocol ABI44_0_0EXRemoteNotificationPermissionDelegate

- (void)handleDidFinishRegisteringForRemoteNotifications;

@end

@protocol ABI44_0_0EXRemoteNotificationPermissionProgressPublisher

- (void)addDelegate:(id<ABI44_0_0EXRemoteNotificationPermissionDelegate>)delegate;
- (void)removeDelegate:(id<ABI44_0_0EXRemoteNotificationPermissionDelegate>)delegate;

@end

@interface ABI44_0_0EXRemoteNotificationPermissionSingletonModule : ABI44_0_0EXSingletonModule <UIApplicationDelegate, ABI44_0_0EXRemoteNotificationPermissionProgressPublisher>

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token;
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;

@end

NS_ASSUME_NONNULL_END


text:
layout: page
title: Exquisite Aerospace Executive Retreat
date: 2016-05-24
author: Vincent Reese
tags: weekly links, java
status: published
summary: Sed non leo elit. Nullam tristique vestibulum enim ac.
banner: images/banner/office-01.jpg
booking:
  startDate: 03/15/2017
  endDate: 03/17/2017
  ctyhocn: FWANOHX
  groupCode: EAER
published: true
---
Phasellus sed dolor nunc. Morbi aliquam egestas est vel lacinia. Fusce pulvinar nulla eget sem ultrices, nec placerat nisi auctor. Praesent commodo lectus erat, eu condimentum nunc bibendum vitae. Proin fringilla placerat libero ac convallis. Nunc id neque augue. Phasellus tincidunt justo et odio egestas, nec efficitur dolor posuere. Curabitur feugiat tincidunt tortor, in tincidunt eros dictum in.
Donec convallis leo vel varius feugiat. Vestibulum et dignissim lacus. Ut sed gravida lacus. Nullam vestibulum lobortis erat, non consectetur felis mattis at. Praesent facilisis odio sit amet mattis cursus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque lacinia pretium sapien vitae hendrerit. Cras elementum eros a lacus tincidunt porta. Etiam vitae enim ipsum. Nulla et tortor a sem cursus feugiat a in mauris. Nullam varius neque molestie augue vulputate sodales.

* Mauris porta turpis ut mollis fringilla
* Pellentesque tincidunt quam a libero finibus, et rhoncus leo ultricies
* Morbi pretium nibh sit amet venenatis vehicula
* Pellentesque quis nisl elementum, eleifend metus vel, commodo purus
* Morbi id magna sed mi aliquam rhoncus ut eget dolor.

Fusce id ipsum et nisi faucibus lacinia eget ac elit. Mauris vestibulum ultrices pulvinar. Fusce viverra felis at laoreet auctor. Integer sit amet dictum metus. Fusce metus leo, lacinia et sem nec, placerat tincidunt tellus. Quisque nulla justo, imperdiet et tellus id, fringilla tincidunt ex. Integer interdum pharetra sem eu maximus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum porttitor nulla a ligula rhoncus, sit amet aliquam mi placerat. Sed fringilla iaculis leo nec venenatis. Aliquam eu risus dui.


text:
package org.motechproject.security.service.impl;

import org.motechproject.security.domain.MotechUser;
import org.motechproject.security.model.RoleDto;
import org.motechproject.security.service.AuthoritiesService;
import org.motechproject.security.service.MotechRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Implementation for {@link AuthoritiesService}. Given a MotechUser, retrieves the roles granted to that user
 * and for each role collects permissions associated with the role.
 */
@Service
public class AuthoritiesServiceImpl implements AuthoritiesService {

    private MotechRoleService motechRoleService;

    @Override
    @Transactional
    public List<GrantedAuthority> authoritiesFor(MotechUser user) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String role : user.getRoles()) {
            RoleDto motechRole = motechRoleService.getRole(role);
            if (motechRole != null) {
                for (String permission : motechRole.getPermissionNames()) {
                    authorities.add(new SimpleGrantedAuthority(permission));
                }
            }
        }
        return authorities;
    }

    @Autowired
    public void setMotechRoleService(MotechRoleService motechRoleService) {
        this.motechRoleService = motechRoleService;
    }

}


text:
1. Click the cog () icon in the top right corner
   of the right sidebar.
2. From the dropdown menu, choose the **Settings** option.

    ![settings-dropdown](/static/images/help/cog_dropdown_settings.png)

3. Click on the tabs on the left to select the settings you'd like to edit.

    ![settings](/static/images/help/display-settings.png)


text:
import sinon from 'sinon';

import eventize, {Priority} from '.';

describe('emit()', () => {
  describe('calls the listener with all given args (except the event name)', () => {
    const obj = eventize({});
    const fn1 = sinon.fake();
    const fn2 = sinon.fake();

    beforeAll(() => {
      obj.on('foo', 0, fn1);
      obj.on('*', fn2);
      obj.emit('foo', 'bar', 666);
    });

    it('named event listener', () => {
      expect(fn1.calledOnce).toBe(true);
      expect(fn2.calledWith('bar', 666)).toBeTruthy();
    });

    it('catch-em-all event listener', () => {
      expect(fn2.calledOnce).toBeTruthy();
      expect(fn2.calledWith('bar', 666)).toBeTruthy();
    });
  });

  describe('getting started example', () => {
    const obj = eventize({});
    const results: Array<string> = [];

    beforeAll(() => {
      obj.on('foo', (hello) => results.push(`hello ${hello}`));

      obj.once(['foo', 'bar'], Priority.AAA, {
        foo: (hello: string) => results.push(`hej ${hello}`),
      });

      obj.on(['foo', 'bar'], Priority.Low, (hello) =>
        results.push(`moin moin ${hello}`),
      );
    });

    it('first emit()', () => {
      obj.emit('foo', 'world');

      expect(results).toEqual(['hej world', 'hello world', 'moin moin world']);
    });

    it('second emit()', () => {
      results.length = 0;

      obj.on('foo', () => obj.off('foo'));
      obj.emit(['foo', 'bar'], 'eventize');

      expect(results).toEqual(['hello eventize', 'moin moin eventize']);
    });
  });
});


text:
describe("Transaction", function() {
  var transactions;

  beforeEach(function() {
    transactions = CoinPocketApp.Models.transactions;
    transactions.unbind("transactions.updated");
  });

  describe("transaction.confirmations", function() {

    describe("without a block height", function() {
      var transaction;

      beforeEach(function() {
        transaction = new CoinPocketApp.Models.Transaction('address', {
          tx_index: 0,
          time: 1389124087,
          out: [],
          inputs: []
        });
      });

      it("returns 0 confirmations at any block height", function() {
        expect(transaction.confirmations(280000)).toEqual(0);
        expect(transaction.confirmations(100)).toEqual(0);
        expect(transaction.confirmations(99999999)).toEqual(0);
      });

    });

    describe("at a block height of 280000", function() {
      var transaction;

      beforeEach(function() {
        transaction = new CoinPocketApp.Models.Transaction('address', {
          tx_index: 0,
          time: 1389124087,
          block_height: 280000,
          out: [],
          inputs: []
        });
      });

      it("returns 0 at 279998 blocks", function() {
        expect(transaction.confirmations(279998)).toEqual(0);
      });

      it("returns 0 at 279999 blocks", function() {
        expect(transaction.confirmations(279999)).toEqual(0);
      });

      it("returns 1 at 280000 blocks", function() {
        expect(transaction.confirmations(280000)).toEqual(1);
      });

      it("returns 2 at 280001 blocks", function() {
        expect(transaction.confirmations(280001)).toEqual(2);
      });
    });

  });

  describe("transactions#fetchRecent", function() {

    describe("with no transactions", function() {
      var result;

      beforeEach(function(done) {
        result = null;
        transactions.fetchRecent('1M3p9Gfhn9vrPgjYLZEcFSnxSM6WuCVm2Y-empty', 0, function(txs) {
          result = txs;
          done()
        });
      });

      it("is empty", function() {
        expect(result).toEqual([]);
      });

    });

    describe("with 2 credits and 1 debit", function() {
      var result;

      beforeEach(function(done) {
        result = null;
        transactions.fetchRecent('1KCVyR5Ucq3ExNhVFwbTWkeviU1ZpWpSoH-2credit1debit', 0, function(txs) {
          result = txs;
          done()
        });
      });

      it("has 3 transactions", function() {
        expect(result.length).toEqual(3);
      });

      it("is ordered by most recent first", function() {
        expect(result[0].time).toEqual(1389124087000);
        expect(result[1].time).toEqual(1389067925000);
        expect(result[2].time).toEqual(1388545895000);
      });

      it("reports each transactions amount delta", function() {
        expect(result[0].amountDelta).toEqual(1000000000);
        expect(result[1].amountDelta).toEqual(-1000000);
        expect(result[2].amountDelta).toEqual(1000000);
      });

      it("reports each transactions block height", function() {
        expect(result[0].blockHeight).toEqual(279165);
        expect(result[1].blockHeight).toEqual(279054);
        expect(result[2].blockHeight).toEqual(278021);
      });

    });

  });

  describe("transactions.updated event", function() {

    it("triggers when new transactions are fetched", function(done) {
      transactions.bind("transactions.updated", function(newTransactions) {
        done();
      });
      localStorage.removeItem('hasTransactions');
      transactions.fetchRecent('1KCVyR5Ucq3ExNhVFwbTWkeviU1ZpWpSoH-2credit1debit', 0);
    });

    it("does not trigger if there are transactions already", function(done) {
      var self = this;
      transactions.bind("transactions.updated", function(newTransactions) {
        throw new Error('should not trigger transactions.updated event');
      });
      localStorage.setItem('hasTransactions', 'true');
      transactions.fetchRecent('1KCVyR5Ucq3ExNhVFwbTWkeviU1ZpWpSoH-2credit1debit', 0, function() {
        done();
      });
    });

  });

  describe("transactions.totalCount", function() {

    it("returns 0", function(done) {
      transactions.fetchRecent('1M3p9Gfhn9vrPgjYLZEcFSnxSM6WuCVm2Y-empty', 0, function(txs) {
        expect(transactions.totalCount).toEqual(0);
        done()
      });
    });

    it("returns 3", function(done) {
      transactions.fetchRecent('1KCVyR5Ucq3ExNhVFwbTWkeviU1ZpWpSoH-2credit1debit', 0, function(txs) {
        expect(transactions.totalCount).toEqual(3);
        done()
      });
    });

  });

});


text:
<?php

// no direct access
defined('_JEXEC') or die ;
require_once dirname(__FILE__). '/juelementhelper.php';
jimport('joomla.form.formfield');

class JFormFieldJULayout extends JFormField {

	public $type = 'JULayout';

	/**
	 * Method to get the field input markup.
	 *
	 * @return	string	The field input markup.
	 * @since	1.6
	 */
	protected function getInput() {

		$document = JFactory::getDocument();

		$document->addScript(JURI::root(true)."/modules/".$this->form->getValue('module')."/admin/js/julayout.min.js");
		$document->addScript(JURI::root(true)."/modules/".$this->form->getValue('module')."/admin/js/juutilities.min.js");

		//Define layout_field_name varible to auto detect this layout field
		$script = "var layout_field_name = '".$this->name."';

		//Load layout when page load
		JU_jQuery(document).ready(function($){
				loadLayout($('#".$this->id."'));
			}
		);
		";

		$document->addScriptDeclaration($script);

		if (version_compare(JVERSION, '3.0', 'ge')) {
			$field_class = 'joomla3ge';
		} else {
			$field_class = 'joomla25';
		}

		$html = '
';
		$layouts_in_template_ori = $layouts_in_template_ext = $layouts_in_module_ori = $merged_layouts = array();

        $template = JUElementHelper::getActiveTemplate();

		$layouts = array();

		//Get all layouts in module
		$layout_path = JPATH_SITE . DS . 'modules' . DS . $this->form->getValue('module') . DS . 'tmpl';
		$folders = glob($layout_path.DS.'*', GLOB_ONLYDIR);
		if(count($folders)) {
			foreach ($folders AS $key=>$folder){
				$layout =  basename($folder);
				$layouts[$layout] = $layout;
			}
		}

		//Get all layouts in template, layouts in template has higher priority, so it will overwrite layout in module if they have the same folder name
        $layout_path = JPATH_SITE . DS . 'templates' . DS . $template . DS . 'html' . DS . $this->form->getValue('module');
		$folders = glob($layout_path.DS.'*', GLOB_ONLYDIR);
		if(count($folders)) {
			foreach ($folders AS $key=>$folder){
				$layout =  basename($folder);
				$layouts[$layout] = $layout ." [".JText::_("Template")."]";
			}
		}

		//Sort layouts by alphabet
		asort($layouts);

		$html .= JHTML::_('select.genericlist', $layouts, $this->name, 'class="'.$this->element['class'].'" onchange="loadLayout(this);"', 'id', 'title', $this->value, $this->id);
		$html .= "";
		$html .= "
";
		return $html;
	}

}
?>


text:
import { get } from 'lodash';

const getItemIsLight = (item) => {
  let isLight = get(item, 'content.isLight');
  if (typeof isLight !== 'boolean' ||
    !get(item, 'content.colors[0].value') // we want to use parent's isLight value if relying on parent's colors
  ) {
    isLight = get(item, 'parent.content.isLight');
  }
  return isLight;
};

export default getItemIsLight;


text:
namespace ppapi {

struct FileRefCreateInfo;

namespace proxy {

class PPAPI_PROXY_EXPORT FileChooserResource
    : public PluginResource,
      public NON_EXPORTED_BASE(thunk::PPB_FileChooser_API) {
 public:
  FileChooserResource(Connection connection,
                      PP_Instance instance,
                      PP_FileChooserMode_Dev mode,
                      const std::string& accept_types);
  virtual ~FileChooserResource();

  // Resource overrides.
  virtual thunk::PPB_FileChooser_API* AsPPB_FileChooser_API() override;

  // PPB_FileChooser_API.
  virtual int32_t Show(const PP_ArrayOutput& output,
                       scoped_refptr<TrackedCallback> callback) override;
  virtual int32_t ShowWithoutUserGesture(
      PP_Bool save_as,
      PP_Var suggested_file_name,
      const PP_ArrayOutput& output,
      scoped_refptr<TrackedCallback> callback) override;
  virtual int32_t Show0_5(scoped_refptr<TrackedCallback> callback) override;
  virtual PP_Resource GetNextChosenFile() override;
  virtual int32_t ShowWithoutUserGesture0_5(
      PP_Bool save_as,
      PP_Var suggested_file_name,
      scoped_refptr<TrackedCallback> callback) override;

  // Parses the accept string into the given vector.
  static void PopulateAcceptTypes(const std::string& input,
                                  std::vector<std::string>* output);

 private:
  void OnPluginMsgShowReply(
      const ResourceMessageReplyParams& params,
      const std::vector<FileRefCreateInfo>& chosen_files);

  int32_t ShowInternal(PP_Bool save_as,
                       const PP_Var& suggested_file_name,
                       scoped_refptr<TrackedCallback> callback);

  PP_FileChooserMode_Dev mode_;
  std::vector<std::string> accept_types_;

  // When using v0.6 of the API, contains the array output info.
  ArrayWriter output_;

  // When using v0.5 of the API, contains all files returned by the current
  // show callback that haven't yet been given to the plugin. The plugin will
  // repeatedly call us to get the next file, and we'll vend those out of this
  // queue, removing them when ownership has transferred to the plugin.
  std::queue<PP_Resource> file_queue_;

  scoped_refptr<TrackedCallback> callback_;

  DISALLOW_COPY_AND_ASSIGN(FileChooserResource);
};

}  // namespace proxy
}  // namespace ppapi

#endif  // PPAPI_PROXY_FILE_CHOOSER_RESOURCE_H_


text:
package com.bloomberg.sparkflow.dc

import com.holdenkarau.spark.testing.SharedSparkContext
import org.apache.spark.mllib.clustering.LDA
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.linalg.Vector
import org.apache.spark.rdd.RDD
import org.scalatest._

import scala.util.Random
import com.bloomberg.sparkflow._

/**
  * Created by ngoehausen on 3/23/16.
  */
class DRTest extends FunSuite with SharedSparkContext with ShouldMatchers {

  test("normalize"){

    val numbers: DC[Int] = parallelize(1 to 10)
    val doubles: DC[Double] = numbers.map(_.toDouble)
    val sum: DR[Double] = doubles.sum
    val normalized: DC[Double] = doubles.withResult(sum).map{case (number, s) => number / s}

    val normalizedRDD = normalized.getRDD(sc)
    normalizedRDD.foreach(println)
  }

  test("machineLearning"){

    /* Regular spark

    val randomVecs = sc.parallelize(1 to 100).map(i => Vectors.dense(Seq.fill(10)(Random.nextDouble()).toArray))
    val corpus = randomVecs.zipWithUniqueId().map{case (k,v) => (v,k)}
    val ldaModel = new LDA().setK(3).run(corpus)
    println(ldaModel)
     */
//    val randomVecs = parallelize(1 to 100).map(i => Vectors.dense(Seq.fill(10)(Random.nextDouble()).toArray))
//    val corpus = randomVecs.zipWithUniqueId().map{case (k,v) => (v,k)}
//    val ldaModel = new LDA().setK(3).run(corpus)

    val randomVecs = parallelize(1 to 100).map(i => Vectors.dense(Seq.fill(10)(Random.nextDouble()).toArray))
    val corpus = randomVecs.zipWithUniqueId().map{case (k,v) => (v,k)}
    val ldaModel = corpus.mapToResult(rdd => new LDA().setK(3).run(rdd))

  }

  test("regularSpark"){
    val numbers: RDD[Int] = sc.parallelize(1 to 10)
    val doubles: RDD[Double] = numbers.map(_.toDouble)
    val sum: Double = doubles.sum()
    val normalized: RDD[Double] = doubles.map(_ / sum)
  }
}


text:
test_description='git-merge

Do not overwrite changes.'

. ./test-lib.sh

test_expect_success 'setup' '
	test_commit c0 c0.c &&
	test_commit c1 c1.c &&
	test_commit c1a c1.c "c1 a" &&
	git reset --hard c0 &&
	test_commit c2 c2.c &&
	git reset --hard c0 &&
	mkdir sub &&
	echo "sub/f" > sub/f &&
	mkdir sub2 &&
	echo "sub2/f" > sub2/f &&
	git add sub/f sub2/f &&
	git commit -m sub &&
	git tag sub &&
	echo "VERY IMPORTANT CHANGES" > important
'

test_expect_success 'will not overwrite untracked file' '
	git reset --hard c1 &&
	cp important c2.c &&
	test_must_fail git merge c2 &&
	test_path_is_missing .git/MERGE_HEAD &&
	test_cmp important c2.c
'

test_expect_success 'will overwrite tracked file' '
	git reset --hard c1 &&
	cp important c2.c &&
	git add c2.c &&
	git commit -m important &&
	git checkout c2
'

test_expect_success 'will not overwrite new file' '
	git reset --hard c1 &&
	cp important c2.c &&
	git add c2.c &&
	test_must_fail git merge c2 &&
	test_path_is_missing .git/MERGE_HEAD &&
	test_cmp important c2.c
'

test_expect_success 'will not overwrite staged changes' '
	git reset --hard c1 &&
	cp important c2.c &&
	git add c2.c &&
	rm c2.c &&
	test_must_fail git merge c2 &&
	test_path_is_missing .git/MERGE_HEAD &&
	git checkout c2.c &&
	test_cmp important c2.c
'

test_expect_success 'will not overwrite removed file' '
	git reset --hard c1 &&
	git rm c1.c &&
	git commit -m "rm c1.c" &&
	cp important c1.c &&
	test_must_fail git merge c1a &&
	test_cmp important c1.c
'

test_expect_success 'will not overwrite re-added file' '
	git reset --hard c1 &&
	git rm c1.c &&
	git commit -m "rm c1.c" &&
	cp important c1.c &&
	git add c1.c &&
	test_must_fail git merge c1a &&
	test_path_is_missing .git/MERGE_HEAD &&
	test_cmp important c1.c
'

test_expect_success 'will not overwrite removed file with staged changes' '
	git reset --hard c1 &&
	git rm c1.c &&
	git commit -m "rm c1.c" &&
	cp important c1.c &&
	git add c1.c &&
	rm c1.c &&
	test_must_fail git merge c1a &&
	test_path_is_missing .git/MERGE_HEAD &&
	git checkout c1.c &&
	test_cmp important c1.c
'

test_expect_success 'will not overwrite untracked subtree' '
	git reset --hard c0 &&
	rm -rf sub &&
	mkdir -p sub/f &&
	cp important sub/f/important &&
	test_must_fail git merge sub &&
	test_path_is_missing .git/MERGE_HEAD &&
	test_cmp important sub/f/important
'

cat >expect <<\EOF
error: The following untracked working tree files would be overwritten by merge:
	sub
	sub2
Please move or remove them before you can merge.
EOF

test_expect_success 'will not overwrite untracked file in leading path' '
	git reset --hard c0 &&
	rm -rf sub &&
	cp important sub &&
	cp important sub2 &&
	test_must_fail git merge sub 2>out &&
	test_cmp out expect &&
	test_path_is_missing .git/MERGE_HEAD &&
	test_cmp important sub &&
	test_cmp important sub2 &&
	rm -f sub sub2
'

test_expect_success SYMLINKS 'will not overwrite untracked symlink in leading path' '
	git reset --hard c0 &&
	rm -rf sub &&
	mkdir sub2 &&
	ln -s sub2 sub &&
	test_must_fail git merge sub &&
	test_path_is_missing .git/MERGE_HEAD
'

test_expect_success SYMLINKS 'will not be confused by symlink in leading path' '
	git reset --hard c0 &&
	rm -rf sub &&
	ln -s sub2 sub &&
	git add sub &&
	git commit -m ln &&
	git checkout sub
'

cat >expect <<\EOF
error: Untracked working tree file 'c0.c' would be overwritten by merge.
fatal: read-tree failed
EOF

test_expect_success 'will not overwrite untracked file on unborn branch' '
	git reset --hard c0 &&
	git rm -fr . &&
	git checkout --orphan new &&
	cp important c0.c &&
	test_must_fail git merge c0 2>out &&
	test_i18ncmp out expect
'

test_expect_success 'will not overwrite untracked file on unborn branch .git/MERGE_HEAD sanity etc.' '
	test_when_finished "rm c0.c" &&
	test_path_is_missing .git/MERGE_HEAD &&
	test_cmp important c0.c
'

test_expect_success 'failed merge leaves unborn branch in the womb' '
	test_must_fail git rev-parse --verify HEAD
'

test_expect_success 'set up unborn branch and content' '
	git symbolic-ref HEAD refs/heads/unborn &&
	rm -f .git/index &&
	echo foo > tracked-file &&
	git add tracked-file &&
	echo bar > untracked-file
'

test_expect_success 'will not clobber WT/index when merging into unborn' '
	git merge master &&
	grep foo tracked-file &&
	git show :tracked-file >expect &&
	grep foo expect &&
	grep bar untracked-file
'

test_done


text:
#ifndef __NVME_COMMON_H__
#define __NVME_COMMON_H__

#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <unistd.h>
#include <limits.h>
#include <time.h>
#include <sys/types.h>
#include <sys/cdefs.h>
#include <sys/queue.h>
#include <linux/types.h>

#include "libnvme/nvme.h"
#include "nvme_arch.h"
#include "nvme_log.h"

/*
 * Check if a branch is likely to be taken.
 */
#ifndef likely
#define likely(x)  __builtin_expect((x),1)
#endif /* likely */

/*
 * Check if a branch is unlikely to be taken.
 */
#ifndef unlikely
#define unlikely(x)  __builtin_expect((x),0)
#endif /* unlikely */

#ifndef typeof
#define typeof __typeof__
#endif

/*
 * Trim whitespace from a string in place.
 */
extern void nvme_str_trim(char *s);

/*
 * Split string into tokens
 */
extern int nvme_str_split(char *string, int stringlen,
			  char **tokens, int maxtokens, char delim);

/*
 * Converts a numeric string to the equivalent uint64_t value.
 * As well as straight number conversion, also recognises the suffixes
 * k, m and g for kilobytes, megabytes and gigabytes respectively.
 *
 * If a negative number is passed in, zero is returned.
 * Zero is also returned in the case of an error with the
 * strtoull call in the function.
 */
static inline size_t nvme_str2size(const char *str)
{
	unsigned long long size;
	char *endptr;

	while (isspace((int)*str))
		str++;
	if (*str == '-')
		return 0;

	errno = 0;
	size = strtoull(str, &endptr, 0);
	if (errno)
		return 0;

	/* Allow 1 space gap between number and unit */
	if (*endptr == ' ')
		endptr++;

	switch (*endptr){
	case 'G':
	case 'g':
		size *= 1024;
		/* Fall through */
	case 'M':
	case 'm':
		/* Fall through */
		size *= 1024;
	case 'K':
	case 'k':
		/* Fall through */
		size *= 1024;
	}

	return size;
}

/*
 * Function to read a single numeric value from a file on the filesystem.
 * Used to read information from files on /sys
 */
extern int nvme_parse_sysfs_value(const char *filename, unsigned long *val);

/*
 * Get a file size in Bytes.
 */
extern uint64_t nvme_file_get_size(int fd);

/*
 * Get a block device block size in Bytes.
 */
extern ssize_t nvme_dev_get_blocklen(int fd);

/*
 * Get current time in nano seconds.
 */
static inline unsigned long long nvme_time_nsec(void)
{
	struct timespec ts;

	clock_gettime(CLOCK_REALTIME, &ts);

	return (unsigned long long) ts.tv_sec * 1000000000ULL
		+ (unsigned long long) ts.tv_nsec;
}

/*
 * Get current time in micro seconds.
 */
static inline unsigned long long nvme_time_usec(void)
{
	return nvme_time_nsec() / 1000;
}

/*
 * Get current time in milli seconds.
 */
static inline unsigned long long nvme_time_msec(void)
{
	return nvme_time_nsec() / 1000000;
}

/*
 * PAUSE instruction for tight loops (avoid busy waiting)
 */
#ifdef __SSE2__
#include <emmintrin.h>
static inline void nvme_pause(void)
{
	_mm_pause();
}
#else
static inline void nvme_pause(void) {}
#endif

/*
 * Micro-seconds sleep.
 */
static inline void nvme_usleep(int usecs)
{
	struct timeval tv;

	tv.tv_sec = usecs / 1000000;
	tv.tv_usec = usecs % 1000000;
	select(0, NULL, NULL, NULL, &tv);
}

/*
 * Milli-seconds sleep.
 */
static inline void nvme_msleep(int msecs)
{
	struct timeval tv;

	tv.tv_sec = msecs / 1000;
	tv.tv_usec = (msecs - tv.tv_sec * 1000) * 1000;
	select(0, NULL, NULL, NULL, &tv);
}

/*
 * Provide notification of a critical non-recoverable error and stop.
 * This function should not be called directly. Use nvme_panic() instead.
 */
extern void __nvme_panic(const char *funcname , const char *format, ...)
#ifdef __GNUC__
#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 2))
	__attribute__((cold))
#endif
#endif
	__attribute__((noreturn))
	__attribute__((format(printf, 2, 3)));

/*
 * Provide notification of a critical non-recoverable error
 * and terminate execution abnormally.
 */
#define nvme_panic(format, args...)	\
	__nvme_panic(__FUNCTION__, format, ## args)

/*
 * Macro to evaluate a scalar expression and
 * abort the program if the assertion is false.
 */
#define _nvme_assert_default(exp)					\
	do {								\
		if (unlikely(!(exp)))					\
			nvme_panic("line %d, assert %s failed\n",	\
				   __LINE__, # exp);			\
	} while (0)

#define _nvme_assert_msg(exp, msg)					\
	do {								\
		if (unlikely(!(exp)))					\
			nvme_panic("%s\n", msg);			\
	} while (0)

#define _NVME_GET_ASSERT_OVERLOAD(_1, _2, NAME, args...) NAME

#define nvme_assert(args...) \
	_NVME_GET_ASSERT_OVERLOAD(args,					\
				  _nvme_assert_msg,			\
				  _nvme_assert_default)			\
				  (args)

/*
 * Macro to return the minimum of two numbers
 */
#define nvme_min(a, b) ({	     \
		typeof (a) _a = (a); \
		typeof (b) _b = (b); \
		_a < _b ? _a : _b;   \
	})

/*
 * Macro to return the maximum of two numbers
 */
#define nvme_max(a, b) ({	     \
		typeof (a) _a = (a); \
		typeof (b) _b = (b); \
		_a > _b ? _a : _b;   \
	})

/*
 * Returns true if n is a power of 2.
 */
static inline int nvme_is_pow2(__u64 v)
{
	return v && !(v & (v - 1));
}

/*
 * Return the power of 2 immediately after v.
 */
static inline __u64 nvme_align_pow2(__u64 v)
{
	v--;
	v |= v >> 1;
	v |= v >> 2;
	v |= v >> 4;
	v |= v >> 8;
	v |= v >> 16;
	v |= v >> 32;

	return v + 1;
}

/*
 * Calculate log2 of a power of 2 size.
 */
static inline size_t nvme_log2(size_t size)
{
	size_t bits = 0;

        if (!nvme_is_pow2(size))
                return 0;

        while (size >>= 1)
		bits++;

	return bits;
}

/*
 * Handle alignements.
 */
#define nvme_align_down(val, align)	\
	((val) & (~((typeof(val))((align) - 1))))
#define nvme_align_up(val, align)	\
	nvme_align_down((val) + (align) - 1, (align))

/*
 * Test a bit value.
 */
static inline int test_bit(__u8 *bitmap, unsigned int bit)
{
        return bitmap[bit >> 3] & (1U << (bit & 0x7));
}

/*
 * Set a bit.
 */
static inline void set_bit(__u8 *bitmap, unsigned int bit)
{
        bitmap[bit >> 3] |= 1U << (bit & 0x7);
}

/*
 * Clear a bit.
 */
static inline void clear_bit(__u8 *bitmap, unsigned int bit)
{
        bitmap[bit >> 3] &= ~(1U << (bit & 0x7));
}

/*
 * Find the first zero bit in a bitmap of size nr_bits.
 * If no zero bit is found, return -1.
 */
static inline int find_first_zero_bit(__u8 *bitmap, unsigned int nr_bits)
{
	__u64 *b = (__u64 *)bitmap;
	unsigned int i, j, bit, count = (nr_bits + 63) >> 6;

	for(i = 0; i < count; i++) {
		if (b[i] != ~0UL)
			break;
	}

	bit = i << 6;
	for (j = bit; j < nr_bits; j++) {
		if (!test_bit(bitmap, j))
			return j;
	}

	return -1;
}

/*
 * Close all open controllers on exit.
 * Defined in lib/nvme/nvme.c
 */
extern void nvme_ctrlr_cleanup(void);

#endif /* __NVME_COMMON_H__ */


text:
<?php

namespace Diploma\BackOfficeBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class TaskControllerTest extends WebTestCase
{
    public function testTask()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', 'post/');
    }
}


text:
TubeTK Convert4DImageTo3DImages
=============================

Separates a 4D image into a series of 3D images.
---
*This file is part of [TubeTK](http://www.tubetk.org). TubeTK is developed by [Kitware, Inc.](https://www.kitware.com) and licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0).*


text:
// Copyright 2017 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.

package kbfscrypto

import (
	"bytes"
	"encoding/hex"
	"fmt"
	"reflect"

	"github.com/keybase/client/go/kbfs/cache"
	"github.com/keybase/client/go/kbfs/kbfscodec"
	"github.com/keybase/client/go/kbfs/kbfshash"
	"github.com/keybase/client/go/libkb"
	"github.com/pkg/errors"
	"golang.org/x/crypto/nacl/box"
	"golang.org/x/crypto/nacl/secretbox"
)

// EncryptionVer denotes a version for the encryption method.
type EncryptionVer int

const (
	// EncryptionSecretbox is the encryption version that uses
	// nacl/secretbox or nacl/box.
	EncryptionSecretbox EncryptionVer = 1
	// EncryptionSecretboxWithKeyNonce is the encryption version that
	// uses nacl/secretbox or nacl/box, with a nonce derived from a
	// secret key.
	EncryptionSecretboxWithKeyNonce EncryptionVer = 2
)

func (v EncryptionVer) String() string {
	switch v {
	case EncryptionSecretbox:
		return "EncryptionSecretbox"
	case EncryptionSecretboxWithKeyNonce:
		return "EncryptionSecretboxWithKeyNonce"
	default:
		return fmt.Sprintf("EncryptionVer(%d)", v)
	}
}

// ToHashType returns the type of the hash that should be used for the
// given encryption version.
func (v EncryptionVer) ToHashType() kbfshash.HashType {
	switch v {
	case EncryptionSecretbox:
		return kbfshash.SHA256Hash
	case EncryptionSecretboxWithKeyNonce:
		return kbfshash.SHA256HashV2
	default:
		return kbfshash.InvalidHash
	}
}

// encryptedData is encrypted data with a nonce and a version.
type encryptedData struct {
	// Exported only for serialization purposes. Should only be
	// used by implementations of Crypto.
	Version       EncryptionVer `codec:"v"`
	EncryptedData []byte        `codec:"e"`
	Nonce         []byte        `codec:"n"`
}

// Size implements the cache.Measurable interface.
func (ed encryptedData) Size() int {
	return cache.IntSize /* ed.Version */ +
		cache.PtrSize + len(ed.EncryptedData) + cache.PtrSize + len(ed.Nonce)
}

func (ed encryptedData) String() string {
	if reflect.DeepEqual(ed, encryptedData{}) {
		return "EncryptedData{}"
	}
	return fmt.Sprintf("%s{data=%s, nonce=%s}",
		ed.Version, hex.EncodeToString(ed.EncryptedData),
		hex.EncodeToString(ed.Nonce))
}

func (ed encryptedData) Nonce24() (nonce [24]byte, err error) {
	if len(ed.Nonce) != len(nonce) {
		return nonce, errors.WithStack(InvalidNonceError{ed.Nonce})
	}
	copy(nonce[:], ed.Nonce)
	return nonce, nil
}

// encryptDataWithNonce encrypts the given data with the given
// symmetric key and nonce.
func encryptDataWithNonce(
	data []byte, key [32]byte, nonce [24]byte, ver EncryptionVer) (
	encryptedData, error) {
	sealedData := secretbox.Seal(nil, data, &nonce, &key)

	return encryptedData{
		Version:       ver,
		Nonce:         nonce[:],
		EncryptedData: sealedData,
	}, nil
}

// encryptData encrypts the given data with the given symmetric key.
func encryptData(data []byte, key [32]byte) (encryptedData, error) {
	var nonce [24]byte
	err := RandRead(nonce[:])
	if err != nil {
		return encryptedData{}, err
	}

	return encryptDataWithNonce(data, key, nonce, EncryptionSecretbox)
}

// decryptData decrypts the given encrypted data with the given
// symmetric key and nonce.
func decryptData(
	encryptedData encryptedData, key [32]byte, nonce [24]byte) ([]byte, error) {
	switch encryptedData.Version {
	case EncryptionSecretbox:
		// We're good, no nonce check needed.
	case EncryptionSecretboxWithKeyNonce:
		if !bytes.Equal(nonce[:], encryptedData.Nonce) {
			return nil, errors.WithStack(InvalidNonceError{encryptedData.Nonce})
		}
	default:
		return nil, errors.WithStack(
			UnknownEncryptionVer{encryptedData.Version})
	}

	decryptedData, ok := secretbox.Open(
		nil, encryptedData.EncryptedData, &nonce, &key)
	if !ok {
		return nil, errors.WithStack(
			libkb.DecryptionError{Cause: libkb.ErrorCause{Err: errors.New("Cannot open secret box")}})
	}

	return decryptedData, nil
}

// EncryptedTLFCryptKeyClientHalf is an encrypted
// TLFCryptKeyClientHalf object.
type EncryptedTLFCryptKeyClientHalf struct {
	encryptedData
}

// EncryptTLFCryptKeyClientHalf encrypts a TLFCryptKeyClientHalf
// using both a TLF's ephemeral private key and a device pubkey.
func EncryptTLFCryptKeyClientHalf(
	privateKey TLFEphemeralPrivateKey, publicKey CryptPublicKey,
	clientHalf TLFCryptKeyClientHalf) (
	encryptedClientHalf EncryptedTLFCryptKeyClientHalf, err error) {
	var nonce [24]byte
	err = RandRead(nonce[:])
	if err != nil {
		return EncryptedTLFCryptKeyClientHalf{}, err
	}

	keypair, err := libkb.ImportKeypairFromKID(publicKey.KID())
	if err != nil {
		return EncryptedTLFCryptKeyClientHalf{}, errors.WithStack(err)
	}

	dhKeyPair, ok := keypair.(libkb.NaclDHKeyPair)
	if !ok {
		return EncryptedTLFCryptKeyClientHalf{}, errors.WithStack(
			libkb.KeyCannotEncryptError{})
	}

	clientHalfData := clientHalf.Data()
	privateKeyData := privateKey.Data()
	encryptedBytes := box.Seal(nil, clientHalfData[:], &nonce, (*[32]byte)(&dhKeyPair.Public), &privateKeyData)

	return EncryptedTLFCryptKeyClientHalf{
		encryptedData{
			Version:       EncryptionSecretbox,
			EncryptedData: encryptedBytes,
			Nonce:         nonce[:],
		},
	}, nil
}

// EncryptedPrivateMetadata is an encrypted PrivateMetadata object.
type EncryptedPrivateMetadata struct {
	encryptedData
}

// EncryptEncodedPrivateMetadata encrypts an encoded PrivateMetadata
// object.
func EncryptEncodedPrivateMetadata(encodedPrivateMetadata []byte, key TLFCryptKey) (
	encryptedPrivateMetadata EncryptedPrivateMetadata, err error) {
	encryptedData, err := encryptData(encodedPrivateMetadata, key.Data())
	if err != nil {
		return EncryptedPrivateMetadata{}, err
	}

	return EncryptedPrivateMetadata{encryptedData}, nil
}

// DecryptPrivateMetadata decrypts a PrivateMetadata object, but does
// not decode it.
func DecryptPrivateMetadata(
	encryptedPrivateMetadata EncryptedPrivateMetadata, key TLFCryptKey) (
	[]byte, error) {
	if encryptedPrivateMetadata.encryptedData.Version ==
		EncryptionSecretboxWithKeyNonce {
		// Only blocks should have v2 encryption.
		return nil, errors.WithStack(InvalidEncryptionVer{
			encryptedPrivateMetadata.encryptedData.Version})
	}

	nonce, err := encryptedPrivateMetadata.encryptedData.Nonce24()
	if err != nil {
		return nil, err
	}

	return decryptData(
		encryptedPrivateMetadata.encryptedData, key.Data(), nonce)
}

// EncryptedBlock is an encrypted Block object.
type EncryptedBlock struct {
	encryptedData
}

// EncryptPaddedEncodedBlock encrypts a padded, encoded block.
func EncryptPaddedEncodedBlock(
	paddedEncodedBlock []byte, tlfCryptKey TLFCryptKey,
	blockServerHalf BlockCryptKeyServerHalf, ver EncryptionVer) (
	encryptedBlock EncryptedBlock, err error) {
	var ed encryptedData
	switch ver {
	case EncryptionSecretbox:
		key := UnmaskBlockCryptKey(blockServerHalf, tlfCryptKey)
		ed, err = encryptData(paddedEncodedBlock, key.Data())
		if err != nil {
			return EncryptedBlock{}, err
		}
	case EncryptionSecretboxWithKeyNonce:
		key := MakeBlockHashKey(blockServerHalf, tlfCryptKey)
		ed, err = encryptDataWithNonce(
			paddedEncodedBlock, key.cryptKey(), key.nonce(),
			EncryptionSecretboxWithKeyNonce)
		if err != nil {
			return EncryptedBlock{}, err
		}
	default:
		return EncryptedBlock{}, errors.WithStack(UnknownEncryptionVer{ver})
	}

	return EncryptedBlock{ed}, nil
}

// DecryptBlock decrypts a block, but does not unpad or decode it.
func DecryptBlock(
	encryptedBlock EncryptedBlock, tlfCryptKey TLFCryptKey,
	blockServerHalf BlockCryptKeyServerHalf) ([]byte, error) {
	switch encryptedBlock.encryptedData.Version {
	case EncryptionSecretbox:
		nonce, err := encryptedBlock.encryptedData.Nonce24()
		if err != nil {
			return nil, err
		}

		key := UnmaskBlockCryptKey(blockServerHalf, tlfCryptKey)
		return decryptData(encryptedBlock.encryptedData, key.Data(), nonce)
	case EncryptionSecretboxWithKeyNonce:
		key := MakeBlockHashKey(blockServerHalf, tlfCryptKey)
		return decryptData(
			encryptedBlock.encryptedData, key.cryptKey(), key.nonce())
	default:
		return nil, errors.WithStack(
			InvalidEncryptionVer{encryptedBlock.encryptedData.Version})
	}
}

// EncryptedTLFCryptKeys is an encrypted TLFCryptKey array.
type EncryptedTLFCryptKeys struct {
	encryptedData
}

// EncryptTLFCryptKeys encrypts a TLFCryptKey array.
func EncryptTLFCryptKeys(codec kbfscodec.Codec, oldKeys []TLFCryptKey, key TLFCryptKey) (
	encryptedTLFCryptKeys EncryptedTLFCryptKeys, err error) {
	encodedKeys, err := codec.Encode(oldKeys)
	if err != nil {
		return EncryptedTLFCryptKeys{}, err
	}

	encryptedData, err := encryptData(encodedKeys, key.Data())
	if err != nil {
		return EncryptedTLFCryptKeys{}, err
	}

	return EncryptedTLFCryptKeys{encryptedData}, nil
}

// DecryptTLFCryptKeys decrypts a TLFCryptKey array, but does not
// decode it.
func DecryptTLFCryptKeys(
	codec kbfscodec.Codec, encryptedTLFCryptKeys EncryptedTLFCryptKeys, key TLFCryptKey) (
	[]TLFCryptKey, error) {
	if encryptedTLFCryptKeys.encryptedData.Version ==
		EncryptionSecretboxWithKeyNonce {
		// Only blocks should have v2 encryption.
		return nil, errors.WithStack(
			InvalidEncryptionVer{encryptedTLFCryptKeys.encryptedData.Version})
	}

	nonce, err := encryptedTLFCryptKeys.encryptedData.Nonce24()
	if err != nil {
		return nil, err
	}

	encodedKeys, err := decryptData(
		encryptedTLFCryptKeys.encryptedData, key.Data(), nonce)
	if err != nil {
		return nil, err
	}

	var oldKeys []TLFCryptKey
	err = codec.Decode(encodedKeys, &oldKeys)
	if err != nil {
		return nil, err
	}

	return oldKeys, nil
}

// EncryptedMerkleLeaf is an encrypted MerkleLeaf object.
type EncryptedMerkleLeaf struct {
	encryptedData
}

// MakeEncryptedMerkleLeaf constructs an EncryptedMerkleLeaf.
func MakeEncryptedMerkleLeaf(
	version EncryptionVer, data []byte, nonce *[24]byte) EncryptedMerkleLeaf {
	return EncryptedMerkleLeaf{
		encryptedData{
			Version:       version,
			EncryptedData: data,
			Nonce:         nonce[:],
		},
	}
}

// PrepareMerkleLeaf verifies the correctness of the given leaf, and
// returns its nonce.
func PrepareMerkleLeaf(encryptedMerkleLeaf EncryptedMerkleLeaf) (
	nonce [24]byte, err error) {
	if encryptedMerkleLeaf.Version != EncryptionSecretbox {
		return nonce,
			errors.WithStack(UnknownEncryptionVer{
				Ver: encryptedMerkleLeaf.Version})
	}

	if len(encryptedMerkleLeaf.Nonce) != len(nonce) {
		return nonce,
			errors.WithStack(InvalidNonceError{
				Nonce: encryptedMerkleLeaf.Nonce})
	}
	copy(nonce[:], encryptedMerkleLeaf.Nonce)
	return nonce, nil
}

// DecryptMerkleLeaf decrypts an EncryptedMerkleLeaf using the given
// private TLF key and ephemeral public key.
func DecryptMerkleLeaf(
	privateKey TLFPrivateKey, publicKey TLFEphemeralPublicKey,
	encryptedMerkleLeaf EncryptedMerkleLeaf) ([]byte, error) {
	nonce, err := PrepareMerkleLeaf(encryptedMerkleLeaf)
	if err != nil {
		return nil, err
	}

	publicKeyData := publicKey.Data()
	privateKeyData := privateKey.Data()
	decryptedData, ok := box.Open(nil, encryptedMerkleLeaf.EncryptedData,
		&nonce, &publicKeyData, &privateKeyData)
	if !ok {
		return nil, errors.WithStack(
			libkb.DecryptionError{Cause: libkb.ErrorCause{Err: errors.New("Cannot open box")}})
	}
	return decryptedData, nil
}


text: FROM prima/filebeat:5-rc


text:
package rest

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"

	"github.com/gorilla/mux"
)

const (
	// resourceIDKey is the name of the URL path variable for a resource ID.
	resourceIDKey = "resource_id"

	// formatKey is the name of the query string variable for the response format.
	formatKey = "format"

	// versionKey is the name of the URL path variable for the endpoint version.
	versionKey = "version"

	// cursorKey is the name of the query string variable for the results cursor.
	cursorKey = "next"

	// limitKey is the name of the query string variable for the results limit.
	limitKey = "limit"

	requestKey int = iota
	statusKey
	errorKey
	resultKey
)

// RequestContext contains the context information for the current HTTP request. Context
// values are stored on the http.Request context.
type RequestContext interface {
	// Value returns the value associated with this context for key, or nil
	// if no value is associated with key. Successive calls to Value with
	// the same key returns the same result.
	Value(key interface{}) interface{}

	// WithValue returns a new RequestContext with the provided key-value pair and this context
	// as the parent.
	WithValue(interface{}, interface{}) RequestContext

	// ValueWithDefault returns the context value for the given key. If there's no such value,
	// the provided default is returned.
	ValueWithDefault(interface{}, interface{}) interface{}

	// Request returns the *http.Request associated with context using NewContext, if any.
	Request() (*http.Request, bool)

	// NextURL returns the URL to use to request the next page of results using the current
	// cursor. If there is no cursor for this request or the URL fails to be built, an empty
	// string is returned with the error set.
	NextURL() (string, error)

	// BuildURL builds a url.URL struct for a resource name & method.
	//
	// resourceName should have the same value as the handler's ResourceName method.
	//
	// method is the HandleMethod constant that corresponds with the resource
	// method for which to build the URL. E.g. HandleCreate with build a URL that
	// corresponds with the CreateResource method.
	//
	// All URL variables should be named in the vars map.
	BuildURL(resourceName string, method HandleMethod, vars RouteVars) (*url.URL, error)

	// ResponseFormat returns the response format for the request, defaulting to "json" if
	// one is not specified using the "format" query parameter.
	ResponseFormat() string

	// ResourceID returns the resource id for the request, defaulting to an empty string if
	// there isn't one.
	ResourceID() string

	// Version returns the API version for the request, defaulting to an empty string if
	// one is not specified in the request path.
	Version() string

	// Status returns the current HTTP status code that will be returned for the request,
	// defaulting to 200 if one hasn't been set yet.
	Status() int

	// setStatus sets the HTTP status code to be returned for the request.
	setStatus(int) RequestContext

	// Error returns the current error for the request or nil if no errors have been set.
	Error() error

	// setError sets the current error for the request.
	setError(error) RequestContext

	// Result returns the result resource for the request or nil if no result has been set.
	Result() interface{}

	// setResult sets the result resource for the request.
	setResult(interface{}) RequestContext

	// Cursor returns the current result cursor for the request, defaulting to an empty
	// string if one hasn't been set.
	Cursor() string

	// setCursor sets the current result cursor for the request.
	setCursor(string) RequestContext

	// Limit returns the maximum number of results that should be fetched.
	Limit() int

	// Messages returns all of the messages set by the request handler to be included in
	// the response.
	Messages() []string

	// AddMessage adds a message to the request messages to be included in the response.
	AddMessage(string)

	// Header returns the header key-value pairs for the request.
	Header() http.Header

	// Body returns a buffer containing the raw body of the request.
	Body() *bytes.Buffer

	// ResponseWriter Access to Response Writer Interface to allow for setting Response Header values
	ResponseWriter() http.ResponseWriter
}

// requestContext is an implementation of the RequestContext interface.
type requestContext struct {
	req      *http.Request
	body     *bytes.Buffer
	writer   http.ResponseWriter
	router   *mux.Router
	messages []string
}

func setValueOnRequestContext(req *http.Request, key, val interface{}) *http.Request {
	ctx := context.WithValue(req.Context(), key, val)
	return req.WithContext(ctx)
}

// NewContext returns a RequestContext populated with parameters from the request path and
// query string.
func NewContext(req *http.Request, writer http.ResponseWriter) RequestContext {
	for key, value := range req.URL.Query() {
		var val interface{}
		val = value

		// Query string values are slices (e.g. ?foo=bar,baz,qux yields
		// [bar, baz, qux] for foo), but we unbox single values (e.g. ?foo=bar
		// yields bar for foo).
		if len(value) == 1 {
			val = value[0]
		}

		req = setValueOnRequestContext(req, key, val)
	}

	for key, value := range mux.Vars(req) {
		req = setValueOnRequestContext(req, key, value)
	}

	var body []byte
	if req.Body != nil {
		bytes, err := ioutil.ReadAll(req.Body)
		if err == nil {
			body = bytes
		}
	}

	// TODO: Keys can potentially be overwritten if the request path has
	// parameters with the same name as query string values. Figure out a
	// better way to handle this.

	return &requestContext{
		req:      req,
		body:     bytes.NewBuffer(body),
		writer:   writer,
		router:   nil,
		messages: []string{},
	}
}

func NewContextWithRouter(req *http.Request, writer http.ResponseWriter, router *mux.Router) RequestContext {
	context := NewContext(req, writer)
	context.(*requestContext).router = router
	return context
}

// WithValue returns a new RequestContext with the provided key-value pair and this context
// as the parent.
func (ctx *requestContext) WithValue(key, value interface{}) RequestContext {
	if r, ok := ctx.Request(); ok {
		req := setValueOnRequestContext(r, key, value)
		return &requestContext{
			req:      req,
			body:     ctx.body,
			writer:   ctx.writer,
			router:   ctx.router,
			messages: ctx.messages,
		}
	}

	// Should not reach this.
	panic("Unable to set value on context: no request")
}

// Value returns this Context's request's value for the given key, or the request if
// passed the request key. It will return nil if no value is associated with the key.
func (ctx *requestContext) Value(key interface{}) interface{} {
	if key == requestKey {
		return ctx.req
	}
	val := ctx.req.Context().Value(key)
	if val != nil {
		return val
	}
	return nil
}

// ValueWithDefault returns the context value for the given key. If there's no
// such value, the provided default is returned.
func (ctx *requestContext) ValueWithDefault(key, defaultVal interface{}) interface{} {
	value := ctx.req.Context().Value(key)
	if value == nil {
		value = defaultVal
	}
	return value
}

// ResponseFormat returns the response format for the request, defaulting to "json"
// if one is not specified using the "format" query parameter.
func (ctx *requestContext) ResponseFormat() string {
	return ctx.ValueWithDefault(formatKey, "json").(string)
}

// ResourceID returns the resource id for the request, defaulting to an empty string
// if there isn't one.
func (ctx *requestContext) ResourceID() string {
	return ctx.ValueWithDefault(resourceIDKey, "").(string)
}

// Version returns the API version for the request, defaulting to an empty string
// if one is not specified in the request path.
func (ctx *requestContext) Version() string {
	return ctx.ValueWithDefault(versionKey, "").(string)
}

// Status returns the current HTTP status code that will be returned for the request,
// defaulting to 200 if one hasn't been set yet.
func (ctx *requestContext) Status() int {
	return ctx.ValueWithDefault(statusKey, http.StatusOK).(int)
}

// setStatus sets the HTTP status code to be returned for the request.
func (ctx *requestContext) setStatus(status int) RequestContext {
	return ctx.WithValue(statusKey, status)
}

// Error returns the current error for the request or nil if no errors have been set.
func (ctx *requestContext) Error() error {
	err := ctx.ValueWithDefault(errorKey, nil)

	if err == nil {
		return nil
	}

	return err.(error)
}

// setError sets the current error for the request.
func (ctx *requestContext) setError(err error) RequestContext {
	return ctx.WithValue(errorKey, err)
}

// Result returns the result resource for the request or nil if no result has been set.
func (ctx *requestContext) Result() interface{} {
	return ctx.ValueWithDefault(resultKey, nil)
}

// setResult sets the result resource for the request.
func (ctx *requestContext) setResult(result interface{}) RequestContext {
	return ctx.WithValue(resultKey, result)
}

// Cursor returns the current result cursor for the request, defaulting to an empty
// string if one hasn't been set.
func (ctx *requestContext) Cursor() string {
	return ctx.ValueWithDefault(cursorKey, "").(string)
}

// setCursor sets the current result cursor for the request.
func (ctx *requestContext) setCursor(cursor string) RequestContext {
	return ctx.WithValue(cursorKey, cursor)
}

// Header returns the header key-value pairs for the request.
func (ctx *requestContext) Header() http.Header {
	req, ok := ctx.Request()
	if !ok {
		return http.Header{}
	}

	return req.Header
}

// Body returns a buffer containing the raw body of the request.
func (ctx *requestContext) Body() *bytes.Buffer {
	return ctx.body
}

// Request returns the *http.Request associated with context using NewContext, if any.
func (ctx *requestContext) Request() (*http.Request, bool) {
	// We cannot use ctx.(*requestContext).req to get the request because ctx may
	// be a Context derived from a *requestContext. Instead, we use Value to
	// access the request if it is anywhere up the Context tree.
	req, ok := ctx.Value(requestKey).(*http.Request)
	return req, ok
}

// Limit returns the maximum number of results that should be fetched.
func (ctx *requestContext) Limit() int {
	limitStr := ctx.ValueWithDefault(limitKey, "100")
	limit, err := strconv.Atoi(limitStr.(string))
	if err != nil {
		limit = 100
	}
	return limit
}

// NextURL returns the URL to use to request the next page of results using the current
// cursor. If there is no cursor for this request or the URL fails to be built, an empty
// string is returned with the error set.
func (ctx *requestContext) NextURL() (string, error) {
	cursor := ctx.Cursor()
	if cursor == "" {
		return "", fmt.Errorf("Unable to build next url: no cursor")
	}

	r, ok := ctx.Request()
	if !ok {
		return "", fmt.Errorf("Unable to build next url: no request")
	}

	var scheme string
	scheme = r.URL.Scheme
	if scheme == "" {
		scheme = "http"
	}

	urlStr := fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)
	u, err := url.Parse(urlStr)
	if err != nil {
		return "", fmt.Errorf("Unable to build next url: %s", urlStr)
	}

	q := u.Query()
	q.Set("next", cursor)
	u.RawQuery = q.Encode()
	return u.String(), nil
}

// RouteVars is a map of URL route variables to values.
//
//     vars = RouteVars{"category": "widgets", "resource_id": "42"}
//
// Variables are defined in CreateURI and the other URI methods.
type RouteVars map[string]string

// BuildURL builds a full URL for a resource name & method.
//
// resourceName should have the same value as the handler's ResourceName method.
//
// method is the HandleMethod constant that corresponds with the resource
// method for which to build the URL. E.g. HandleCreate with build a URL that
// corresponds with the CreateResource method.
//
// All URL variables should be named in the vars map.
func (ctx *requestContext) BuildURL(resourceName string,
	method HandleMethod, vars RouteVars) (*url.URL, error) {
	r, ok := ctx.Request()
	if !ok {
		return nil, fmt.Errorf("unable to build URL for resource name %q: no request available",
			resourceName)
	}

	routeName := resourceName + ":" + string(method)
	route := ctx.router.Get(routeName)

	// Transform RouteVars map to list of key, val pairs for Gorilla's API
	pairs := make([]string, (len(vars)*2)+2)
	for key, val := range vars {
		pairs = append(pairs, key, val)
	}
	pairs = append(pairs, "version", ctx.Version())
	url, err := route.URL(pairs...)
	if err != nil {
		return nil, err
	}
	url.Host = r.Host

	url.Scheme = "http"
	if r.TLS != nil {
		url.Scheme += "s"
	}

	return url, nil
}

// Messages returns all of the messages set by the request handler to be included in
// the response.
func (ctx *requestContext) Messages() []string {
	messages := ctx.messages
	if err := ctx.Error(); err != nil {
		messages = append(messages, err.Error())
	}
	return messages
}

// AddMessage adds a message to the request messages to be included in the response.
func (ctx *requestContext) AddMessage(message string) {
	ctx.messages = append(ctx.messages, message)
}

func (ctx *requestContext) ResponseWriter() http.ResponseWriter {
	return ctx.writer
}


text:
"""
@author: David Albrecht
anaconda 4.2.13
python 3.5.2
pandas 0.19.1

Dataset Name:
    RCFE ALWP PDF - http://www.dhcs.ca.gov/services/ltc/Documents/ListofRCFEfacilities.pdf

Purpose:
    1) Answer the third bullet point within the first question block, "RCFE Capacity":
        - How many of the RCFEs in a given community participate in the Assisted Living Waiver Program (ALWP)?
          Answer: count_ALWP
    2) Compare the unique zipcodes in this data set to those in all of San Diego from "RCFE_Capacity.py"

Notes:
    1) Manually copied and pasted all RCFEs in San Diego County into TextWrangler and created a CSV
    2) Confirmed: All unique zipcodes from this data set are found in the "RCFE_Capacity.py" data set
"""

#import necessary libraries
import pandas as pd
import os

#change working directory
os.chdir('')

#create dataframe
alwp_df = pd.read_csv('ALWP RCFEs.csv')
alwp_df['Zipcode'] = alwp_df['Zipcode'].astype(str)
#optional mask to remove any Facility Name with an asterisk
#alwp_df = alwp_df[alwp_df['Facility Name'].str.contains('[*]') == False]

#create a list of unique zipcodes within San Diego County that participate in ALWP
alwp_unique_zips = list(alwp_df['Zipcode'].unique())

#create an empty dictionary using the list of unique zipcodes
count_ALWP = {}
for unique_zipcode in alwp_unique_zips:
    count_ALWP[unique_zipcode] = 0

#find the number of RCFEs in each zipcode that participate in ALWP: count_ALWP
for unique_zipcode in alwp_unique_zips:
    for all_zipcode in alwp_df['Zipcode']:
        if unique_zipcode == all_zipcode:
            count_ALWP[unique_zipcode] += 1

"""
#check if each alwp zipcode is in the total list of RCFE zipcodes
#requires that you run 'RCFE_Capacity.py' first
for zip in alwp_unique_zips:
    if zip not in unique_zips:
        print(zip)
"""


text:
INTERFACE=${INTERFACE:-ftdi/jtagkey2}
BOARD=${BOARD:-apf27}

openocd -f interface/${INTERFACE}.cfg -f board/${BOARD}.cfg -c init


text:
#pragma once

#include <itkDataImageReaderBase.h>
#include <itkDataImagePluginExport.h>

class ITKDATAIMAGEPLUGIN_EXPORT itkGiplDataImageReader: public itkDataImageReaderBase {
public:
    itkGiplDataImageReader();
    virtual ~itkGiplDataImageReader();

    virtual QString identifier()  const;
    virtual QString description() const;

    QStringList handled() const;

    static QStringList s_handled();

    static bool registered();

private:

    static const char ID[];
};

dtkAbstractDataReader *createItkGiplDataImageReader();


text:
package com.yvertical.yvda.mqtt;

import com.yvertical.yvda.common.Constants;
import com.yvertical.yvda.common.MDMUser;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;

import android.content.Context;
import android.util.Log;

public class YVMqttConnection {
    private MqttAndroidClient client;
    private MqttConnectOptions conOpt;

    private YVMqttCallbackHandler callback;

    private MDMUser mdmUser;
    private Context context;

    private static YVMqttConnection instance;

    public int state;
    public final static int CONNECTION_NULL = 0;
    public final static int CONNECTION_CONNECTING = 1;
    public final static int CONNECTION_CONNECTED = 2;
    public final static int CONNECTION_RECONNECTING = 3;
    public final static int CONNECTION_DISCONNECTING = 4;

    private YVMqttConnection(Context _context, String _host, MDMUser _user) {
    	Log.i("MyPlugin", "----------yvmgttConnection---------------");
        state = CONNECTION_NULL;
        context = _context;
        mdmUser = _user;
        String uri = "tcp://" + _host + ":" + Constants.MQTT_PORT;
        conOpt = new MqttConnectOptions();
        conOpt.setCleanSession(true);
        conOpt.setConnectionTimeout(Constants.MQTT_CONNECTION_TIMEOUT);
        conOpt.setKeepAliveInterval(Constants.MQTT_KEEPALIVE_INTERVAL);
        conOpt.setUserName(_user.user_uuid);
        conOpt.setPassword(_user.session_uuid.toCharArray());

        callback = new YVMqttCallbackHandler(context, _user.device_id);
        client = new MqttAndroidClient(context, uri, _user.device_id);

        client.setCallback(callback);
        client.setTraceEnabled(true);

    }

    public static YVMqttConnection createConnection(Context context,MDMUser _user) {
        String _host =  _user.host;
        if (_user == null || _host == null) {
            return null;
        }
        instance = new YVMqttConnection(context, _host, _user);
        return instance;
    }

    public static YVMqttConnection access(String _uuid) {
        if (instance == null) {
            return null;
        }
        if (_uuid.equals(instance.mdmUser.device_id)) {
            return instance;
        }
        return null;
    }

    public void connect() {
        ActionListener _actionCallback = new ActionListener(context,
                                                            ActionListener.Action.CONNECT,
                                                            mdmUser.device_id);
        try {
            client.connect(conOpt, null, _actionCallback);
        } catch (MqttException e) {
            e.printStackTrace();
            state = CONNECTION_NULL;
        }
    }

    public void subscribe() {
        ActionListener _actionCallback = new ActionListener(context,
                                                            ActionListener.Action.SUBSCRIBE,
                                                            mdmUser.device_id);
        try {
            client.subscribe(mdmUser.subtopic, Constants.MQTT_QOS, null, _actionCallback);
            Log.i("MyPlugin", "====subscribe mqtt");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void disconnect() {
        try {
            Log.i(Constants.DEBUG_TAG, "DISCONNECT YVMQTT");
            client.disconnect(null, new ActionListener(context, ActionListener.Action.DISCONNECT, mdmUser.device_id));
        } catch (MqttException e) {
            e.printStackTrace();
            state = CONNECTION_NULL;
        }
    }

    public void register() {
        client.registerResources(context);
    }

    public void unregister() {
        Log.i(Constants.DEBUG_TAG, "UNREGISTER YVMQTT");
        client.unregisterResources();
    }

}


text:
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.Transports.InMemory.Topology.Topologies
{
    using System;
    using System.Collections.Generic;
    using Builders;
    using Configurators;
    using MassTransit.Topology;
    using MassTransit.Topology.Topologies;

    public class InMemoryMessagePublishTopology<TMessage> :
        MessagePublishTopology<TMessage>,
        IInMemoryMessagePublishTopologyConfigurator<TMessage>
        where TMessage : class
    {
        readonly IList<IInMemoryMessagePublishTopology> _implementedMessageTypes;
        readonly IMessageTopology<TMessage> _messageTopology;

        public InMemoryMessagePublishTopology(IMessageTopology<TMessage> messageTopology)
        {
            _messageTopology = messageTopology;
            _implementedMessageTypes = new List<IInMemoryMessagePublishTopology>();
        }

        public void Apply(IInMemoryPublishTopologyBuilder builder)
        {
            var exchangeHandle = ExchangeDeclare(builder);

            if (builder.ExchangeName != null)
                builder.ExchangeBind(builder.ExchangeName, exchangeHandle);
            else
                builder.ExchangeName = exchangeHandle;

            foreach (IInMemoryMessagePublishTopology configurator in _implementedMessageTypes)
                configurator.Apply(builder);
        }

        public override bool TryGetPublishAddress(Uri baseAddress, out Uri publishAddress)
        {
            var exchangeName = _messageTopology.EntityName;

            publishAddress = new Uri($"{baseAddress}{exchangeName}");
            return true;
        }

        string ExchangeDeclare(IInMemoryTopologyBuilder builder)
        {
            var exchangeName = _messageTopology.EntityName;

            builder.ExchangeDeclare(exchangeName);

            return exchangeName;
        }

        public void AddImplementedMessageConfigurator<T>(IInMemoryMessagePublishTopologyConfigurator<T> configurator, bool direct)
            where T : class
        {
            var adapter = new TypeAdapter<T>(configurator, direct);

            _implementedMessageTypes.Add(adapter);
        }

        class TypeAdapter<T> :
            IInMemoryMessagePublishTopology
            where T : class
        {
            readonly IInMemoryMessagePublishTopologyConfigurator<T> _configurator;
            readonly bool _direct;

            public TypeAdapter(IInMemoryMessagePublishTopologyConfigurator<T> configurator, bool direct)
            {
                _configurator = configurator;
                _direct = direct;
            }

            public void Apply(IInMemoryPublishTopologyBuilder builder)
            {
                if (_direct)
                {
                    var implementedBuilder = builder.CreateImplementedBuilder();

                    _configurator.Apply(implementedBuilder);
                }
            }
        }
    }
}


text:
struct basic_ios{~basic_ios(); };

template<typename _CharT> struct basic_istream : virtual public basic_ios {
  virtual ~basic_istream(){}
};

template<typename _CharT> struct basic_iostream : public basic_istream<_CharT>
{
  virtual ~basic_iostream(){}
};

basic_iostream<char> res;

int main() {
}

// basic_iostream's complete dtor calls its base dtor, then its
// virtual base's dtor.
//  CHECK: define linkonce_odr {{.*}} @_ZN14basic_iostreamIcED1Ev(%struct.basic_iostream* {{.*}}%this) unnamed_addr
//  CHECK: call {{.*}} @_ZN14basic_iostreamIcED2Ev
//  CHECK: call {{.*}} @_ZN9basic_iosD2Ev

// basic_iostream's base dtor calls its non-virtual base dtor.
//  CHECK: define linkonce_odr {{.*}} @_ZN14basic_iostreamIcED2Ev(%struct.basic_iostream* {{.*}}%this, i8** %vtt) unnamed_addr
//  CHECK: call {{.*}} @_ZN13basic_istreamIcED2Ev
//  CHECK: }

// basic_iostream's deleting dtor calls its complete dtor, then
// operator delete().
//  CHECK: define linkonce_odr {{.*}} @_ZN14basic_iostreamIcED0Ev(%struct.basic_iostream* {{.*}}%this) unnamed_addr
//  CHECK: call {{.*}} @_ZN14basic_iostreamIcED1Ev
//  CHECK: call {{.*}} @_ZdlPv

// basic_istream's complete dtor calls the base dtor,
// then its virtual base's base dtor.
//  CHECK: define linkonce_odr {{.*}} @_ZN13basic_istreamIcED1Ev(%struct.basic_istream* {{.*}}%this) unnamed_addr
//  CHECK: call {{.*}} @_ZN13basic_istreamIcED2Ev
//  CHECK: call {{.*}} @_ZN9basic_iosD2Ev

// basic_istream's deleting dtor calls the complete dtor, then
// operator delete().
//  CHECK: define linkonce_odr {{.*}} @_ZN13basic_istreamIcED0Ev(%struct.basic_istream* {{.*}}%this) unnamed_addr
//  CHECK: call {{.*}} @_ZN13basic_istreamIcED1Ev
//  CHECK: call {{.*}} @_ZdlPv

// basic_istream's base dtor is a no-op.
//  CHECK: define linkonce_odr {{.*}} @_ZN13basic_istreamIcED2Ev(%struct.basic_istream* {{.*}}%this, i8** %vtt) unnamed_addr
//  CHECK-NOT: call
//  CHECK: }


text:
/*
 * Copyright (c) 2014, Atmel Corporation All rights reserved.
 *
 * Licensed under Atmel's Limited License Agreement --> EULA.txt
 */
 /**
 * Support and FAQ: visit Atmel Support
 */

#ifndef _SYS_ENCRYPT_H_
#define _SYS_ENCRYPT_H_

/*- Includes ---------------------------------------------------------------*/
#include <stdint.h>
#include <stdbool.h>

/**
 * \ingroup group_lwmesh_sys
 * \defgroup group_lwmesh_sys_timer LWMesh System Services - Security
 * @{
 */

/*- Prototypes -------------------------------------------------------------*/
void SYS_EncryptReq(uint32_t *text, uint32_t *key);
void SYS_EncryptConf(void);

/** @} */
#endif /* _SYS_ENCRYPT_H_ */


text:
title: Perfektionisten und ihre Unantastbarkeit
description: 'Es geht dem Perfektionisten nicht um die Perfektion an sich, sondern um die...'
category: Quotes
createdAt: '2016-07-28T15:44:02+02:00'
position: 11
---

"Es geht dem Perfektionisten nicht um die Perfektion an sich, sondern um die damit verbundene bombensichere Unantastbarkeit."

### *Referenz*:

---

R. M. Bonelli: Perfektionismus: Wenn das Soll zum Muss wird. Pattloch-Verlag, München 2014, S. 332 ff


text:
var chromeHidden = requireNative('chrome_hidden').GetChromeHidden();
var DCHECK = requireNative('logging').DCHECK;
var forEach = require('utils').forEach;
var json = require('json');
var lastError = require('lastError');
var natives = requireNative('sendRequest');
var validate = require('schemaUtils').validate;

// All outstanding requests from sendRequest().
var requests = {};

// Used to prevent double Activity Logging for API calls that use both custom
// bindings and ExtensionFunctions (via sendRequest).
var calledSendRequest = false;

// Callback handling.
chromeHidden.handleResponse = function(requestId, name,
                                       success, responseList, error) {
  // The chrome objects we will set lastError on. Really we should only be
  // setting this on the callback's chrome object, but set on ours too since
  // it's conceivable that something relies on that.
  var chromesForLastError = [chrome];

  try {
    var request = requests[requestId];
    DCHECK(request != null);

    // lastError needs to be set on the caller's chrome object no matter what,
    // though chances are it's the same as ours (it will be different when
    // calling API methods on other contexts).
    if (request.callback) {
      var chromeForCallback = natives.GetGlobal(request.callback).chrome;
      if (chromeForCallback != chrome)
        chromesForLastError.push(chromeForCallback);
    }

    forEach(chromesForLastError, function(i, c) {lastError.clear(c)});
    if (!success) {
      if (!error)
        error = "Unknown error.";
      forEach(chromesForLastError, function(i, c) {
        lastError.set(name, error, request.stack, c)
      });
    }

    if (request.customCallback) {
      var customCallbackArgs = [name, request].concat(responseList);
      request.customCallback.apply(request, customCallbackArgs);
    }

    if (request.callback) {
      // Validate callback in debug only -- and only when the
      // caller has provided a callback. Implementations of api
      // calls may not return data if they observe the caller
      // has not provided a callback.
      if (chromeHidden.validateCallbacks && !error) {
        try {
          if (!request.callbackSchema.parameters) {
            throw new Error("No callback schemas defined");
          }

          validate(responseList, request.callbackSchema.parameters);
        } catch (exception) {
          return "Callback validation error during " + name + " -- " +
                 exception.stack;
        }
      }

      request.callback.apply(request, responseList);
    }
  } finally {
    delete requests[requestId];
    forEach(chromesForLastError, function(i, c) {lastError.clear(c)});
  }
};

function getExtensionStackTrace(call_name) {
  var stack = new Error().stack.split('\n');

  // Remove stack frames before and after that weren't associated with the
  // extension.
  var id = chrome.runtime.id;
  while (stack.length > 0 && stack[0].indexOf(id) == -1)
    stack.shift();
  while (stack.length > 0 && stack[stack.length - 1].indexOf(id) == -1)
    stack.pop();

  return stack.join('\n');
}

function prepareRequest(args, argSchemas) {
  var request = {};
  var argCount = args.length;

  // Look for callback param.
  if (argSchemas.length > 0 &&
      argSchemas[argSchemas.length - 1].type == "function") {
    request.callback = args[args.length - 1];
    request.callbackSchema = argSchemas[argSchemas.length - 1];
    --argCount;
  }

  request.args = [];
  for (var k = 0; k < argCount; k++) {
    request.args[k] = args[k];
  }

  return request;
}

// Send an API request and optionally register a callback.
// |optArgs| is an object with optional parameters as follows:
// - noStringify: true if we should not stringify the request arguments.
// - customCallback: a callback that should be called instead of the standard
//   callback.
// - nativeFunction: the v8 native function to handle the request, or
//   StartRequest if missing.
// - forIOThread: true if this function should be handled on the browser IO
//   thread.
// - preserveNullInObjects: true if it is safe for null to be in objects.
function sendRequest(functionName, args, argSchemas, optArgs) {
  calledSendRequest = true;
  if (!optArgs)
    optArgs = {};
  var request = prepareRequest(args, argSchemas);
  request.stack = getExtensionStackTrace();
  if (optArgs.customCallback) {
    request.customCallback = optArgs.customCallback;
  }
  // json.stringify doesn't support a root object which is undefined.
  if (request.args === undefined)
    request.args = null;

  // TODO(asargent) - convert all optional native functions to accept raw
  // v8 values instead of expecting JSON strings.
  var doStringify = false;
  if (optArgs.nativeFunction && !optArgs.noStringify)
    doStringify = true;
  var requestArgs = doStringify ? json.stringify(request.args) : request.args;
  var nativeFunction = optArgs.nativeFunction || natives.StartRequest;

  var requestId = natives.GetNextRequestId();
  request.id = requestId;
  requests[requestId] = request;

  var hasCallback = request.callback || optArgs.customCallback;
  return nativeFunction(functionName,
                        requestArgs,
                        requestId,
                        hasCallback,
                        optArgs.forIOThread,
                        optArgs.preserveNullInObjects);
}

function getCalledSendRequest() {
  return calledSendRequest;
}

function clearCalledSendRequest() {
  calledSendRequest = false;
}

exports.sendRequest = sendRequest;
exports.getCalledSendRequest = getCalledSendRequest;
exports.clearCalledSendRequest = clearCalledSendRequest;


text:
namespace content {

namespace {

const int kMinimumVibrationDurationMs = 1;  // 1 millisecond
const int kMaximumVibrationDurationMs = 10000;  // 10 seconds

PlatformNotificationData SanitizeNotificationData(
    const PlatformNotificationData& notification_data) {
  PlatformNotificationData sanitized_data = notification_data;

  // Make sure that the vibration values are within reasonable bounds.
  for (int& pattern : sanitized_data.vibration_pattern) {
    pattern = std::min(kMaximumVibrationDurationMs,
        std::max(kMinimumVibrationDurationMs, pattern));
  }

  return sanitized_data;
}

}  // namespace

NotificationMessageFilter::NotificationMessageFilter(
    int process_id,
    PlatformNotificationContextImpl* notification_context,
    ResourceContext* resource_context,
    BrowserContext* browser_context)
    : BrowserMessageFilter(PlatformNotificationMsgStart),
      process_id_(process_id),
      notification_context_(notification_context),
      resource_context_(resource_context),
      browser_context_(browser_context),
      weak_factory_io_(this) {}

NotificationMessageFilter::~NotificationMessageFilter() {}

void NotificationMessageFilter::DidCloseNotification(int notification_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  close_closures_.erase(notification_id);
}

void NotificationMessageFilter::OnDestruct() const {
  BrowserThread::DeleteOnIOThread::Destruct(this);
}

bool NotificationMessageFilter::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(NotificationMessageFilter, message)
    IPC_MESSAGE_HANDLER(PlatformNotificationHostMsg_CheckPermission,
                        OnCheckNotificationPermission)
    IPC_MESSAGE_HANDLER(PlatformNotificationHostMsg_Show,
                        OnShowPlatformNotification)
    IPC_MESSAGE_HANDLER(PlatformNotificationHostMsg_ShowPersistent,
                        OnShowPersistentNotification)
    IPC_MESSAGE_HANDLER(PlatformNotificationHostMsg_GetNotifications,
                        OnGetNotifications)
    IPC_MESSAGE_HANDLER(PlatformNotificationHostMsg_Close,
                        OnClosePlatformNotification)
    IPC_MESSAGE_HANDLER(PlatformNotificationHostMsg_ClosePersistent,
                        OnClosePersistentNotification)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void NotificationMessageFilter::OverrideThreadForMessage(
    const IPC::Message& message, content::BrowserThread::ID* thread) {
  if (message.type() == PlatformNotificationHostMsg_Show::ID ||
      message.type() == PlatformNotificationHostMsg_Close::ID)
    *thread = BrowserThread::UI;
}

void NotificationMessageFilter::OnCheckNotificationPermission(
    const GURL& origin, blink::WebNotificationPermission* permission) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  *permission = GetPermissionForOriginOnIO(origin);
}

void NotificationMessageFilter::OnShowPlatformNotification(
    int notification_id,
    const GURL& origin,
    const SkBitmap& icon,
    const PlatformNotificationData& notification_data) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!RenderProcessHost::FromID(process_id_))
    return;

  scoped_ptr<DesktopNotificationDelegate> delegate(
      new PageNotificationDelegate(process_id_, notification_id));

  PlatformNotificationService* service =
      GetContentClient()->browser()->GetPlatformNotificationService();
  DCHECK(service);

  if (!VerifyNotificationPermissionGranted(service, origin))
    return;

  base::Closure close_closure;
  service->DisplayNotification(browser_context_,
                               origin,
                               icon,
                               SanitizeNotificationData(notification_data),
                               delegate.Pass(),
                               &close_closure);

  if (!close_closure.is_null())
    close_closures_[notification_id] = close_closure;
}

void NotificationMessageFilter::OnShowPersistentNotification(
    int request_id,
    int64 service_worker_registration_id,
    const GURL& origin,
    const SkBitmap& icon,
    const PlatformNotificationData& notification_data) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  if (GetPermissionForOriginOnIO(origin) !=
          blink::WebNotificationPermissionAllowed) {
    bad_message::ReceivedBadMessage(this, bad_message::NMF_NO_PERMISSION_SHOW);
    return;
  }

  NotificationDatabaseData database_data;
  database_data.origin = origin;
  database_data.service_worker_registration_id = service_worker_registration_id;

  PlatformNotificationData sanitized_notification_data =
      SanitizeNotificationData(notification_data);
  database_data.notification_data = sanitized_notification_data;

  // TODO(peter): Significantly reduce the amount of information we need to
  // retain outside of the database for displaying notifications.
  notification_context_->WriteNotificationData(
      origin,
      database_data,
      base::Bind(&NotificationMessageFilter::DidWritePersistentNotificationData,
                 weak_factory_io_.GetWeakPtr(),
                 request_id,
                 origin,
                 icon,
                 sanitized_notification_data));
}

void NotificationMessageFilter::DidWritePersistentNotificationData(
    int request_id,
    const GURL& origin,
    const SkBitmap& icon,
    const PlatformNotificationData& notification_data,
    bool success,
    int64_t persistent_notification_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  if (success) {
    PlatformNotificationService* service =
      GetContentClient()->browser()->GetPlatformNotificationService();
    DCHECK(service);

    BrowserThread::PostTask(
        BrowserThread::UI,
        FROM_HERE,
        base::Bind(&PlatformNotificationService::DisplayPersistentNotification,
                   base::Unretained(service),  // The service is a singleton.
                   browser_context_,
                   persistent_notification_id,
                   origin,
                   icon,
                   notification_data));
  }

  Send(new PlatformNotificationMsg_DidShowPersistent(request_id, success));
}

void NotificationMessageFilter::OnGetNotifications(
    int request_id,
    int64_t service_worker_registration_id,
    const GURL& origin,
    const std::string& filter_tag) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  if (GetPermissionForOriginOnIO(origin) !=
          blink::WebNotificationPermissionAllowed) {
    // No permission has been granted for the given origin. It is harmless to
    // try to get notifications without permission, so return an empty vector
    // indicating that no (accessible) notifications exist at this time.
    Send(new PlatformNotificationMsg_DidGetNotifications(
        request_id, std::vector<PersistentNotificationInfo>()));
    return;
  }

  notification_context_->ReadAllNotificationDataForServiceWorkerRegistration(
      origin,
      service_worker_registration_id,
      base::Bind(&NotificationMessageFilter::DidGetNotifications,
                 weak_factory_io_.GetWeakPtr(),
                 request_id,
                 filter_tag));
}

void NotificationMessageFilter::DidGetNotifications(
    int request_id,
    const std::string& filter_tag,
    bool success,
    const std::vector<NotificationDatabaseData>& notifications) {
  std::vector<PersistentNotificationInfo> persistent_notifications;
  for (const NotificationDatabaseData& database_data : notifications) {
    if (!filter_tag.empty()) {
      const std::string& tag = database_data.notification_data.tag;
      if (tag != filter_tag)
        continue;
    }

    persistent_notifications.push_back(std::make_pair(
        database_data.notification_id, database_data.notification_data));
  }

  Send(new PlatformNotificationMsg_DidGetNotifications(
      request_id, persistent_notifications));
}

void NotificationMessageFilter::OnClosePlatformNotification(
    int notification_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!RenderProcessHost::FromID(process_id_))
    return;

  if (!close_closures_.count(notification_id))
    return;

  close_closures_[notification_id].Run();
  close_closures_.erase(notification_id);
}

void NotificationMessageFilter::OnClosePersistentNotification(
    const GURL& origin,
    int64_t persistent_notification_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  if (GetPermissionForOriginOnIO(origin) !=
          blink::WebNotificationPermissionAllowed) {
    bad_message::ReceivedBadMessage(this, bad_message::NMF_NO_PERMISSION_CLOSE);
    return;
  }

  PlatformNotificationService* service =
      GetContentClient()->browser()->GetPlatformNotificationService();
  DCHECK(service);

  // There's no point in waiting until the database data has been removed before
  // closing the notification presented to the user. Post that task immediately.
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(&PlatformNotificationService::ClosePersistentNotification,
                 base::Unretained(service),  // The service is a singleton.
                 browser_context_,
                 persistent_notification_id));

  notification_context_->DeleteNotificationData(
      persistent_notification_id,
      origin,
      base::Bind(&NotificationMessageFilter::
                     DidDeletePersistentNotificationData,
                 weak_factory_io_.GetWeakPtr()));
}

void NotificationMessageFilter::DidDeletePersistentNotificationData(
    bool success) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // TODO(peter): Consider feeding back to the renderer that the notification
  // has been closed.
}

blink::WebNotificationPermission
NotificationMessageFilter::GetPermissionForOriginOnIO(
    const GURL& origin) const {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  PlatformNotificationService* service =
      GetContentClient()->browser()->GetPlatformNotificationService();
  if (!service)
    return blink::WebNotificationPermissionDenied;

  return service->CheckPermissionOnIOThread(resource_context_,
                                            origin,
                                            process_id_);
}

bool NotificationMessageFilter::VerifyNotificationPermissionGranted(
    PlatformNotificationService* service,
    const GURL& origin) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  blink::WebNotificationPermission permission =
      service->CheckPermissionOnUIThread(browser_context_,
                                         origin,
                                         process_id_);

  if (permission == blink::WebNotificationPermissionAllowed)
    return true;

  bad_message::ReceivedBadMessage(this, bad_message::NMF_NO_PERMISSION_VERIFY);
  return false;
}

}  // namespace content


text:
@extends('layouts.master')

@section('content')

Modify DataType

					<form class="form-horizontal" role="form" method="post" action="/datatypes">
						<input type="hidden" name="_token" value="{{csrf_token()}}" />

						  Name

							<input type="text" name="name" class="form-control" value="{{$datatype_details->name}}">

						  Snap Time Value

							<input type="text" name="snap_time_value" class="form-control" value="{{$datatype_details->snap_time_value}}">

						  Snap Time Frame

							<select name="snap_time_frame">
								<option></option>
								<option @if($datatype_details->snap_time_frame == 'hour') selected="selected" @endif >hour</option>
								<option @if($datatype_details->snap_time_frame == 'day') selected="selected" @endif >day</option>
								<option @if($datatype_details->snap_time_frame == 'week') selected="selected" @endif >week</option>
								<option @if($datatype_details->snap_time_frame == 'month') selected="selected" @endif >month</option>
							</select>

						  Retention Value

							<input type="text" name="retention_time_value" class="form-control" value="{{$datatype_details->retention_time_value}}">

						  Retention Frame

							<select name="retention_time_frame">
								<option></option>
								<option @if($datatype_details->retention_time_frame == 'hour') selected="selected" @endif >hour</option>
								<option @if($datatype_details->retention_time_frame == 'day') selected="selected" @endif >day</option>
								<option @if($datatype_details->retention_time_frame == 'week') selected="selected" @endif >week</option>
								<option @if($datatype_details->retention_time_frame == 'month') selected="selected" @endif >month</option>
							</select>

						<input type="submit" value="Update DataType" class="btn btn-success" />

					</form>

@stop