text:
<?php

namespace Skim\MainBundle\Skim\Library\USEvent\Circuit\Handler;

use Skim\MainBundle\Skim\Library\USEvent\Circuit\Model\CircuitHandler;

class RefineExtended extends CircuitHandler
{

	public $percentage = 0.02;

	public function execute()
	{
		$ue = $this->getService()->getUser();

		$ue -> setLastcat($ue->getLastcat()+1);

		if(!$this
			->getService()
			->getEntityManager()
			->getRepository('SkimMainBundle:Category')
			->exists($ue->getLastcat())
		)
			$ue -> setLastcat(1);

		$category = $this
			->getService()
			->getUser()
			->getLastcat()
		;

		$category = $this
			->getService()
			->getEntityManager()
			->getRepository('SkimMainBundle:Category')
			->find($category)
		;

		$this->setUrl(
			$this
			->getService()
			->getEntityManager()
			->getRepository('SkimMainBundle:Url')
			->getBestUrlofCategory($category)
		);
		return $this;
	}
}


text:
#include "context.h"

using namespace c::context;

// constructors/ destructors
context_ptr new_context()
{
    return new context_t(efac::newEfac());
}

void free_context(context_ptr e)
{
    delete e;
}

int context_size(const context_ptr e)
{
    return e->impl->size();
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.jena.atlas.web.auth;

import java.net.URI;

/**
 *

 * A HTTP Authenticator which provides authentication via user name and password
 * combinations. Works with the basic and digest HTTP authentication schemes.
 *

 *

 * See {@link SimpleNTAuthenticator} for an implementation that works for the
 * NTLM authentication scheme.
 *

 *

 * This authenticator will present the given credentials to any server that
 * request authentication even though the credentials may not be valid there. It
 * is typically more secure to use the {@link ScopedAuthenticator} instead which
 * only presents credentials to specific servers.
 *

 *
 */
public class SimpleAuthenticator extends AbstractCredentialsAuthenticator {

    String username;
    char[] password;

    /**
     * Creates a new authenticator
     *
     * @param username
     *            Username
     * @param password
     *            Password
     */
    public SimpleAuthenticator(String username, char[] password) {
        this.username = username;
        this.password = password;
    }

    @Override
    protected boolean hasUserName(URI target) {
        return this.username != null;
    }

    @Override
    protected String getUserName(URI target) {
        return this.username;
    }

    @Override
    protected boolean hasPassword(URI target) {
        return this.password != null;
    }

    @Override
    protected char[] getPassword(URI target) {
        return this.password;
    }

}


text:
title: Writing Practice

source:
- title: Common Core Basics
  subject: Social Studies
  chapter: 5
  toc_type: Lesson Review
  toc_number: 5.4
  pages: 202 - 207

questions:
  - number: 1
    text: >
      Write an essay comparing the benefits of commercial banks with the benefits of credit unions. ln the first paragraph, compare and contrast the two institutions. In the second paragraph, write your opinion of which type of institution you would prefer to use. Be sure to support your opinion with clear reasons and evidence.
    choice:
      - option: blank
    answer:
      - text: >
          You may want to read the web pages of a commerical bank and a credit union before writing your essay.

          Sample Response

          Banks and credit unions provide similar services to customers. A commercial bank is operated for profit; its goal is to make money for its owners and investors. A credit union is owned by its members; it is not designed to earn profits. Both institutions offer loans to individuals. Banks also offer loans to businesses.

          I would like to do my banking at a credit union. The savings interest may be higher, and the loan interest lower. This is because no bank owner is making a big profit. I might be giving up some convenience because my local credit union does not have branch offices, but I wouldrather stick with an institution that looks out for the people it serves.

layout: cc_review
---


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Include test fixture.
GEN_INCLUDE([
  '../chromevox/testing/chromevox_next_e2e_test_base.js',
]);

/** Test fixture for array_util.js. */
EventGeneratorTest = class extends ChromeVoxNextE2ETest {};

// Fails on ChromeOS - https://crbug.com/1136991
TEST_F(
    'EventGeneratorTest', 'DISABLED_MouseEventsProcessedSequentially',
    function() {
      const mouseEventLog = [];
      chrome.accessibilityPrivate.sendSyntheticMouseEvent = (event) =>
          mouseEventLog.push(event);

      // Set a 1ms delay so that a timeout is set between the press and release.
      EventGenerator.sendMouseClick(100, 100, /*delayMs=*/ 1);
      assertEquals(
          1, mouseEventLog.length, 'First event should be synchronous');

      EventGenerator.sendMouseClick(200, 200, /*delayMs=*/ 1);
      assertEquals(
          1, mouseEventLog.length,
          'Second mouse click shouldn\'t start until first has finished');

      const checkEventLog = () => {
        assertEquals(
            4, mouseEventLog.length,
            'Both click events should have completed.');
        assertEquals('press', mouseEventLog[0].type);
        assertEquals('release', mouseEventLog[1].type);
        assertEquals(mouseEventLog[0].x, mouseEventLog[1].x);
        assertEquals(mouseEventLog[0].y, mouseEventLog[1].y);

        assertEquals('press', mouseEventLog[2].type);
        assertEquals('release', mouseEventLog[3].type);
        assertEquals(mouseEventLog[2].x, mouseEventLog[3].x);
        assertEquals(mouseEventLog[2].y, mouseEventLog[3].y);
      };
      // Experimentally, the code takes 13ms to set all timeouts on a
      // development machine. Wait 150ms to increase stability.
      setTimeout(this.newCallback(checkEventLog), 150);
    });


text:
import json
import os
import shutil
import subprocess
import sys
from datetime import date

from platformio import __core_packages__, exception, fs, util
from platformio.exception import UserSideException
from platformio.package.exception import UnknownPackageError
from platformio.package.manager.tool import ToolPackageManager
from platformio.package.meta import PackageItem, PackageSpec
from platformio.proc import get_pythonexe_path

def get_installed_core_packages():
    result = []
    pm = ToolPackageManager()
    for name, requirements in __core_packages__.items():
        spec = PackageSpec(owner="platformio", name=name, requirements=requirements)
        pkg = pm.get_package(spec)
        if pkg:
            result.append(pkg)
    return result

def get_core_package_dir(name, spec=None, auto_install=True):
    if name not in __core_packages__:
        raise exception.PlatformioException("Please upgrade PlatformIO Core")
    pm = ToolPackageManager()
    spec = spec or PackageSpec(
        owner="platformio", name=name, requirements=__core_packages__[name]
    )
    pkg = pm.get_package(spec)
    if pkg:
        return pkg.path
    if not auto_install:
        return None
    assert pm.install(spec)
    remove_unnecessary_core_packages()
    return pm.get_package(spec).path

def update_core_packages():
    pm = ToolPackageManager()
    for name, requirements in __core_packages__.items():
        spec = PackageSpec(owner="platformio", name=name, requirements=requirements)
        try:
            pm.update(spec, spec)
        except UnknownPackageError:
            pass
    remove_unnecessary_core_packages()
    return True

def remove_unnecessary_core_packages(dry_run=False):
    candidates = []
    pm = ToolPackageManager()
    best_pkg_versions = {}

    for name, requirements in __core_packages__.items():
        spec = PackageSpec(owner="platformio", name=name, requirements=requirements)
        pkg = pm.get_package(spec)
        if not pkg:
            continue
        # pylint: disable=no-member
        best_pkg_versions[pkg.metadata.name] = pkg.metadata.version

    for pkg in pm.get_installed():
        skip_conds = [
            os.path.isfile(os.path.join(pkg.path, ".piokeep")),
            pkg.metadata.spec.owner != "platformio",
            pkg.metadata.name not in best_pkg_versions,
            pkg.metadata.name in best_pkg_versions
            and pkg.metadata.version == best_pkg_versions[pkg.metadata.name],
        ]
        if not any(skip_conds):
            candidates.append(pkg)

    if dry_run:
        return candidates

    for pkg in candidates:
        pm.uninstall(pkg)

    return candidates

def inject_contrib_pysite():
    # pylint: disable=import-outside-toplevel
    from site import addsitedir

    try:
        contrib_pysite_dir = get_core_package_dir("contrib-pysite")
    except UnknownPackageError:
        pm = ToolPackageManager()
        contrib_pysite_dir = build_contrib_pysite_package(
            os.path.join(pm.package_dir, "contrib-pysite")
        )

    if contrib_pysite_dir in sys.path:
        return True

    addsitedir(contrib_pysite_dir)
    sys.path.insert(0, contrib_pysite_dir)

    try:
        # pylint: disable=import-error,unused-import,unused-variable
        from OpenSSL import SSL

    except:  # pylint: disable=bare-except
        build_contrib_pysite_package(contrib_pysite_dir)

    return True

def build_contrib_pysite_package(target_dir, with_metadata=True):
    systype = util.get_systype()
    if os.path.isdir(target_dir):
        fs.rmtree(target_dir)
    os.makedirs(target_dir)

    # issue 3865: There is no "rustup" in "Raspbian GNU/Linux 10 (buster)"
    os.environ["CRYPTOGRAPHY_DONT_BUILD_RUST"] = "1"

    # build dependencies
    args = [
        get_pythonexe_path(),
        "-m",
        "pip",
        "install",
        "--no-compile",
        "-t",
        target_dir,
    ]
    if "linux" in systype:
        args.extend(["--no-binary", ":all:"])
    try:
        subprocess.run(args + get_contrib_pysite_deps(), check=True, env=os.environ)
    except subprocess.CalledProcessError as exc:
        if "linux" in systype:
            raise UserSideException(
                "\n\nPlease ensure that the next packages are installed:\n\n"
                "sudo apt install python3-dev libffi-dev libssl-dev\n"
            )
        raise exc

    # build manifests
    with open(
        os.path.join(target_dir, "package.json"), mode="w", encoding="utf8"
    ) as fp:
        json.dump(
            dict(
                name="contrib-pysite",
                version="2.%d%d.%s"
                % (
                    sys.version_info.major,
                    sys.version_info.minor,
                    date.today().strftime("%y%m%d"),
                ),
                system=list(
                    set([systype, "linux_armv6l", "linux_armv7l", "linux_armv8l"])
                )
                if systype.startswith("linux_arm")
                else systype,
                description="Extra Python package for PlatformIO Core",
                keywords=["platformio", "platformio-core"],
                homepage="https://docs.platformio.org/page/core/index.html",
                repository={
                    "type": "git",
                    "url": "https://github.com/platformio/platformio-core",
                },
            ),
            fp,
        )

    # generate package metadata
    if with_metadata:
        pm = ToolPackageManager()
        pkg = PackageItem(target_dir)
        pkg.metadata = pm.build_metadata(
            target_dir, PackageSpec(owner="platformio", name="contrib-pysite")
        )
        pkg.dump_meta()

    # remove unused files
    for root, dirs, files in os.walk(target_dir):
        for t in ("_test", "test", "tests"):
            if t in dirs:
                shutil.rmtree(os.path.join(root, t))
        for name in files:
            if name.endswith((".chm", ".pyc")):
                os.remove(os.path.join(root, name))

    return target_dir

def get_contrib_pysite_deps():
    systype = util.get_systype()
    twisted_version = "22.1.0"
    if "linux_arm" in systype:
        result = [
            # twisted[tls], see setup.py for %twisted_version%
            "twisted == %s" % twisted_version,
            # pyopenssl depends on it, use RUST-less version
            "cryptography >= 3.3, < 35.0.0",
            "pyopenssl >= 16.0.0, <= 21.0.0",
            "service_identity >= 18.1.0, <= 21.1.0",
        ]
    else:
        result = ["twisted[tls] == %s" % twisted_version]
    if "windows" in systype:
        result.append("pywin32 != 226")
    return result


text:
// Optimize CSS/JavaScript and update HTML
// This module requires "useminPrepare" task,
// and depends on "grunt-contrib-concat", "grunt-contrib-cssmin" and "grunt-contrib-uglify".
// grunt-usemin: <https://github.com/yeoman/grunt-usemin>

'use strict';

module.exports = {

    // Base options
    options: {
        assetsDirs: [
            '<%= path.dist %>'
        ]
    },

    // Update HTML files
    html: {
        files: [{
            src: ['<%= path.dist %>/**/*.html'],
            filter: 'isFile'
        }]
    },

    // Update CSS files
    css: {
        files: [{
            src: ['<%= path.dist %>/**/*.css'],
            filter: 'isFile'
        }]
    }

};


text:
<?php include("top.html"); ?>
  <form action="signup-submit.php" method="post">

    <fieldset>
      <legend>New User Signup:</legend>

          Name:
          <input type="text" name="name" maxlength="16" size="16">

          Gender:
            Male
            <input id="male" type="radio" name="gender" value="M">
            Female
              <input id="female" type="radio" name="gender" value="F">

          Age
          <input id="age" type="text" maxlength="2" size="6" name="age">

          Personality types:
          <input type="text" maxlength="4" size="6" name="personality">

            Don't know your type?

          Favorite OS:
          <select name="fav_os">
            <datalist>
              <option selected="selected">Windows</option>
              <option value="Mac OS X">OS X</option>
              <option>Linux</option>
              <option>Android</option>
              <option>iOS</option>
            </datalist>
          </select>

          Seeking age:
            <input type="text" name="minage" placeholder="min" maxlength="2" size="6">
            to
            <input type="text" name="maxage" placeholder="max" maxlength="2" size="6">

          <input type="submit" name="submit"/>

  </fieldset>
  </form>

<?php include("bottom.html"); ?>


text:
using System;

namespace Microsoft.AspNet.SignalR.Samples
{
    public partial class SignalRMaster : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
package com.amazonaws.services.logs.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeQueriesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The list of queries that match the request.
     *

     */
    private com.amazonaws.internal.SdkInternalList<QueryInfo> queries;

    private String nextToken;

    /**
     *

     * The list of queries that match the request.
     *

     *
     * @return The list of queries that match the request.
     */

    public java.util.List<QueryInfo> getQueries() {
        if (queries == null) {
            queries = new com.amazonaws.internal.SdkInternalList<QueryInfo>();
        }
        return queries;
    }

    /**
     *

     * The list of queries that match the request.
     *

     *
     * @param queries
     *        The list of queries that match the request.
     */

    public void setQueries(java.util.Collection<QueryInfo> queries) {
        if (queries == null) {
            this.queries = null;
            return;
        }

        this.queries = new com.amazonaws.internal.SdkInternalList<QueryInfo>(queries);
    }

    /**
     *

     * The list of queries that match the request.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setQueries(java.util.Collection)} or {@link #withQueries(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param queries
     *        The list of queries that match the request.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeQueriesResult withQueries(QueryInfo... queries) {
        if (this.queries == null) {
            setQueries(new com.amazonaws.internal.SdkInternalList<QueryInfo>(queries.length));
        }
        for (QueryInfo ele : queries) {
            this.queries.add(ele);
        }
        return this;
    }

    /**
     *

     * The list of queries that match the request.
     *

     *
     * @param queries
     *        The list of queries that match the request.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeQueriesResult withQueries(java.util.Collection<QueryInfo> queries) {
        setQueries(queries);
        return this;
    }

    /**
     * @param nextToken
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     * @return
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     * @param nextToken
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeQueriesResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getQueries() != null)
            sb.append("Queries: ").append(getQueries()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeQueriesResult == false)
            return false;
        DescribeQueriesResult other = (DescribeQueriesResult) obj;
        if (other.getQueries() == null ^ this.getQueries() == null)
            return false;
        if (other.getQueries() != null && other.getQueries().equals(this.getQueries()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getQueries() == null) ? 0 : getQueries().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public DescribeQueriesResult clone() {
        try {
            return (DescribeQueriesResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
This code provides the user interface for overviewing one's memory, which is
displayed in a tab of its own. It is a html+javascript app, built with
[React](https://facebook.github.io/react/) and [Redux](http://redux.js.org/),
which create a somewhat complex-looking but nicely organised application
structure.

## Redactux?!

In short, the React components (in `components`) define how the HTML DOM is
calculated as a function of the Redux *state* (which is just a large javascript
object), and which Redux *actions* are triggered upon user input. When changing
application behaviour, we therefore only have to modify in which ways these
actions modify the state (through *reducers*), and do not touch any of the
DOM-related stuff, allowing for more abstract thinking. There are great
explanations of Redux and React on their websites, so we will not go deeper
into this here.

## Application structure

It all starts with [`main.jsx`](main.jsx), which creates the store (using
[`store.js`](store.js)), and renders the main component
([`components/Overview.jsx`](components/Overview.jsx)) to the DOM. Then
components will dispatch actions, which trigger reducers (and more actions),
which update the state, which triggers component updates, and so on. Any change
to the database will also trigger actions to update the output directly.

Keeping the code clean, modular and understandable is an ongoing process. Some
inspiration is drawn from Jack Hsu's nice
[essays](https://jaysoo.ca/2016/02/28/organizing-redux-application/) about
structuring Redux applications.

Some Redux middleware is used to deal with complexity and asynchronicity. In
particular:

- [`redux-act`](https://github.com/pauldijou/redux-act) to lessen boilerplate
  code and simplify actions and reducers.
- [`redux-thunk`](https://github.com/gaearon/redux-thunk) enables actions to
  execute a function that can dispatch other actions, possibly
  asynchronously.
- [`redux-observable`](https://redux-observable.js.org) is used to enable
  actions to listen and react to other actions (see [`epics.js`](epics.js))

## Debugging

To ease debugging, the app includes
[`redux-devtools`](https://github.com/gaearon/redux-devtools) (unless it is
built in production mode). Press `Ctrl+Shift+L` in the overview to open the
devtools sidebar, to see the actions and state transitions as they happen.


text:
//---------------------------------------------------------------------
// <copyright file="MimeTypeAnnotation.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Astoria.Contracts.EntityModel
{
    using Microsoft.Test.Taupo.Contracts.EntityModel;

    /// <summary>
    /// MimeTypeAnnotation holds all the information required to build a mime type attribute
    /// </summary>
    public class MimeTypeAnnotation : CompositeAnnotation
    {
        /// <summary>
        /// Initializes a new instance of the MimeTypeAnnotation class
        /// </summary>
        /// <param name="mimeTypeValue">Mime type value</param>
        public MimeTypeAnnotation(string mimeTypeValue)
        {
            this.MimeTypeValue = mimeTypeValue;
        }

        /// <summary>
        /// Initializes a new instance of the MimeTypeAnnotation class
        /// </summary>
        internal MimeTypeAnnotation()
        {
        }

        /// <summary>
        /// Gets mime type value
        /// </summary>
        public string MimeTypeValue { get; private set; }
    }
}


text:
<!doctype html><title>Punch a Doom Character in Augmented Reality</title>
<script src="vendor/tquery-bundle.js"></script>
<script src="vendor/tquery.norequirejs.js"></script>
<script src="vendor/THREEx.KeyboardState.js"></script>
<script src="vendor/tquery.keyboard.js"></script>
<script src='vendor/tquery.checkerboard.js'></script>
<script src='vendor/tquery.world.createfog.js'></script>

<script src="vendor/tquery.md2character.js"></script>
<script src="vendor/tquery.md2character.cameracontrols.js"></script>
<script src="vendor/tquery.md2character.ratamahatta.js"></script>
<script src="vendor/tquery.md2character.ratamahatta.keyboard.js"></script>

<script src="vendor/augmentedgesture-bundle.js"></script>

<script>
document.addEventListener('keydown', function(event){
    // if it is keydown on a arrow, prevent default
    if( event.keyCode >= 37 && event.keyCode <= 40 ){
        event.preventDefault();
    }
}, true);
</script>
<body><script src="./index.js"></script></body>


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'StyledLinkStyle'
        db.create_table(u'djangocms_styledlink_styledlinkstyle', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('label', self.gf('django.db.models.fields.CharField')(default='', max_length=32)),
            ('link_class', self.gf('django.db.models.fields.CharField')(default='', max_length=32)),
        ))
        db.send_create_signal(u'djangocms_styledlink', ['StyledLinkStyle'])

        # Adding model 'StyledLink'
        db.create_table(u'djangocms_styledlink_styledlink', (
            (u'cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
            ('label', self.gf('django.db.models.fields.CharField')(default='', max_length=255)),
            ('title', self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True)),
            ('int_destination_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True, blank=True)),
            ('int_destination_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
            ('page_destination', self.gf('django.db.models.fields.CharField')(max_length=64, blank=True)),
            ('ext_destination', self.gf('django.db.models.fields.TextField')(default='', blank=True)),
            ('ext_follow', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('mailto', self.gf('django.db.models.fields.EmailField')(max_length=75, null=True, blank=True)),
            ('target', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
        ))
        db.send_create_signal(u'djangocms_styledlink', ['StyledLink'])

        # Adding M2M table for field styles on 'StyledLink'
        db.create_table(u'djangocms_styledlink_styledlink_styles', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('styledlink', models.ForeignKey(orm[u'djangocms_styledlink.styledlink'], null=False)),
            ('styledlinkstyle', models.ForeignKey(orm[u'djangocms_styledlink.styledlinkstyle'], null=False))
        ))
        db.create_unique(u'djangocms_styledlink_styledlink_styles', ['styledlink_id', 'styledlinkstyle_id'])

    def backwards(self, orm):
        # Deleting model 'StyledLinkStyle'
        db.delete_table(u'djangocms_styledlink_styledlinkstyle')

        # Deleting model 'StyledLink'
        db.delete_table(u'djangocms_styledlink_styledlink')

        # Removing M2M table for field styles on 'StyledLink'
        db.delete_table('djangocms_styledlink_styledlink_styles')

    models = {
        'cms.cmsplugin': {
            'Meta': {'object_name': 'CMSPlugin'},
            'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
            'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
            'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
            'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
        },
        'cms.placeholder': {
            'Meta': {'object_name': 'Placeholder'},
            'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'djangocms_styledlink.styledlink': {
            'Meta': {'object_name': 'StyledLink', 'db_table': "u'djangocms_styledlink_styledlink'", '_ormbases': ['cms.CMSPlugin']},
            u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
            'ext_destination': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
            'ext_follow': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'int_destination_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'int_destination_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}),
            'label': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255'}),
            'mailto': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
            'page_destination': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}),
            'styles': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'styled_link_style'", 'default': '1', 'to': u"orm['djangocms_styledlink.StyledLinkStyle']", 'blank': 'True', 'symmetrical': 'False', 'null': 'True'}),
            'target': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'})
        },
        u'djangocms_styledlink.styledlinkstyle': {
            'Meta': {'object_name': 'StyledLinkStyle'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'label': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32'}),
            'link_class': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '32'})
        }
    }

    complete_apps = ['djangocms_styledlink']


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Сръбско_Unleashed
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, Dictionary<string, long>> cityProfit = new Dictionary<string, Dictionary<string, long>>();

            string[] singerInfo = ReadInfo();

            while (!singerInfo[0].Equals("End"))
            {

                if (!singerInfo[0][singerInfo[0].Length - 1].Equals(' '))
                {
                    singerInfo = ReadInfo();
                }
                else
                {
                    string[] leftPart = singerInfo[0].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                    string[] rightPart = singerInfo[1].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
                    string singer = string.Join(" ", leftPart);

                    if (rightPart.Length - 2 > 0)
                    {
                        string[] cityAsString = new string[rightPart.Length - 2];

                        for (int i = 0; i < cityAsString.Length; i++)
                        {
                            cityAsString[i] = rightPart[i];
                        }

                        int ticketPrice, ticketCount;
                        long profit;

                        if (int.TryParse(rightPart[rightPart.Length - 1], out ticketCount) &&
                            int.TryParse(rightPart[rightPart.Length - 2], out ticketPrice))
                        {
                            profit = ticketPrice * ticketCount;
                            string newCity = string.Join(" ", cityAsString);
                            InsertCity(cityProfit, newCity);
                            InsertProfit(cityProfit, newCity, singer, profit);
                            singerInfo = ReadInfo();
                        }
                        else
                        {
                            singerInfo = ReadInfo();
                        }

                    }
                    else
                    {
                        singerInfo = ReadInfo();
                    }
                }
            }

            PrintProfit(cityProfit);
        }

        private static string[] ReadInfo()
        {
            string[] singerInfo = Console.ReadLine().Split('@').ToArray();
            return singerInfo;
        }

        private static void PrintProfit(Dictionary<string, Dictionary<string, long>> cityProfit)
        {
            foreach (KeyValuePair<string, Dictionary<string, long>> cityEntry in cityProfit)
            {
                Console.WriteLine(cityEntry.Key);

                foreach (KeyValuePair<string, long> singerProfit in cityEntry.Value.OrderByDescending(x => x.Value))
                {
                    Console.WriteLine($"#  {singerProfit.Key} -> {singerProfit.Value}");
                }
            }
        }

        private static void InsertProfit(Dictionary<string, Dictionary<string, long>> cityProfit, string newCity, string singer, long profit)
        {
            if (!cityProfit[newCity].ContainsKey(singer))
            {
                cityProfit[newCity].Add(singer, 0);
            }
            cityProfit[newCity][singer] += profit;
        }

        private static void InsertCity(Dictionary<string, Dictionary<string, long>> cityProfit, string newCity)
        {
            if (!cityProfit.ContainsKey(newCity))
            {
                cityProfit.Add(newCity, new Dictionary<string, long>());
            }
        }
    }
}


text:
#import <UIKit/UIKit.h>
#import "CTAssetItemViewController.h"

extern NSString *const CTAssetScrollViewTappedNotification;

@interface CTAssetScrollView : UIScrollView

@property (nonatomic, weak) id<CTAssetItemViewControllerDataSource> dataSource;
@property (nonatomic) NSUInteger index;

@end


text:
                                   Package `expirationd`
-------------------------------------------------------------------------------

For a commercial-grade example of a Lua rock that works with Tarantool, let us
look at expirationd, which Tarantool supplies on GitHub_ with an Artistic license.
The expirationd.lua program is lengthy (about 500 lines), so here we will only
highlight the matters that will be enhanced by studying the full source later.

.. code-block:: lua

    task.worker_fiber = fiber.create(worker_loop, task)
    log.info("expiration: task %q restarted", task.name)
    ...
    fiber.sleep(expirationd.constants.check_interval)
    ...

Whenever one hears "daemon" in Tarantool, one should suspect it's being done
with :doc:`fiber`. The program is making a fiber and turning control over to it so
it runs occasionally, goes to sleep, then comes back for more.

.. code-block:: lua

    for _, tuple in scan_space.index[0]:pairs(nil, {iterator = box.index.ALL}) do
    ...
            if task.is_tuple_expired(task.args, tuple) then
            task.expired_tuples_count = task.expired_tuples_count + 1
            task.process_expired_tuple(task.space_id, task.args, tuple)
    ...

The "for" instruction can be translated as "iterate through the index of the
space that is being scanned", and within it, if the tuple is "expired" (that
is, if the tuple has a timestamp field which is less than the current time),
process the tuple as an expired tuple.

.. code-block:: lua

    -- put expired tuple in archive
    local function put_tuple_to_archive(space_id, args, tuple)
        -- delete expired tuple
        box.space[space_id]:delete{tuple[1]}
        local email = get_field(tuple, 2)
        if args.archive_space_id ~= nil and email ~= nil then
            box.space[args.archive_space_id]:replace{email, os.time()}
        end
    end

Ultimately the tuple-expiry process leads to ``put_tuple_to_archive()``
which does a "delete" of a tuple from its original space, and an "insert"
of the same tuple into another space. Tarantool's "replace" function is
the same as an "insert" function without an error message if a tuple with
the same content already exists in the target space.

.. code-block:: lua

    function expirationd.do_test(space_id, archive_space_id)
    ...

At this point, if the above explanation is worthwhile, it's clear that
``expirationd.lua`` starts a background routine (fiber) which iterates through
all the tuples in a space, sleeps cooperatively so that other fibers can
operate at the same time, and - whenever it finds a tuple that has expired
- deletes it from this space and puts it in another space. Now the
"``do_test()``" function can be used to create some sample spaces, let the
daemon run for a while, and print results.

For those who like to see things run, here are the exact steps to get
expirationd through the test.

1. Get ``expirationd.lua``. There are standard ways - it is after all part
   of a `standard rock <https://luarocks.org/modules/rtsisyk/expirationd>`_  - but for this purpose just copy the contents of
   expirationd.lua_ to a default directory.
2. Start the Tarantool server as described before.
3. Execute these requests:

.. code-block:: lua

     box.cfg{}
     a = box.schema.space.create('origin')
     a:create_index('first', {type = 'tree', parts = {1, 'NUM'}})
     b = box.schema.space.create('archive')
     b:create_index('first', {type = 'tree', parts = {1, 'STR'}})
     expd = require('expirationd')
     expd._debug = true
     expd.do_test('origin', 'archive')
     os.exit()

The database-specific requests (``cfg``, ``space.create``, ``create_index``)
should already be familiar. The key for getting the rock rolling is
``expd = require('expirationd')``. The "``require``" function is what reads in
the program; it will appear in many later examples in this manual, when it's
necessary to get a package that's not part of the Tarantool kernel. After the
Lua variable expd has been assigned the value of the expirationd package, it's
possible to invoke the package's ``do_test()`` function.

After a while, when the task has had time to do its iterations through the spaces,
``do_test()`` will print out a report showing the tuples that were originally in
the original space, the tuples that have now been moved to the archive space, and
some statistics. Of course, expirationd can be customized to do different things
by passing different parameters, which will be evident after looking in more detail
at the source code.

.. _rock: http://rocks.tarantool.org/
.. _expirationd.lua: https://github.com/tarantool/expirationd/blob/master/expirationd.lua
.. _GitHub: https://github.com/tarantool/expirationd/blob/master/expirationd.lua


text:
package com.graphhopper.routing.util;

import com.graphhopper.util.EdgeSkipIterator;

/**
 * @author Peter Karich
 */
public interface AllEdgesSkipIterator extends AllEdgesIterator, EdgeSkipIterator
{
}


text:
<?php

namespace Magento\Store\Test\Constraint;

use Magento\Backend\Test\Page\Adminhtml\StoreIndex;
use Magento\Store\Test\Fixture\StoreGroup;
use Magento\Mtf\Constraint\AbstractConstraint;

/**
 * Class AssertStoreGroupInGrid
 * Assert that created Store Group can be found in Stores grid
 */
class AssertStoreGroupInGrid extends AbstractConstraint
{
    /* tags */
    const SEVERITY = 'low';
    /* end tags */

    /**
     * Assert that created Store Group can be found in Stores grid by name
     *
     * @param StoreIndex $storeIndex
     * @param StoreGroup $storeGroup
     * @return void
     */
    public function processAssert(StoreIndex $storeIndex, StoreGroup $storeGroup)
    {
        $storeGroupName = $storeGroup->getName();
        $storeIndex->open()->getStoreGrid()->search(['group_title' => $storeGroupName]);
        \PHPUnit_Framework_Assert::assertTrue(
            $storeIndex->getStoreGrid()->isStoreExists($storeGroupName),
            'Store group \'' . $storeGroupName . '\' is not present in grid.'
        );
    }

    /**
     * Returns a string representation of the object.
     *
     * @return string
     */
    public function toString()
    {
        return 'Store Group is present in grid.';
    }
}


text:
package org.hisp.dhis.indicator;

import org.hisp.dhis.DhisSpringTest;
import org.hisp.dhis.common.GenericIdentifiableObjectStore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;

import javax.annotation.Resource;

import static org.junit.Assert.*;

/**
 * @author Lars Helge Overland
 * @version $Id: IndicatorStoreTest.java 3286 2007-05-07 18:05:21Z larshelg $
 */
public class IndicatorStoreTest
    extends DhisSpringTest
{
    @Autowired
    private IndicatorStore indicatorStore;

    @Resource(name="org.hisp.dhis.indicator.IndicatorTypeStore")
    private GenericIdentifiableObjectStore<IndicatorType> indicatorTypeStore;

    // -------------------------------------------------------------------------
    // Support methods
    // -------------------------------------------------------------------------

    private void assertEq( char uniqueCharacter, Indicator indicator )
    {
        assertEquals( "Indicator" + uniqueCharacter, indicator.getName() );
        assertEquals( "IndicatorShort" + uniqueCharacter, indicator.getShortName() );
        assertEquals( "IndicatorCode" + uniqueCharacter, indicator.getCode() );
        assertEquals( "IndicatorDescription" + uniqueCharacter, indicator.getDescription() );
    }

    // -------------------------------------------------------------------------
    // IndicatorType
    // -------------------------------------------------------------------------

    @Test
    public void testAddIndicatorType()
        throws Exception
    {
        IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
        IndicatorType typeB = new IndicatorType( "IndicatorTypeB", 1, false );

        int idA = indicatorTypeStore.save( typeA );
        int idB = indicatorTypeStore.save( typeB );

        typeA = indicatorTypeStore.get( idA );
        assertNotNull( typeA );
        assertEquals( idA, typeA.getId() );

        typeB = indicatorTypeStore.get( idB );
        assertNotNull( typeB );
        assertEquals( idB, typeB.getId() );
    }

    @Test
    public void testUpdateIndicatorType()
        throws Exception
    {
        IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
        int idA = indicatorTypeStore.save( typeA );
        typeA = indicatorTypeStore.get( idA );
        assertEquals( typeA.getName(), "IndicatorTypeA" );

        typeA.setName( "IndicatorTypeB" );
        indicatorTypeStore.update( typeA );
        typeA = indicatorTypeStore.get( idA );
        assertNotNull( typeA );
        assertEquals( typeA.getName(), "IndicatorTypeB" );
    }

    @Test
    public void testGetAndDeleteIndicatorType()
        throws Exception
    {
        IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
        IndicatorType typeB = new IndicatorType( "IndicatorTypeB", 1, false );

        int idA = indicatorTypeStore.save( typeA );
        int idB = indicatorTypeStore.save( typeB );

        assertNotNull( indicatorTypeStore.get( idA ) );
        assertNotNull( indicatorTypeStore.get( idB ) );

        indicatorTypeStore.delete( typeA );

        assertNull( indicatorTypeStore.get( idA ) );
        assertNotNull( indicatorTypeStore.get( idB ) );

        indicatorTypeStore.delete( typeB );

        assertNull( indicatorTypeStore.get( idA ) );
        assertNull( indicatorTypeStore.get( idB ) );
    }

    @Test
    public void testGetAllIndicatorTypes()
        throws Exception
    {
        IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
        IndicatorType typeB = new IndicatorType( "IndicatorTypeB", 1, false );

        indicatorTypeStore.save( typeA );
        indicatorTypeStore.save( typeB );

        Collection<IndicatorType> types = indicatorTypeStore.getAll();

        assertEquals( types.size(), 2 );
        assertTrue( types.contains( typeA ) );
        assertTrue( types.contains( typeB ) );
    }

    @Test
    public void testGetIndicatorTypeByName()
        throws Exception
    {
        IndicatorType typeA = new IndicatorType( "IndicatorTypeA", 100, false );
        IndicatorType typeB = new IndicatorType( "IndicatorTypeB", 1, false );

        int idA = indicatorTypeStore.save( typeA );
        int idB = indicatorTypeStore.save( typeB );

        assertNotNull( indicatorTypeStore.get( idA ) );
        assertNotNull( indicatorTypeStore.get( idB ) );

        typeA = indicatorTypeStore.getByName( "IndicatorTypeA" );
        assertNotNull( typeA );
        assertEquals( typeA.getId(), idA );

        IndicatorType typeC = indicatorTypeStore.getByName( "IndicatorTypeC" );
        assertNull( typeC );
    }

    // -------------------------------------------------------------------------
    // Indicator
    // -------------------------------------------------------------------------

    @Test
    public void testAddIndicator()
        throws Exception
    {
        IndicatorType type = new IndicatorType( "IndicatorType", 100, false );

        indicatorTypeStore.save( type );

        Indicator indicatorA = createIndicator( 'A', type );
        Indicator indicatorB = createIndicator( 'B', type );

        int idA = indicatorStore.save( indicatorA );
        int idB = indicatorStore.save( indicatorB );

        indicatorA = indicatorStore.get( idA );
        assertNotNull( indicatorA );
        assertEq( 'A', indicatorA );

        indicatorB = indicatorStore.get( idB );
        assertNotNull( indicatorB );
        assertEq( 'B', indicatorB );
    }

    @Test
    public void testUpdateIndicator()
        throws Exception
    {
        IndicatorType type = new IndicatorType( "IndicatorType", 100, false );

        indicatorTypeStore.save( type );

        Indicator indicatorA = createIndicator( 'A', type );
        int idA = indicatorStore.save( indicatorA );
        indicatorA = indicatorStore.get( idA );
        assertEq( 'A', indicatorA );

        indicatorA.setName( "IndicatorB" );
        indicatorStore.update( indicatorA );
        indicatorA = indicatorStore.get( idA );
        assertNotNull( indicatorA );
        assertEquals( indicatorA.getName(), "IndicatorB" );
    }

    @Test
    public void testGetAndDeleteIndicator()
        throws Exception
    {
        IndicatorType type = new IndicatorType( "IndicatorType", 100, false );

        indicatorTypeStore.save( type );

        Indicator indicatorA = createIndicator( 'A', type );
        Indicator indicatorB = createIndicator( 'B', type );
        Indicator indicatorC = createIndicator( 'C', type );

        int idA = indicatorStore.save( indicatorA );
        int idB = indicatorStore.save( indicatorB );
        int idC = indicatorStore.save( indicatorC );

        assertNotNull( indicatorStore.get( idA ) );
        assertNotNull( indicatorStore.get( idB ) );
        assertNotNull( indicatorStore.get( idC ) );

        indicatorStore.delete( indicatorA );
        indicatorStore.delete( indicatorC );

        assertNull( indicatorStore.get( idA ) );
        assertNotNull( indicatorStore.get( idB ) );
        assertNull( indicatorStore.get( idC ) );
    }

    @Test
    public void testGetAllIndicators()
        throws Exception
    {
        IndicatorType type = new IndicatorType( "IndicatorType", 100, false );

        indicatorTypeStore.save( type );

        Indicator indicatorA = createIndicator( 'A', type );
        Indicator indicatorB = createIndicator( 'B', type );

        indicatorStore.save( indicatorA );
        indicatorStore.save( indicatorB );

        Collection<Indicator> indicators = indicatorStore.getAll();

        assertEquals( indicators.size(), 2 );
        assertTrue( indicators.contains( indicatorA ) );
        assertTrue( indicators.contains( indicatorB ) );
    }

    @Test
    public void testGetIndicatorByName()
        throws Exception
    {
        IndicatorType type = new IndicatorType( "IndicatorType", 100, false );

        indicatorTypeStore.save( type );

        Indicator indicatorA = createIndicator( 'A', type );
        Indicator indicatorB = createIndicator( 'B', type );

        int idA = indicatorStore.save( indicatorA );
        int idB = indicatorStore.save( indicatorB );

        assertNotNull( indicatorStore.get( idA ) );
        assertNotNull( indicatorStore.get( idB ) );

        indicatorA = indicatorStore.getByName( "IndicatorA" );
        assertNotNull( indicatorA );
        assertEq( 'A', indicatorA );

        Indicator indicatorC = indicatorStore.getByName( "IndicatorC" );
        assertNull( indicatorC );
    }

    @Test
    public void testGetIndicatorByShortName()
        throws Exception
    {
        IndicatorType type = new IndicatorType( "IndicatorType", 100, false );

        indicatorTypeStore.save( type );

        Indicator indicatorA = createIndicator( 'A', type );
        Indicator indicatorB = createIndicator( 'B', type );

        int idA = indicatorStore.save( indicatorA );
        int idB = indicatorStore.save( indicatorB );

        assertNotNull( indicatorStore.get( idA ) );
        assertNotNull( indicatorStore.get( idB ) );

        indicatorA = indicatorStore.getByShortName( "IndicatorShortA" );
        assertNotNull( indicatorA );
        assertEq( 'A', indicatorA );

        Indicator indicatorC = indicatorStore.getByShortName( "IndicatorShortC" );
        assertNull( indicatorC );
    }
}


text:
/*! \file
    \brief Defines iterators for efficiently loading and storing tiles to and from shared memory.
*/
#pragma once

#include "cutlass/gemm/gemm_operand.h"

namespace cutlass {
namespace gemm {

////////////////////////////////////////////////////////////////////////////////////////////////////

template <typename Scalar_, typename Tile_, typename Threads_, int kScalarsPerSts_>
struct GemmSharedStoreTileAbTraits {
  /// The scalar.
  typedef typename platform::remove_const<Scalar_>::type Scalar;
  /// The pointer.
  typedef Scalar_* Pointer;
  /// The tile.
  typedef typename ReshapeTile<Tile_, kScalarsPerSts_>::Tile Tile;
  /// The threads.
  typedef Threads_ Threads;
  /// The strides to compute the base position of the thread.
  typedef Shape<0, ShapeCount<Tile>::kWc, Tile::kC, kScalarsPerSts_> ThreadsStrides;
  /// The skew.
  static int const kSkew = 0;
  /// The number of scalars per LDG/STG.
  static int const kAccessSize = kScalarsPerSts_;
  /// The memory space.
  static MemorySpace::Kind const kMemorySpace = MemorySpace::kShared;

  /// The number of iterations needed to load/store the tile.
  typedef Shape<1,
                Tile::kH / Threads::kH,
                Tile::kW / Threads::kW,
                Tile::kC / Threads::kC / kAccessSize>
      Iterations;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<0, Threads::kH * ShapeCount<Tile>::kWc, Threads::kW * kAccessSize> Delta;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<0, Threads::kH * ShapeCount<Tile>::kWc, Threads::kW * kAccessSize>
      ImmediateOffsetStrides;

  struct ThreadOffset {
    CUTLASS_HOST_DEVICE
    Coord<4> operator()() const {
      int offset = ComputeThreadOffsetFromStrides<Threads, ThreadsStrides>::get();
      return make_Coord(0, 0, offset, 0);
    }
  };
};

////////////////////////////////////////////////////////////////////////////////////////////////////

template <typename Scalar_, typename Tile_, typename Threads_, int kScalarsPerSts_, int kSkew_>
struct GemmSharedStoreWithSkewTileAbTraits {
  /// The scalar.
  typedef typename platform::remove_const<Scalar_>::type Scalar;
  /// The pointer.
  typedef Scalar_* Pointer;
  /// The tile without skews.
  typedef typename ReshapeTile<Tile_, kScalarsPerSts_>::Tile TileWithoutSkew;
  /// The tile.
  typedef typename ReshapeTile<Shape<Tile_::kD, Tile_::kH, Tile_::kW + kSkew_>,
                               kScalarsPerSts_>::Tile Tile;
  /// The threads.
  typedef Threads_ Threads;
  /// The skew.
  static int const kSkew = kSkew_;
  /// The number of scalars per STS.
  static int const kAccessSize = kScalarsPerSts_;
  /// The memory space.
  static MemorySpace::Kind const kMemorySpace = MemorySpace::kShared;

  /// The number of iterations needed to load/store the tile.
  typedef Shape<1, TileWithoutSkew::kH / Threads::kW, TileWithoutSkew::kW / Threads::kH> Iterations;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<0, ShapeCount<Tile>::kWc, Threads::kH * kAccessSize> Delta;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<0, ShapeCount<Tile>::kWc, Threads::kH * kAccessSize> ImmediateOffsetStrides;

  struct ThreadOffset {
    CUTLASS_HOST_DEVICE Coord<4> operator()() const {
      int offset = ComputeThreadOffsetFromStrides<Threads, ThreadsStrides>::get();
      return make_Coord(0, 0, offset, 0);
    }
  };

 protected:
  /// The strides to compute the base position of the thread.
  typedef Shape<0, kScalarsPerSts_, ShapeCount<Tile>::kHwc / Threads::kW> ThreadsStrides;
};

////////////////////////////////////////////////////////////////////////////////////////////////////

template <typename Scalar_,
          typename OutputTile_,
          typename Warps_,
          typename ThreadsPerWarp_,
          typename InstructionShape_,
          int kStages_,
          int kScalarsPerLds_,
          int kSkew_ = 0>
struct GemmSharedLoadTileATraits {
  static GemmOperand::Kind const kOperand = GemmOperand::kA;
  /// The scalar.
  typedef typename platform::remove_const<Scalar_>::type Scalar;
  /// The pointer.
  typedef Scalar_* Pointer;
  /// The tile without skew.
  typedef Shape<kStages_,
                OutputTile_::kD / InstructionShape_::kD,
                GetExtent<kOperand, OutputTile_>::kExtent * InstructionShape_::kD>
      TileWithoutSkew_;
  /// The tile with skew.
  typedef Shape<kStages_, TileWithoutSkew_::kH, TileWithoutSkew_::kW + kSkew_> TileWithSkew;
  /// The tile without skew after reshaping.
  typedef typename ReshapeTile<TileWithoutSkew_, kScalarsPerLds_>::Tile TileWithoutSkew;
  /// The tile.
  typedef typename ReshapeTile<TileWithSkew, kScalarsPerLds_>::Tile Tile;
  /// The number of warps.
  typedef Warps_ Warps;
  /// The threads in a warp.
  typedef ThreadsPerWarp_ ThreadsPerWarp;
  /// The number of scalars per LDG/STG.
  // static int const kScalarsPerLds = kScalarsPerLds_;
  static int const kAccessSize = kScalarsPerLds_;
  /// The skew.
  static int const kSkew = kSkew_;
  /// The memory space.
  static MemorySpace::Kind const kMemorySpace = MemorySpace::kShared;

  /// The number of warps.
  static int const kWarps = GetExtent<kOperand, Warps>::kExtent;
  /// The number of threads in one dimension of the warp.
  static int const kThreadsPerWarp = GetExtent<kOperand, ThreadsPerWarp>::kExtent;

  /// The number of iterations needed to load/store the tile.
  typedef Shape<1, 1, TileWithoutSkew::kW / kWarps / kThreadsPerWarp /* / kScalarsPerLds*/>
      Iterations;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<TileWithSkew::kW * Warps::kD, 0, kWarps * kThreadsPerWarp * kAccessSize, 0>
      ImmediateOffsetStrides;
  typedef Shape<TileWithSkew::kW * Warps::kD, 0, kWarps * kThreadsPerWarp * kAccessSize, 0> Delta;

  /// Computes the thread offset in (H, W) based on thread ID
  struct ThreadOffset {
    CUTLASS_HOST_DEVICE Coord<4> operator()() const {
      // Extract the warp.
      int const warp = threadIdx.x / kWarpSize;
      // Extract the slice.
      int const slice = warp / (Warps::kH * Warps::kW);
      // Compute the row offset for each warp.
      int const warp_row = warp % Warps::kW;
      // Compute the row offset for each thread.
      int const lane_row = (threadIdx.x & 0x0e) / 2;
      // The offset.
      int const offset =
          slice * Tile::kW * Tile::kC + (warp_row * ThreadsPerWarp::kW + lane_row) * kAccessSize;
      // Embed the offset in a 4D coordinate vector.
      return make_Coord(0, 0, offset, 0);
    }
  };
};

////////////////////////////////////////////////////////////////////////////////////////////////////

template <typename Scalar_,
          typename OutputTile_,
          typename Warps_,
          typename ThreadsPerWarp_,
          typename InstructionShape_,
          int kStages_,
          int kScalarsPerLds_,
          int kSkew_ = 0>
struct GemmSharedLoadTileBTraits {
  static GemmOperand::Kind const kOperand = GemmOperand::kB;
  /// The scalar.
  typedef typename platform::remove_const<Scalar_>::type Scalar;
  /// The pointer.
  typedef Scalar_* Pointer;
  /// The tile without skew.
  typedef Shape<kStages_,
                OutputTile_::kD / InstructionShape_::kD,
                GetExtent<kOperand, OutputTile_>::kExtent * InstructionShape_::kD>
      TileWithoutSkew_;
  /// The tile with skew.
  typedef Shape<kStages_, TileWithoutSkew_::kH, TileWithoutSkew_::kW + kSkew_> TileWithSkew;
  /// The tile without skew after reshaping.
  typedef typename ReshapeTile<TileWithoutSkew_, kScalarsPerLds_>::Tile TileWithoutSkew;
  /// The tile.
  typedef typename ReshapeTile<TileWithSkew, kScalarsPerLds_>::Tile Tile;
  /// The number of warps.
  typedef Warps_ Warps;
  /// The threads in a warp.
  typedef ThreadsPerWarp_ ThreadsPerWarp;
  /// The number of scalars per LDG/STG.
  static int const kAccessSize = kScalarsPerLds_;
  /// The skew.
  static int const kSkew = kSkew_;
  /// The memory space.
  static MemorySpace::Kind const kMemorySpace = MemorySpace::kShared;

  /// The number of warps.
  static int const kWarps = GetExtent<kOperand, Warps>::kExtent;
  /// The number of threads in one dimension of the warp.
  static int const kThreadsPerWarp = GetExtent<kOperand, ThreadsPerWarp>::kExtent;

  /// The number of iterations needed to load/store the tile.
  typedef Shape<1, 1, TileWithoutSkew::kW / kWarps / kThreadsPerWarp /* / kAccessSize*/> Iterations;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<TileWithSkew::kW * Warps::kD, 0, kWarps * kThreadsPerWarp * kAccessSize, 0>
      ImmediateOffsetStrides;
  typedef Shape<TileWithSkew::kW * Warps::kD, 0, kWarps * kThreadsPerWarp * kAccessSize, 0> Delta;

  /// Computes the thread offset in (H, W) based on thread ID
  struct ThreadOffset {
    CUTLASS_HOST_DEVICE Coord<4> operator()() const {
      // Extract the warp.
      int const warp = threadIdx.x / kWarpSize;
      // Extract the slice.
      int const slice = warp / (Warps::kH * Warps::kW);
      // The warp in the slice.
      int const warp_in_slice = warp % (Warps::kH * Warps::kW);
      // Compute the row offset for each warp.
      int const warp_col = warp_in_slice / Warps::kW;
      // Compute the row offset for each thread.
      int const lane_col = (threadIdx.x & 0x10) / 8 + (threadIdx.x & 0x01);
      // The offset.
      int const offset =
          slice * Tile::kW * Tile::kC + (warp_col * ThreadsPerWarp::kH + lane_col) * kAccessSize;
      // Embed the offset in a 4D coordinate.
      return make_Coord(0, 0, offset, 0);
    }
  };
};

////////////////////////////////////////////////////////////////////////////////////////////////////

template <typename Scalar_,
          typename OutputTile_,
          typename Warps_,
          typename ThreadsPerWarp_,
          int kScalarsPerSts_,
          int kSkew_ = 0>
struct GemmSharedStoreTileDTraits {
  /// The scalar.
  typedef typename platform::remove_const<Scalar_>::type Scalar;
  /// The pointer.
  typedef Scalar_* Pointer;
  /// The dimension of the output tile.
  typedef OutputTile_ OutputTile;
  /// The warps in the tile.
  typedef Warps_ Warps;
  /// The threads in the warps.
  typedef ThreadsPerWarp_ ThreadsPerWarp;
  /// The number of scalars per LDG/STG.
  static int const kAccessSize = kScalarsPerSts_;
  /// The skew.
  static int const kSkew = kSkew_;
  /// The memory space.
  static MemorySpace::Kind const kMemorySpace = MemorySpace::kShared;

  /// The number of scalars per thread.
  static int const kScalarsPerThread = OutputTile_::kW / Warps::kW / ThreadsPerWarp::kW;
  /// The number of threads.
  static int const kThreads = ShapeCount<Warps>::kCount * kWarpSize;
  /// The number of scalars per row. We build a tile with 2 rows (to avoid bank conflicts).
  static int const kScalarsPerRow = kThreads / 2 * kScalarsPerThread + kSkew;

  /// The tile.
  typedef Shape<1, 2, kScalarsPerRow / kAccessSize, kAccessSize> Tile;
  /// The number of iterations needed to store the tile.
  typedef Shape<1, 1, kScalarsPerThread / kAccessSize> Iterations;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<0, 0, Warps::kW * ThreadsPerWarp::kW * kAccessSize> Delta;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<0, 0, Warps::kW * ThreadsPerWarp::kW * kAccessSize> ImmediateOffsetStrides;

  /// Computes the thread offset in (H, W) based on thread ID
  struct ThreadOffset {
    CUTLASS_HOST_DEVICE Coord<4> operator()() const {
      // The warp.
      int const warp = threadIdx.x / kWarpSize;

      // The position of the warp in the 2D tile.
      int const warp_row = warp % Warps::kW;
      int const warp_col = warp / Warps::kW;

      // We assume that the elements are distributed in a warps as 4 columns of 8 elements. The
      // columns are stored in threads col0=[0, 2, 4, 6, 8, 10, 12, 14], col1=[1, 3, 5, 7, .., 15],
      // col2=[16, 18, 20, ..., 30] and col3=[17, 19, ..., 31].
      int hi_halfwarp_offset = ((threadIdx.x >> 4) & 0x1) * OutputTile::kW;
      int lo_halfwarp_offset = ((threadIdx.x >> 1) & 0x7) + ThreadsPerWarp::kW * warp_row;

      // Odd threads go to the second half of shared memory.
      int const row = threadIdx.x & 0x01;
      int col = warp_col * (ThreadsPerWarp::kH / 2) * OutputTile::kW +
                lo_halfwarp_offset * kAccessSize + hi_halfwarp_offset;
      // Embed the offset in a 4D coords.
      return make_Coord(0, 0, row * kScalarsPerRow + col, 0);
    }
  };
};

////////////////////////////////////////////////////////////////////////////////////////////////////

template <typename Scalar_,
          typename OutputTile_,
          typename Warps_,
          typename ThreadsPerWarp_,
          int kTileH_,
          int kScalarsPerLds_,
          int kSkew_ = 0>
struct GemmSharedLoadTileDTraits {
  /// The scalar.
  typedef typename platform::remove_const<Scalar_>::type Scalar;
  /// The pointer.
  typedef Scalar_* Pointer;
  /// The dimension of the output tile.
  typedef OutputTile_ OutputTile;
  /// The warps in the tile.
  typedef Warps_ Warps;
  /// The threads in the warps.
  typedef ThreadsPerWarp_ ThreadsPerWarp;
  /// The number of scalars per LDG/STG.
  static int const kAccessSize = kScalarsPerLds_;
  /// The skew.
  static int const kSkew = kSkew_;
  /// The memory space.
  static MemorySpace::Kind const kMemorySpace = MemorySpace::kShared;

  /// The number of scalars per thread.
  static int const kScalarsPerThread = OutputTile_::kW / Warps::kW / ThreadsPerWarp::kW;
  /// The number of threads.
  static int const kThreads = ShapeCount<Warps>::kCount * kWarpSize;
  /// The number of scalars per row. We build a tile with 2 rows (to avoid bank conflicts).
  static int const kScalarsPerRow = kThreads / 2 * kScalarsPerThread + kSkew;

  /// The tile. We have 2 rows of scalars. We use those two rows to make sure we do not have bank
  /// conflicts in the epilogue.
  typedef Shape<1, 2, kScalarsPerRow / kAccessSize, kAccessSize> Tile;

  // Compute the number of iterations per warp in the Tile::kH dimension.
  static int const kIterationsInHPerWarp = kTileH_ / ShapeCount<Warps>::kCount;

  // As explained above, the shared memory tile is composed of 2 rows and each rows is made of
  // kScalarsPerRow. A warp is expected to read from the 1st row, then move to the 2nd row and go
  // back to the 1st row. To model that scheme we define the Iterations shape as Shape<X, 2, ...>.
  // However, in some cases, we have only 1 iteration per warp. In that case, we must define the
  // shape as Shape<1, 1, ...>. The following code does that except that we hijack the kH dimension
  // to keep the number of elements to reduce for split-K.
  static int const kIterationsH = kIterationsInHPerWarp == 1 ? 1 : 2;
  // As soon as we know kIterationsH, it is trivial to compute kIterationsD:
  static int const kIterationsD = kIterationsInHPerWarp / kIterationsH;

  // If we have split-K enabled, we have to jump over the elements from the "odd/even" column of
  // threads to grab the other elements.
  static int const kSplitK = OutputTile::kW * ThreadsPerWarp::kH / 2 * Warps::kH;

  /// The number of iterations needed to store the tile.
  typedef Shape<kIterationsD, kIterationsH, OutputTile::kW / kWarpSize / kAccessSize, Warps::kD>
      Iterations;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<OutputTile::kW, kScalarsPerRow, kWarpSize * kAccessSize, kSplitK>
      ImmediateOffsetStrides;
  /// The strides in each dimension between different loads/stores.
  typedef Shape<OutputTile::kW, kScalarsPerRow, kWarpSize * kAccessSize, kSplitK> Delta;

  /// Computes the thread offset in (H, W) based on thread ID
  struct ThreadOffset {
    CUTLASS_HOST_DEVICE Coord<4> operator()() const {
      // Each warp works on a different column.
      int const h = threadIdx.x / kWarpSize;
      // Compute the row.
      int const w = (threadIdx.x & (kWarpSize - 1)) * kAccessSize;
      int offset = 0;
      if (Iterations::kH == 1) {
        int const row = h & 0x1;
        int const col = h / 2;
        offset = row * ShapeCount<Tile>::kWc + col * OutputTile::kW * Iterations::kD + w;
      } else {
        offset = h * OutputTile::kW * Iterations::kD + w;
      }
      return make_Coord(0, 0, offset, 0);
    }
  };
};

////////////////////////////////////////////////////////////////////////////////////////////////////

}  // namespace gemm
}  // namespace cutlass


text:
package br.com.cronapi;

import cronapi.Var;
import cronapi.database.Operations;
import org.junit.Assert;
import org.junit.Test;

public class DatabaseTest {
  @Test
  public void QAIBT_1436() {
    try {
      Operations.executeQuery(
          Var.valueOf("app.entity.User"),
          Var.valueOf("select u from User u"),
          Var.VAR_NULL
      );
      Assert.fail();
    } catch (Exception e) {
      Assert.assertFalse(e instanceof NullPointerException);
    }
  }
}


text:
DUPSUG 26/05/2015 Lessons Learned: DSC Pull Security and Integration
====================================================================
Subfolder Secure-End-2-End contains the scripts I used during the first Demo.
Subfolder WAPack-Integration contains the SMA runbooks I used during the second Demo.

Hyper-v.nu
==========
I've posted a blogpost describing the integration demo here: http://www.hyper-v.nu/archives/bgelens/2015/06/lessons-learned-dsc-pull-security-and-integration-with-wapack-dupsug/

Presentation
------------
The PowerPoint can be found here: https://github.com/bgelens/Presentations/blob/master/052015_DUPSUG/052015_Lessons_learned_DSC_Pull_Security_and_Integration.pptx

Youtube
-------
The demo for the Secure End-2-End DSC Web Pull Services is recorded and posted on youtube here: https://youtu.be/wznZcvpEvhw


text:
import * as actions from '../app/types'

const initialCommentsState = []

export function comments ( state = initialCommentsState, action) {
  switch (action.type) {
    case actions.GET_POST_COMMENTS:
      return [...state, ...action.comments]
    case actions.UPDATE_COMMENT:
    case actions.UPDATE_COMMENT_VOTESCORE:
    case actions.REMOVE_COMMENT:
      return state.map(comment => {
        if(comment.id === action.comment.id) {
          return action.comment
        }
        return comment
      })
    case actions.GOT_NEW_COMMENT:
      return [...state, action.comment]
    default:
      return state
  }
}


text:
//
//  UISwitch+FCKeyValueBinding.h
//  FCKeyValueBinding
//
//  Created by Almer Lucke on 08/01/14.
//  Copyright (c) 2014 Farcoding. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "FCKeyValueBinding.h"

/**
 *  Make UISwitch FCKeyValueBinding compliant.
 *  Observable property is on
 */
@interface UISwitch (FCKeyValueBinding) <FCKeyValueBindingObserveProtocol>

@end


text:
export interface WebsiteId {
  Name: string;
  ResourceGroup: string;
  SubscriptionId: string;
}
export enum ResourceType {
  none,
  site,
  serverFarm,
  hostingEnvironment,
  slot,
  function,
  proxy,
}

export abstract class Descriptor {
  public parts: string[];

  constructor(public resourceId: string) {
    this.parts = resourceId.split('/').filter(part => !!part);
  }

  public abstract getTrimmedResourceId(): string;
}

// tslint:disable-next-line:max-classes-per-file
export class ArmSubcriptionDescriptor extends Descriptor {
  public subscriptionId: string;

  constructor(resourceId: string) {
    super(resourceId);

    if (this.parts[0].toLowerCase() !== 'subscriptions') {
      throw Error(`Expected subscriptions segment in resourceId: ${resourceId}`);
    }

    this.subscriptionId = this.parts[1];
  }

  public getTrimmedResourceId() {
    return `/subscriptions/${this.subscriptionId}`;
  }
}

// tslint:disable-next-line:max-classes-per-file
export class ArmResourceDescriptor extends Descriptor {
  public subscription: string;
  public resourceGroup: string;
  public resourceName: string;

  constructor(resourceId: string) {
    super(resourceId);

    if (this.parts.length < 4) {
      throw Error(`resourceId length is too short: ${resourceId}`);
    }

    if (this.parts[0].toLowerCase() !== 'subscriptions') {
      throw Error(`Expected subscriptions segment in resourceId: ${resourceId}`);
    }

    if (this.parts[2].toLowerCase() !== 'resourcegroups') {
      throw Error(`Expected resourceGroups segment in resourceId: ${resourceId}`);
    }

    this.subscription = this.parts[1];
    this.resourceGroup = this.parts[3];
    this.resourceName = this.parts[this.parts.length - 1];
  }

  public getTrimmedResourceId() {
    return this.resourceId;
  }
}

// tslint:disable-next-line:max-classes-per-file
export class CdsEntityDescriptor extends Descriptor {
  public environment: string;
  public scope: string;

  constructor(resourceId: string) {
    super(resourceId);

    if (this.parts.length < 6) {
      throw Error(`resourceId length is too short for CDS: ${resourceId}`);
    }

    this.environment = this.parts[3];
    this.scope = this.parts[5];
  }

  public getTrimmedResourceId() {
    return `/providers/Microsoft.Blueridge/environments/${this.environment}/scopes/${this.scope}`;
  }
}

// tslint:disable-next-line:max-classes-per-file
export class CdsFunctionDescriptor extends CdsEntityDescriptor implements FunctionDescriptor {
  public name: string;

  constructor(resourceId) {
    super(resourceId);

    if (this.parts.length < 10) {
      throw Error(`resourceId length is too short for function descriptor: ${resourceId}`);
    }

    this.name = this.parts[9];
  }

  public getTrimmedResourceId() {
    return `${super.getTrimmedResourceId()}/functions/${this.name}`;
  }
}

// tslint:disable-next-line:max-classes-per-file
export class ArmSiteDescriptor extends ArmResourceDescriptor {
  public static getSiteDescriptor(resourceId: string): ArmSiteDescriptor | CdsEntityDescriptor {
    const parts = resourceId.split('/').filter(part => !!part);
    let siteId = '';
    let maxIndex: number;

    if (parts.length >= 10 && parts[8].toLowerCase() === 'slots') {
      maxIndex = 9;
    } else if (parts.length >= 8 && parts[6].toLowerCase() === 'sites') {
      maxIndex = 7;
    } else if (parts.length >= 6 && parts[4].toLowerCase() === 'scopes') {
      return new CdsEntityDescriptor(resourceId);
    } else {
      throw Error(`Not enough segments in site or slot or scope id`);
    }

    // tslint:disable-next-line:no-increment-decrement
    for (let i = 0; i <= maxIndex; i++) {
      // tslint:disable-next-line:prefer-template
      siteId = siteId + '/' + parts[i];
    }

    return new ArmSiteDescriptor(siteId);
  }
  public site: string;
  public slot: string;

  private _websiteId: WebsiteId;

  constructor(resourceId: string) {
    super(resourceId);

    if (this.parts.length < 8) {
      throw Error(`resourceId length is too short for site descriptor: ${resourceId}`);
    }

    if (this.parts[6].toLowerCase() !== 'sites') {
      throw Error(`Expected sites segment in resourceId: ${resourceId}`);
    }

    this.site = this.parts[7];

    if (this.parts.length > 8 && this.parts[8].toLowerCase() === 'slots') {
      this.slot = this.parts[9];
    }
  }

  public getSiteOnlyResourceId(): string {
    return `/subscriptions/${this.subscription}/resourceGroups/${this.resourceGroup}/providers/Microsoft.Web/sites/${this.site}`;
  }

  public getTrimmedResourceId(): string {
    // resource id without slot information
    let resource = this.getSiteOnlyResourceId();
    // add slots if available
    if (this.slot && this.slot !== 'new') {
      resource = `${resource}/slots/${this.slot}`;
    }
    return resource;
  }

  public getWebsiteId(): WebsiteId {
    if (!this._websiteId) {
      const name = !this.slot ? this.site : `${this.site}(${this.slot})`;
      this._websiteId = {
        Name: name,
        SubscriptionId: this.subscription,
        ResourceGroup: this.resourceGroup,
      };
    }

    return this._websiteId;
  }
}

// tslint:disable-next-line:max-classes-per-file
export class ArmPlanDescriptor extends ArmResourceDescriptor {
  public static getSiteDescriptor(resourceId: string): ArmPlanDescriptor | CdsEntityDescriptor {
    const parts = resourceId.split('/').filter(part => !!part);
    let planId = '';
    let maxIndex: number;

    if (parts.length >= 8 && parts[6].toLowerCase() === 'serverfarms') {
      maxIndex = 7;
    } else {
      throw Error(`Not enough segments in server farm`);
    }

    // tslint:disable-next-line:no-increment-decrement
    for (let i = 0; i <= maxIndex; i++) {
      // tslint:disable-next-line:prefer-template
      planId = planId + '/' + parts[i];
    }

    return new ArmPlanDescriptor(planId);
  }
  public name: string;

  constructor(resourceId: string) {
    super(resourceId);

    if (this.parts.length < 8) {
      throw Error(`resourceId length is too short for serverfarm descriptor: ${resourceId}`);
    }

    if (this.parts[6].toLowerCase() !== 'serverfarms') {
      throw Error(`Expected serverfarms segment in resourceId: ${resourceId}`);
    }

    this.name = this.parts[7];
  }

  public getTrimmedResourceId(): string {
    return `/subscriptions/${this.subscription}/resourceGroups/${this.resourceGroup}/providers/Microsoft.Web/serverfarms/${this.name}`;
  }
}

export interface FunctionDescriptor extends Descriptor {
  name: string;
}

// tslint:disable-next-line:max-classes-per-file
export class ArmFunctionDescriptor extends ArmSiteDescriptor implements FunctionDescriptor {
  public static getFunctionDescriptor(resourceId: string): FunctionDescriptor {
    const parts = resourceId.split('/').filter(part => !!part);

    if (parts.length >= 8 && parts[6].toLowerCase() === 'entities') {
      return new CdsFunctionDescriptor(resourceId);
    }
    return new ArmFunctionDescriptor(resourceId);
  }
  public name: string;
  private _isProxy: boolean;

  constructor(resourceId: string) {
    super(resourceId);

    if (!this.slot) {
      if (this.parts.length < 10) {
        throw Error('Not a site function/proxy id');
      }

      if (this.parts[8].toLowerCase() !== 'functions' && this.parts[8].toLowerCase() !== 'proxies') {
        throw Error('Not a site function/proxy id');
      }

      if (this.parts[9].toLowerCase() === 'new' && this.parts.length > 10 && this.parts[10] === 'function') {
        throw Error('Not a site function/proxy id');
      }

      this._isProxy = this.parts[8].toLowerCase() === 'proxies';
      this.name = this.parts[9];
    } else {
      if (this.parts.length < 12) {
        throw Error('Not a slot function/proxy id');
      }

      if (this.parts[10].toLowerCase() !== 'functions' && this.parts[10].toLowerCase() !== 'proxies') {
        throw Error('Not a slot function/proxy id');
      }

      this._isProxy = this.parts[10].toLowerCase() === 'proxies';
      this.name = this.parts[11];
    }
  }

  public getTrimmedResourceId() {
    return `${super.getTrimmedResourceId()}/${this._isProxy ? 'proxies' : 'functions'}/${this.name}`;
  }
}

// tslint:disable-next-line:max-classes-per-file
export class ARMApplicationInsightsDescriptior extends ArmResourceDescriptor {
  public instanceName: string;

  constructor(resourceId: string) {
    super(resourceId);

    if (this.parts.length < 8) {
      throw Error(`resourceId length is too short for Application Insights: ${resourceId}`);
    }

    this.instanceName = this.parts[7];
  }

  public getTrimmedResourceId() {
    return `/${this.parts.join('/')}`;
  }

  public getResourceIdForDirectUrl() {
    // NOTE(michinoy): The aiResourceId is /subscriptions/<sub>/resourceGroups/<rg>/providers/microsoft.insights/components/<name>
    // to call the app insights instance directly we need /subscriptions/<sub>/resourceGroups/<rg>/components/<name>
    return `subscriptions/${this.subscription}/resourceGroups/${this.resourceGroup}/components/${this.instanceName}`;
  }
}


text:
//$URL$
//$Id$
package de.dev.eth0.bitcointrader.ui.fragments;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewStyle;
import com.jjoe64.graphview.LineGraphView;
import com.xeiam.xchange.dto.marketdata.OrderBook;
import com.xeiam.xchange.dto.trade.LimitOrder;
import de.dev.eth0.bitcointrader.BitcoinTraderApplication;
import de.dev.eth0.bitcointrader.Constants;
import de.dev.eth0.bitcointrader.R;
import de.dev.eth0.bitcointrader.ui.AbstractBitcoinTraderActivity;
import de.dev.eth0.bitcointrader.util.ICSAsyncTask;
import de.schildbach.wallet.ui.HelpDialogFragment;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * @author Alexander Muthmann
 */
public class MarketDepthFragment extends AbstractBitcoinTraderFragment {

  private static final String TAG = MarketDepthFragment.class.getSimpleName();
  private BitcoinTraderApplication application;
  private AbstractBitcoinTraderActivity activity;
  private ProgressDialog mDialog;
  private LineGraphView graphView;
  private GraphViewSeries asksSeries;
  private GraphViewSeries bidsSeries;

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.activity = (AbstractBitcoinTraderActivity)activity;
    this.application = (BitcoinTraderApplication)activity.getApplication();
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    setHasOptionsMenu(true);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.bitcointrader_options_help:
        HelpDialogFragment.page(activity.getSupportFragmentManager(), "help_market_depth");
        return true;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.market_depth_fragment, container);
    return view;
  }

  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    graphView = new LineGraphView(activity, "");
    graphView.setGraphViewStyle(new GraphViewStyle(Color.BLACK, Color.BLACK, Color.BLACK));
    graphView.setHorizontalLabelsOffset(true);
    LinearLayout layout = (LinearLayout)view.findViewById(R.id.market_depth_graph);
    layout.addView(graphView);
  }

  @Override
  public void onPause() {
    super.onPause();
    if (mDialog != null && mDialog.isShowing()) {
      mDialog.dismiss();
    }
    mDialog = null;
  }

  @Override
  public void onResume() {
    super.onResume();
    updateView();
  }

  @Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.marketdepth_options, menu);
  }

  protected void updateView() {
    Log.d(TAG, ".updateView()");
    OrderBook ob = application.getCache().getEntry(OrderBook.class);
    if (ob == null) {
      MarketDepthFragment.GetOrderBookTask tradesTask = new MarketDepthFragment.GetOrderBookTask();
      tradesTask.executeOnExecutor(ICSAsyncTask.SERIAL_EXECUTOR);
    }
    else {
      updateView(ob);
    }
  }

  protected void updateView(OrderBook orderBook) {
    Log.d(TAG, ".updateView");
    if (orderBook != null) {
      List<LimitOrder> asks = orderBook.getAsks();
      List<LimitOrder> bids = orderBook.getBids();
      GraphViewData[] asksData = buildGraphViewData(asks, true);
      if (asksSeries == null) {
        asksSeries = new GraphViewSeries(getString(R.string.market_depth_asks_graph_title), new GraphViewSeries.GraphViewSeriesStyle(Color.rgb(90, 250, 00), 3), asksData);
      }
      else {
        asksSeries.resetData(asksData);
      }
      graphView.addSeries(asksSeries);

      GraphViewData[] bidsData = buildGraphViewData(bids, false);
      if (bidsData.length > 0) {
        if (bidsSeries == null) {
          bidsSeries = new GraphViewSeries(getString(R.string.market_depth_bids_graph_title), new GraphViewSeries.GraphViewSeriesStyle(Color.rgb(200, 50, 00), 3), bidsData);
        }
        else {
          bidsSeries.resetData(bidsData);
        }
        graphView.addSeries(bidsSeries);
        graphView.setViewPort(bidsData[0].valueX, (asksData[asksData.length - 1].valueX) - bidsData[0].valueX);
        graphView.setScalable(true);
        graphView.setScrollable(true);
        graphView.redrawAll();
      }
    }
  }

  private GraphViewData[] buildGraphViewData(List<LimitOrder> orders, boolean assending) {
    Map<Double, Double> data = assending ? new TreeMap<Double, Double>() : new LinkedHashMap<Double, Double>();
    Log.d(TAG, "orders.size() == " + orders.size());
    for (int i = 0; i < orders.size(); i++) {
      LimitOrder cd = orders.get(i);
      double xValue = Math.round((cd.getLimitPrice().getAmount().doubleValue()) * 100.0) / 100.0;
      if (!data.containsKey(xValue)) {
        data.put(xValue, cd.getTradableAmount().doubleValue());
      }
      else {
        data.put(xValue, data.get(xValue) + cd.getTradableAmount().doubleValue());
      }
    }
    GraphViewData[] ret = new GraphViewData[data.size()];
    if (assending) {
      int i = 0;
      double value = 0;
      for (Entry<Double, Double> entry : data.entrySet()) {
        value += entry.getValue();
        GraphViewData gvd = new GraphViewData(entry.getKey(), value);
        ret[i++] = gvd;
        Log.d(TAG, gvd.valueX + "/" + gvd.valueY);
      }
    }
    else {
      int i = ret.length;
      double value = 0;
      for (Entry<Double, Double> entry : data.entrySet()) {
        value += entry.getValue();
        GraphViewData gvd = new GraphViewData(entry.getKey(), value);
        ret[--i] = gvd;
        Log.d(TAG, gvd.valueX + "/" + gvd.valueY);
      }
    }
    return ret;
  }

  private class GetOrderBookTask extends ICSAsyncTask<Void, Void, OrderBook> {

    @Override
    protected void onPreExecute() {
      if (mDialog == null) {
        mDialog = new ProgressDialog(activity);
        mDialog.setMessage(mDialogLoadingString);
        mDialog.setCancelable(false);
        mDialog.setOwnerActivity(activity);
        mDialog.show();
      }
    }

    @Override
    protected void onPostExecute(OrderBook orderBook) {
      if (mDialog != null && mDialog.isShowing()) {
        mDialog.dismiss();
        mDialog = null;
      }
      application.getCache().put(orderBook);
      updateView(orderBook);
    }

    @Override
    protected OrderBook doInBackground(Void... params) {
      try {
        Log.d(TAG, "Loading orderbook");
        return getExchangeService().getOrderBook();
      }
      catch (Exception e) {
        Intent intent = new Intent(Constants.UPDATE_FAILED);
        intent.putExtra(Constants.EXTRA_MESSAGE, e.getLocalizedMessage());
        activity.sendBroadcast(intent);
        Log.e(TAG, Log.getStackTraceString(e), e);
      }
      return null;
    }
  };
}


text:
#include "common.h"

static memcached_return_t memcached_flush_binary(memcached_st *ptr,
                                                 time_t expiration);
static memcached_return_t memcached_flush_textual(memcached_st *ptr,
                                                  time_t expiration);

memcached_return_t memcached_flush(memcached_st *ptr, time_t expiration)
{
  memcached_return_t rc;

  LIBMEMCACHED_MEMCACHED_FLUSH_START();
  if (ptr->flags.binary_protocol)
    rc= memcached_flush_binary(ptr, expiration);
  else
    rc= memcached_flush_textual(ptr, expiration);
  LIBMEMCACHED_MEMCACHED_FLUSH_END();
  return rc;
}

static memcached_return_t memcached_flush_textual(memcached_st *ptr,
                                                  time_t expiration)
{
  unsigned int x;
  unlikely (memcached_server_count(ptr) == 0)
    return MEMCACHED_NO_SERVERS;

  for (x= 0; x < memcached_server_count(ptr); x++)
  {
    memcached_return_t rc;
    char buffer[MEMCACHED_DEFAULT_COMMAND_SIZE];

    bool no_reply= ptr->flags.no_reply;
    memcached_server_write_instance_st instance=
      memcached_server_instance_fetch(ptr, x);

    int send_length;
    if (expiration)
    {
       /* We don't support delayed flush */
       return MEMCACHED_FAILURE;

#if 0
      send_length= snprintf(buffer, MEMCACHED_DEFAULT_COMMAND_SIZE,
                            "flush_all %llu%s\r\n",
                            (unsigned long long)expiration, no_reply ? " noreply" : "");
#endif
    }
    else
    {
      send_length= snprintf(buffer, MEMCACHED_DEFAULT_COMMAND_SIZE,
                            "flush_all%s\r\n", no_reply ? " noreply" : "");
    }

    if (send_length >= MEMCACHED_DEFAULT_COMMAND_SIZE || send_length < 0)
    {
      return MEMCACHED_FAILURE;
    }

    rc= memcached_do(instance, buffer, (size_t)send_length, true);

    if (rc == MEMCACHED_SUCCESS && !no_reply)
      (void)memcached_response(instance, buffer, MEMCACHED_DEFAULT_COMMAND_SIZE, NULL);
  }

  return MEMCACHED_SUCCESS;
}

static memcached_return_t memcached_flush_binary(memcached_st *ptr,
                                                 time_t expiration)
{
  uint32_t x;
  protocol_binary_request_flush request;
  memset(&request, 0, sizeof(request));

  unlikely (memcached_server_count(ptr) == 0)
    return MEMCACHED_NO_SERVERS;

  request.message.header.request.magic= (uint8_t)PROTOCOL_BINARY_REQ;
  request.message.header.request.opcode= PROTOCOL_BINARY_CMD_FLUSH;
  request.message.header.request.extlen= 4;
  request.message.header.request.datatype= PROTOCOL_BINARY_RAW_BYTES;
  request.message.header.request.bodylen= htonl(request.message.header.request.extlen);
  request.message.body.expiration= htonl((uint32_t) expiration);

  for (x= 0; x < memcached_server_count(ptr); x++)
  {
    memcached_server_write_instance_st instance=
      memcached_server_instance_fetch(ptr, x);

    if (ptr->flags.no_reply)
    {
      request.message.header.request.opcode= PROTOCOL_BINARY_CMD_FLUSHQ;
    }
    else
    {
      request.message.header.request.opcode= PROTOCOL_BINARY_CMD_FLUSH;
    }

    if (memcached_do(instance, request.bytes, sizeof(request.bytes), true) != MEMCACHED_SUCCESS)
    {
      memcached_io_reset(instance);
      return MEMCACHED_WRITE_FAILURE;
    }
  }

  for (x= 0; x < memcached_server_count(ptr); x++)
  {
    memcached_server_write_instance_st instance=
      memcached_server_instance_fetch(ptr, x);

    if (memcached_server_response_count(instance) > 0)
      (void)memcached_response(instance, NULL, 0, NULL);
  }

  return MEMCACHED_SUCCESS;
}


text:
require 'video_info/version'
require 'video_info/provider'
require 'forwardable'
require 'net/http'
require 'logger'

class VideoInfo
  class Error < StandardError; end
  class UrlError < Error; end
  class HttpError < Error; end

  class << self
    attr_writer :logger
    attr_accessor :disable_providers, :provider_api_keys

    def disable_providers
      @disable_providers || []
    end

    def provider_api_keys
      @provider_api_keys || {}
    end

    def provider_api_keys=(api_keys)
      api_keys.keys.each do |key|
        raise ArgumentError, 'Key must be a symbol!' unless key.is_a?(Symbol)
      end
      @provider_api_keys = api_keys
    end

    def logger
      @logger ||= Logger.new($stdout).tap do |lgr|
        lgr.progname = name
      end
    end
  end

  extend Forwardable

  PROVIDERS = %w[
    Dailymotion Vkontakte Wistia
    Vimeo Youtube YoutubePlaylist
  ].freeze
  PROVIDERS.each { |p| require "video_info/providers/#{p.downcase}" }

  def_delegators :@provider, :provider, :video_id, :video_owner, :url, :data
  def_delegators :@provider, :title, :description, :keywords, :view_count
  def_delegators :@provider, :date, :duration, :width, :height
  def_delegators :@provider, :thumbnail
  def_delegators :@provider,
                 :thumbnail_small,
                 :thumbnail_medium,
                 :thumbnail_large
  def_delegators :@provider, :embed_code, :embed_url
  def_delegators :@provider, :available?
  def_delegators :@provider, :playlist_id, :videos
  def_delegators :@provider, :author, :author_thumbnail, :author_url
  def_delegators :@provider, :data=

  def initialize(url, options = {})
    @provider = _select_provider(url, options)
  end

  def self.get(*args)
    new(*args)
  end

  def self.usable?(url)
    new(url)
    true
  rescue UrlError
    false
  end

  def ==(other)
    url == other.url && video_id == other.video_id
  end

  def self.disabled_provider?(provider)
    disable_providers.map(&:downcase).include?(provider.downcase)
  end

  private

  def _select_provider(url, options)
    if provider_const = _providers_const.detect { |p| p.usable?(url) }
      const_provider = provider_const.new(url, options)

      if defined?(const_provider.provider) && const_provider.provider
        ensure_enabled_provider(const_provider.provider)
      end

      const_provider
    else
      raise UrlError, "Url is not usable by any Providers: #{url}"
    end
  end

  def _providers_const
    PROVIDERS.map { |p| Providers.const_get(p) }
  end

  def ensure_enabled_provider(provider)
    if self.class.disabled_provider?(provider)
      raise UrlError, "#{provider} is disabled"
    end
  end
end


text:
layout: project
name: Open Pollution
description: A real-time visualization of pollution using open data
date: 2013_10_01
---
![OpenPollution]({{ site.url }}/assets/Openpollution.jpg)

Open Pollution is a data-visualization project utilizing open data from the Open Data Copenhagen platform (http://data.kk.dk/).

Pollution data is visualized, in real-time, on a map of Copenhagen by switching pixels, generating a glitch-like effect concentrated on the areas were the data shows a higher concentration of pollution.

The project aims to bring attention to the invisible pollution by utilizing the glitch-like effects as both a metaphor for the pollution and a visualization of it.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
using Microsoft.CodeAnalysis;
using Wyam.Common.Util;

namespace Wyam.Razor
{
    internal class MetadataReferenceFeatureProvider : IApplicationFeatureProvider<MetadataReferenceFeature>
    {
        private readonly IList<MetadataReference> _metadataReferences;

        public MetadataReferenceFeatureProvider(DynamicAssemblyCollection dynamicAssemblies)
        {
            _metadataReferences = AppDomain.CurrentDomain.GetAssemblies()
                .Where(x => !x.IsDynamic && !string.IsNullOrEmpty(x.Location))
                .Select(x => MetadataReference.CreateFromFile(x.Location))
                .Concat((dynamicAssemblies ?? Enumerable.Empty<byte[]>())
                    .Select(x => (MetadataReference)MetadataReference.CreateFromImage(x)))
                .Concat(new MetadataReference[]
                {
                    // Razor/MVC assemblies that might not be loaded yet
                    MetadataReference.CreateFromFile(typeof(IHtmlContent).GetTypeInfo().Assembly.Location),
                    MetadataReference.CreateFromFile(Assembly.Load(new AssemblyName("Microsoft.CSharp")).Location)
                })
                .ToList();
        }

        public void PopulateFeature(IEnumerable<ApplicationPart> parts, MetadataReferenceFeature feature)
        {
            if (parts == null)
            {
                throw new ArgumentNullException(nameof(parts));
            }

            if (feature == null)
            {
                throw new ArgumentNullException(nameof(feature));
            }

            feature.MetadataReferences.AddRange(_metadataReferences);
        }
    }
}


text:
layout: default
---

{{ page.title }}

 {{ page.date | date: "%d" }}-{{ page.date | date: "%m" }}-{{ page.date | date: "%Y" }}{% if page.meta %}  {{ page.meta }}{% endif %}

    {% for cat in page.categories %}
    {{ cat }}{% unless page.categories.last == category %}  {% endunless %}
    {% endfor %}

    {% for tag in page.tags %}
    {{ tag }} {% unless page.tags.last == tag %}  {% endunless %}
    {% endfor %}

    {{ content }}

    {% if page.previous %}
      {{ page.previous.title }}
    {% else %}
    Artículo Anterior
    {% endif %}

    {% if page.next %}
    {{ page.next.title }}
    {% else %}
    Próximo Artículo
    {% endif %}


text:
import wiiboard
import time
import sys
import getopt
from PyQt4 import QtGui, QtCore

from bluetooth import *

starttime = time.time()
rate = 0.05

def writeFile(valuesSides):
    #top, bottom, left, right
    with open("balanceBoardData", "w") as btDataFile:
        dataString = ""
        for val in valuesSides:
            dataString += str(int(val)) + " "
        btDataFile.write(dataString)

def main():
    ready = False
    board = None
    board = wiiboard.Wiiboard()
    connected = False
    valuesSides = []

    while(True):
        # Check if connection status changed
        if connected is not board.isConnected():
            connected = board.isConnected()
            if connected:
                print "connected"
            else:
                print "disconnected"
                #Turn off lights
                time.sleep(0.1) # This is needed for wiiboard.py
                board.setLight(False)

        # Connect to balance board
        if not board.isConnected():
            # Re initialize each run due to bug in wiiboard
            # Note: Seems to be working though :/
            board = wiiboard.Wiiboard()
            print "SYNC"

            address = board.discover()

            if not address:
                sleep = True
                print "NO DEVICE FOUND"
                return []

            print "CONNECTING"
            board.connect(address)

            if board.isConnected():
                connected = True
                print "CONNECTED"

        #Board is connected and ready
        if board.isConnected():

            # Post ready status once
            if not ready:
                ready = True
                time.sleep(0.1) # This is needed for wiiboard.py
                board.setLight(True)
                print "READY"

            valuesSides = board.mass.valuesSides
            print valuesSides
            writeFile(valuesSides)

        time.sleep(rate - ((time.time() - starttime) % rate))

if __name__ == "__main__":
    main()


text:
<?php

return [

    'password' => 'Passwords must be at least six characters and match the confirmation.',
    'reset'    => 'Your password has been reset!',
    'sent'     => 'We have e-mailed your password reset link!',
    'token'    => 'This password reset token is invalid.',
    'user'     => 'We can\'t find a user with that e-mail address.',

];