text:
/*
 * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
 */
package javax.xml.crypto.test.dsig;

import java.io.*;
import java.security.*;
import java.security.cert.Certificate;
import java.util.*;

import javax.xml.crypto.dom.DOMStructure;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.*;
import javax.xml.crypto.dsig.keyinfo.*;
import javax.xml.crypto.dsig.spec.*;

import org.w3c.dom.*;

import javax.xml.crypto.test.KeySelectors;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Test that recreates interop exc C14N test vectors
 * but with different keys.
 *
 */
public class CreateInteropExcC14NTest {

    private XMLSignatureFactory fac;
    private KeyInfoFactory kifac;
    private KeyStore ks;
    private Key signingKey;
    private PublicKey validatingKey;

    static {
        Security.insertProviderAt
            (new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI(), 1);
    }

    public CreateInteropExcC14NTest() throws Exception {
        fac = XMLSignatureFactory.getInstance
            ("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());
        kifac = fac.getKeyInfoFactory();

        // get key & self-signed certificate from keystore
        String base = System.getProperty("basedir") == null ? "./": System.getProperty("basedir");

        String fs = System.getProperty("file.separator");
        try (FileInputStream fis = new FileInputStream
            (base + fs + "src/test/resources" + fs + "test.jks")) {
            ks = KeyStore.getInstance("JKS");
            ks.load(fis, "changeit".toCharArray());
        }
        Certificate signingCert = ks.getCertificate("mullan");
        signingKey = ks.getKey("mullan", "changeit".toCharArray());
        validatingKey = signingCert.getPublicKey();
    }

    @org.junit.jupiter.api.Test
    public void test_create_Y1() throws Exception {
        List<Reference> refs = new ArrayList<>(4);

        // create reference 1
        refs.add(fac.newReference
            ("#xpointer(id('to-be-signed'))",
             fac.newDigestMethod(DigestMethod.SHA1, null),
             Collections.singletonList
                (fac.newTransform(CanonicalizationMethod.EXCLUSIVE,
                 (TransformParameterSpec) null)),
             null, null));

        // create reference 2
        List<String> prefixList = new ArrayList<>(2);
        prefixList.add("bar");
        prefixList.add("#default");
        ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);
        refs.add(fac.newReference
            ("#xpointer(id('to-be-signed'))",
             fac.newDigestMethod(DigestMethod.SHA1, null),
             Collections.singletonList
                (fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)),
             null, null));

        // create reference 3
        refs.add(fac.newReference
            ("#xpointer(id('to-be-signed'))",
             fac.newDigestMethod(DigestMethod.SHA1, null),
             Collections.singletonList(fac.newTransform
                (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
                 (TransformParameterSpec) null)),
             null, null));

        // create reference 4
        prefixList = new ArrayList<>(2);
        prefixList.add("bar");
        prefixList.add("#default");
        params = new ExcC14NParameterSpec(prefixList);
        refs.add(fac.newReference
            ("#xpointer(id('to-be-signed'))",
             fac.newDigestMethod(DigestMethod.SHA1, null),
             Collections.singletonList(fac.newTransform
                (CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
                 params)),
             null, null));

        // create SignedInfo
        SignedInfo si = fac.newSignedInfo(
            fac.newCanonicalizationMethod
                (CanonicalizationMethod.EXCLUSIVE,
                 (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs);

        // create KeyInfo
        List<KeyValue> kits = new ArrayList<>(2);
        kits.add(kifac.newKeyValue(validatingKey));
        KeyInfo ki = kifac.newKeyInfo(kits);

        // create Objects
        Document doc = TestUtils.newDocument();
        Element baz = doc.createElementNS("urn:bar", "bar:Baz");
        Comment com = doc.createComment(" comment ");
        baz.appendChild(com);
        XMLObject obj = fac.newXMLObject(Collections.singletonList
            (new DOMStructure(baz)), "to-be-signed", null, null);

        // create XMLSignature
        XMLSignature sig = fac.newXMLSignature
            (si, ki, Collections.singletonList(obj), null, null);

        Element foo = doc.createElementNS("urn:foo", "Foo");
        foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo");
        foo.setAttributeNS
            ("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar");
        doc.appendChild(foo);

        DOMSignContext dsc = new DOMSignContext(signingKey, foo);
        dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");

        sig.sign(dsc);
        TestUtils.validateSecurityOrEncryptionElement(foo.getLastChild());

        DOMValidateContext dvc = new DOMValidateContext
            (new KeySelectors.KeyValueKeySelector(), foo.getLastChild());
        XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);

        assertEquals(sig, sig2);

        assertTrue(sig2.validate(dvc));
    }

}


text:
<?php

namespace Ben\GalleryBundle\Controller;

use Ben\GalleryBundle\Entity\Media;
use Ben\GalleryBundle\Form\MediaType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class GalleryController extends Controller
{
    public function indexAction(Request $request)
    {
        $media = new Media();

        $form = $this->createForm(new MediaType(),$media);

        if($form->handleRequest($request)->isValid()){

            $em = $this->getDoctrine()->getManager();
            $em->persist($media);
            $em->flush();

            return $this->redirectToRoute('gallery_home');
            }

        $category = $this->getDoctrine()->getRepository('BenGalleryBundle:Category');
        $categories = $category->findAll();

        $med = $this->getDoctrine()->getRepository('BenGalleryBundle:Media');
        $pictures = $med->findMediasByCategory(2);

        return $this->render('BenGalleryBundle:Gallery:index.html.twig',array(
            'form' => $form->createView(),
            'media' => $media,
            'categories' => $categories,
            'pictures' => $pictures

            ));
    }

    public function editAction($id,Request $request){
        $em = $this->getDoctrine()->getManager();

        //récupération de la catégorie

        $category = $em->getRepository('BenGalleryBundle:Category')->find($id);

        if (null === $category){
            throw new NotFoundHttpException("L'annonce d'id " .id." n'existe pas");
        }

        //récupération de tous les médias
        $listMedias = $em->getRepository('BenGalleryBundle:Media')->findAll();

        $em->flush();

       return $this->redirect('gallery_home');
    }

}

redpajama_set_name: RedPajamaGithub


text:
module ActiveAdminAssociations
  module RedirectDestroyActions
    def destroy
      destroy!{ request.headers["Referer"].presence || admin_dashboard_url }
    end
  end
end


text:
nova.instrumentation

Supporting code for Digital Instrumentation class at Universidade Nova de Lisboa.


text:
import { FeedingLogListComponent} from "./feeding-log-list.component"
import { FeedingLogFormComponent } from './feeding-log-form.component'
import { FeedingLogTimeSinceComponent } from './feeding-log-time-since.component'

export const FEEDING_LOGS_DECLERATIONS = [
    FeedingLogListComponent,
    FeedingLogFormComponent,
    FeedingLogTimeSinceComponent,
];

export const FEEDING_LOGS_PROVIDERS = [

];


text:
SwiftExamples
=============

A Bunch of Examples and Resources that correspond to the Swift Book.

- Chapter 1
	- Chapter1.playground: A playground file to get started by messing around in playgrounds
	- MyFirstApp.xcodeproj: What the Student ends up with at the end of the Chapter

- Chapter 2
	- Chapter2.playground
	- MySecondApp.xcodeproj: More experimentations with Xcode and stuff.

- Chapter 3: Stand To Make
	- Chapter3.playground
	- StandToMake.xcodeproj: The Student's first work on the Stand to Make app.

- Chapter 4: Controls
	- Chapter4.playground
	- StandToMake.xcodeproj: Implement most of the Controls necessary.

- Chapter 5: TablieViews
	- Chapter5.playground: review of collection types
	- MyFirstApp.xcodeproj: Add the TableView portion of the app.

- Chapter 6: Releasing to the app store
	- Chapter6.playground:
	- MyFirstApp.xcodeproj:


text:
'use strict';

import * as strings from 'vs/base/common/strings';
import { Range } from 'vs/editor/common/core/range';
import { TextEdit } from 'vs/editor/common/modes';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { Selection } from 'vs/editor/common/core/selection';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { ITextModel, EndOfLineSequence, ISingleEditOperation } from 'vs/editor/common/model';

export class EditOperationsCommand implements editorCommon.ICommand {

	static execute(editor: ICodeEditor, edits: TextEdit[]) {
		const cmd = new EditOperationsCommand(edits, editor.getSelection());
		if (typeof cmd._newEol === 'number') {
			editor.getModel().setEOL(cmd._newEol);
		}
		editor.pushUndoStop();
		editor.executeCommand('formatEditsCommand', cmd);
		editor.pushUndoStop();
	}

	private _edits: TextEdit[];
	private _newEol: EndOfLineSequence;

	private _initialSelection: Selection;
	private _selectionId: string;

	constructor(edits: TextEdit[], initialSelection: Selection) {
		this._initialSelection = initialSelection;
		this._edits = [];
		this._newEol = undefined;

		for (let edit of edits) {
			if (typeof edit.eol === 'number') {
				this._newEol = edit.eol;
			}
			if (edit.range && typeof edit.text === 'string') {
				this._edits.push(edit);
			}
		}
	}

	public getEditOperations(model: ITextModel, builder: editorCommon.IEditOperationBuilder): void {

		for (let edit of this._edits) {
			// We know that this edit.range comes from the mirror model, so it should only contain \n and no \r's
			let trimEdit = EditOperationsCommand.trimEdit(edit, model);
			if (trimEdit !== null) { // produced above in case the edit.text is identical to the existing text
				builder.addEditOperation(Range.lift(edit.range), edit.text);
			}
		}

		var selectionIsSet = false;
		if (Array.isArray(this._edits) && this._edits.length === 1 && this._initialSelection.isEmpty()) {
			if (this._edits[0].range.startColumn === this._initialSelection.endColumn &&
				this._edits[0].range.startLineNumber === this._initialSelection.endLineNumber) {
				selectionIsSet = true;
				this._selectionId = builder.trackSelection(this._initialSelection, true);
			} else if (this._edits[0].range.endColumn === this._initialSelection.startColumn &&
				this._edits[0].range.endLineNumber === this._initialSelection.startLineNumber) {
				selectionIsSet = true;
				this._selectionId = builder.trackSelection(this._initialSelection, false);
			}
		}

		if (!selectionIsSet) {
			this._selectionId = builder.trackSelection(this._initialSelection);
		}
	}

	public computeCursorState(model: ITextModel, helper: editorCommon.ICursorStateComputerData): Selection {
		return helper.getTrackedSelection(this._selectionId);
	}

	static fixLineTerminators(edit: ISingleEditOperation, model: ITextModel): void {
		edit.text = edit.text.replace(/\r\n|\r|\n/g, model.getEOL());
	}

	/**
	 * This is used to minimize the edits by removing changes that appear on the edges of the range which are identical
	 * to the current text.
	 *
	 * The reason this was introduced is to allow better selection tracking of the current cursor and solve
	 * bug #15108. There the cursor was jumping since the tracked selection was in the middle of the range edit
	 * and was lost.
	 */
	static trimEdit(edit: ISingleEditOperation, model: ITextModel): ISingleEditOperation {

		this.fixLineTerminators(edit, model);

		return this._trimEdit(model.validateRange(edit.range), edit.text, edit.forceMoveMarkers, model);
	}

	static _trimEdit(editRange: Range, editText: string, editForceMoveMarkers: boolean, model: ITextModel): ISingleEditOperation {

		let currentText = model.getValueInRange(editRange);

		// Find the equal characters in the front
		let commonPrefixLength = strings.commonPrefixLength(editText, currentText);

		// If the two strings are identical, return no edit (no-op)
		if (commonPrefixLength === currentText.length && commonPrefixLength === editText.length) {
			return null;
		}

		if (commonPrefixLength > 0) {
			// Apply front trimming
			let newStartPosition = model.modifyPosition(editRange.getStartPosition(), commonPrefixLength);
			editRange = new Range(newStartPosition.lineNumber, newStartPosition.column, editRange.endLineNumber, editRange.endColumn);
			editText = editText.substring(commonPrefixLength);
			currentText = currentText.substr(commonPrefixLength);
		}

		// Find the equal characters in the rear
		let commonSuffixLength = strings.commonSuffixLength(editText, currentText);

		if (commonSuffixLength > 0) {
			// Apply rear trimming
			let newEndPosition = model.modifyPosition(editRange.getEndPosition(), -commonSuffixLength);
			editRange = new Range(editRange.startLineNumber, editRange.startColumn, newEndPosition.lineNumber, newEndPosition.column);
			editText = editText.substring(0, editText.length - commonSuffixLength);
			currentText = currentText.substring(0, currentText.length - commonSuffixLength);
		}

		return {
			text: editText,
			range: editRange,
			forceMoveMarkers: editForceMoveMarkers
		};
	}
}


text:
from pymel.core.windows import *

class MelToPythonWindow(Window):

    def __new__(cls, name=None):
        self = window(title=name or "Mel To Python")
        return Window.__new__(cls, self)

    def convert(w):
        from .. import mel2pyStr
        if cmds.cmdScrollFieldExecuter(w.mel, q=1, hasSelection=1):
            cmds.cmdScrollFieldExecuter(w.mel, e=1, copySelection=1)
            cmds.cmdScrollFieldExecuter(w.python, e=1, clear=1)
            cmds.cmdScrollFieldExecuter(w.python, e=1, pasteSelection=1)
            mel = cmds.cmdScrollFieldExecuter(w.python, q=1, text=1)
        else:
            mel = cmds.cmdScrollFieldExecuter(w.mel, q=1, text=1)
        try:
            py = mel2pyStr(mel)
        except Exception, e:
            confirmDialog(t="Mel To Python", m="Conversion Error:\n%s" % e, b=["Ok"], db="Ok")
        else:
            cmds.cmdScrollFieldExecuter(w.python, e=1, text=py)

    def __init__(self):
        formLayout(slc=True, ratios=[1, .1, 1], orientation=FormLayout.HORIZONTAL, childCreators=[
            cmdScrollFieldExecuter("mel", slc=True),
            button("button", slc=True, l="->", c=lambda *x: self.convert(), bgc=[.5, .7, 1]),
            cmdScrollFieldExecuter("python", slc=True, st="python")
        ]).create(self.__dict__, parent=self, debug=1)

        self.setWidthHeight([600, 800])
        self.show()


text:
<?php

declare(strict_types=1);

namespace Talesweaver\Application\Form\Type\Item;

use Talesweaver\Application\Form\Form;

interface Create extends Form
{
}


text:
/*global defineSuite*/
defineSuite([
        'Scene/Globe',
        'Core/CesiumTerrainProvider',
        'Core/defined',
        'Core/Ellipsoid',
        'Core/loadWithXhr',
        'Core/Rectangle',
        'Renderer/ClearCommand',
        'Scene/SingleTileImageryProvider',
        'Specs/createContext',
        'Specs/createFrameState',
        'Specs/pollToPromise',
        'Specs/render'
    ], function(
        Globe,
        CesiumTerrainProvider,
        defined,
        Ellipsoid,
        loadWithXhr,
        Rectangle,
        ClearCommand,
        SingleTileImageryProvider,
        createContext,
        createFrameState,
        pollToPromise,
        render) {
    "use strict";
    /*global jasmine,describe,xdescribe,it,xit,expect,beforeEach,afterEach,beforeAll,afterAll,spyOn*/

    var context;
    var frameState;
    var globe;

    beforeAll(function() {
        context = createContext();
    });

    afterAll(function() {
        context.destroyForSpecs();
    });

    beforeEach(function() {
        frameState = createFrameState();
        globe = new Globe();
    });

    afterEach(function() {
        globe.destroy();
        loadWithXhr.load = loadWithXhr.defaultLoad;
    });

    function returnTileJson(path) {
        var oldLoad = loadWithXhr.load;
        loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
            if (url.indexOf('layer.json') >= 0) {
                loadWithXhr.defaultLoad(path, responseType, method, data, headers, deferred);
            } else {
                return oldLoad(url, responseType, method, data, headers, deferred, overrideMimeType);
            }
        };
    }

    function returnVertexNormalTileJson() {
        return returnTileJson('Data/CesiumTerrainTileJson/VertexNormals.tile.json');
    }

    /**
     * Repeatedly calls update until the load queue is empty.  Returns a promise that resolves
     * when the load queue is empty.
     */
    function updateUntilDone(globe) {
        // update until the load queue is empty.
        return pollToPromise(function() {
            globe._surface._debug.enableDebugOutput = true;
            var commandList = [];
            globe.update(context, frameState, commandList);
            return globe._surface.tileProvider.ready && !defined(globe._surface._tileLoadQueue.head) && globe._surface._debug.tilesWaitingForChildren === 0;
        });
    }

    it('renders with enableLighting', function() {
        globe.enableLighting = true;

        var layerCollection = globe.imageryLayers;
        layerCollection.removeAll();
        layerCollection.addImageryProvider(new SingleTileImageryProvider({url : 'Data/Images/Red16x16.png'}));

        frameState.camera.viewRectangle(new Rectangle(0.0001, 0.0001, 0.0025, 0.0025), Ellipsoid.WGS84);

        return updateUntilDone(globe).then(function() {
            ClearCommand.ALL.execute(context);
            expect(context.readPixels()).toEqual([0, 0, 0, 0]);

            render(context, frameState, globe);
            expect(context.readPixels()).not.toEqual([0, 0, 0, 0]);
        });
    });

    it('renders with showWaterEffect set to false', function() {
        globe.showWaterEffect = false;

        var layerCollection = globe.imageryLayers;
        layerCollection.removeAll();
        layerCollection.addImageryProvider(new SingleTileImageryProvider({url : 'Data/Images/Red16x16.png'}));

        frameState.camera.viewRectangle(new Rectangle(0.0001, 0.0001, 0.0025, 0.0025), Ellipsoid.WGS84);

        return updateUntilDone(globe).then(function() {
            ClearCommand.ALL.execute(context);
            expect(context.readPixels()).toEqual([0, 0, 0, 0]);

            render(context, frameState, globe);
            expect(context.readPixels()).not.toEqual([0, 0, 0, 0]);
        });
    });

    it('renders terrain with enableLighting', function() {
        globe.enableLighting = true;

        var layerCollection = globe.imageryLayers;
        layerCollection.removeAll();
        layerCollection.addImageryProvider(new SingleTileImageryProvider({url : 'Data/Images/Red16x16.png'}));

        loadWithXhr.load = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
            loadWithXhr.defaultLoad('Data/CesiumTerrainTileJson/tile.vertexnormals.terrain', responseType, method, data, headers, deferred);
        };

        returnVertexNormalTileJson();

        var terrainProvider = new CesiumTerrainProvider({
            url : 'made/up/url',
            requestVertexNormals : true
        });

        globe.terrainProvider = terrainProvider;

        return pollToPromise(function() {
            return terrainProvider.ready;
        }).then(function() {
            frameState.camera.viewRectangle(new Rectangle(0.0001, 0.0001, 0.0025, 0.0025), Ellipsoid.WGS84);

            return updateUntilDone(globe).then(function() {
                ClearCommand.ALL.execute(context);
                expect(context.readPixels()).toEqual([0, 0, 0, 0]);

                render(context, frameState, globe);
                expect(context.readPixels()).not.toEqual([0, 0, 0, 0]);
            });
        });
    });
}, 'WebGL');


text:
## Grade
Pela grade, podemos visualizar suas principais informações e fazer a manutenção de seus dados.
![projetoitens.grid](https://raw.githubusercontent.com/netforcews/docs-erp/master/geral/imagens/projetoitens.grid.png)

Campo | Descrição
--:|---
**Produto** |
**Descrição** |
**Qtdade** |

## Geral
![projetoitens.geral](https://raw.githubusercontent.com/netforcews/docs-erp/master/geral/imagens/projetoitens.geral.png)

Campo | Descrição
--:|---
**Produto** |
**Quantidade** |
**Valor Total** |

```CON_PROJETOITENS:PROJETOITENS```


text:
package org.shanerx.tradeshop.objects;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.block.ShulkerBox;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.shanerx.tradeshop.enumys.DebugLevels;
import org.shanerx.tradeshop.enumys.ShopItemStackSettingKeys;
import org.shanerx.tradeshop.utils.ObjectHolder;
import org.shanerx.tradeshop.utils.Utils;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

public class ShopItemStack implements Serializable, Cloneable {

    private transient ItemStack itemStack;
    private transient Debug debugger;

    private String itemStackB64;

    private HashMap<ShopItemStackSettingKeys, ObjectHolder<?>> shopSettings;

    public ShopItemStack(ItemStack itemStack) {
        this.itemStack = itemStack;
        shopSettings = new HashMap<>();
        buildMap();
        toBase64();
    }

    public ShopItemStack(ItemStack itemStack, HashMap<ShopItemStackSettingKeys, ObjectHolder<?>> settingMap) {
        this.itemStack = itemStack;
        this.shopSettings = settingMap;
        buildMap();
        toBase64();
    }

    public ShopItemStack(String itemStackB64) {
        this.itemStackB64 = itemStackB64;
        shopSettings = new HashMap<>();
        buildMap();
        fromBase64();
    }

    public ShopItemStack(String itemStackB64, HashMap<ShopItemStackSettingKeys, ObjectHolder<?>> settingMap) {
        this.itemStackB64 = itemStackB64;
        this.shopSettings = settingMap;
        buildMap();
        fromBase64();
    }

    //Re-added for backwards compatibility
    @Deprecated
    public ShopItemStack(String itemStackB64, int compareDurability, boolean compareEnchantments,
                         boolean compareName, boolean compareLore, boolean compareCustomModelData,
                         boolean compareItemFlags, boolean compareUnbreakable, boolean compareAttributeModifier,
                         boolean compareBookAuthor, boolean compareBookPages, boolean compareShulkerInventory) {
        this.itemStackB64 = itemStackB64;

        shopSettings = new HashMap<>();

        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_DURABILITY, new ObjectHolder<>(compareDurability));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_NAME, new ObjectHolder<>(compareName));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_LORE, new ObjectHolder<>(compareLore));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA, new ObjectHolder<>(compareCustomModelData));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS, new ObjectHolder<>(compareItemFlags));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE, new ObjectHolder<>(compareUnbreakable));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER, new ObjectHolder<>(compareAttributeModifier));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR, new ObjectHolder<>(compareBookAuthor));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES, new ObjectHolder<>(compareBookPages));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY, new ObjectHolder<>(compareShulkerInventory));
        shopSettings.putIfAbsent(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS, new ObjectHolder<>(compareEnchantments));

        buildMap();
        fromBase64();
    }

    public HashMap<ShopItemStackSettingKeys, ObjectHolder<?>> getShopSettings() {
        return shopSettings;
    }

    public static ShopItemStack deserialize(String serialized) {
        ShopItemStack item = new Gson().fromJson(serialized, ShopItemStack.class);
        item.fromBase64();
        item.buildMap();
        return item;
    }

    public boolean getShopSettingAsBoolean(ShopItemStackSettingKeys key) {
        try {
            ObjectHolder<?> tempObj = shopSettings.get(key);
            return shopSettings.containsKey(key) ? (Boolean) tempObj.getObject() : (Boolean) key.getDefaultValue().getObject();
        } catch (ClassCastException | NullPointerException e) {
            return (Boolean) key.getDefaultValue().getObject();
        }
    }

    public int getShopSettingAsInteger(ShopItemStackSettingKeys key) {
        try {
            ObjectHolder<?> tempObj = shopSettings.get(key);
            return shopSettings.containsKey(key) ? (Integer) tempObj.getObject() : (Integer) key.getDefaultValue().getObject();
        } catch (ClassCastException | NullPointerException e) {
            return (Integer) key.getDefaultValue().getObject();
        }
    }

    private void buildMap() {
        if (shopSettings == null) {
            shopSettings = new HashMap<>();
        }

        for (ShopItemStackSettingKeys key : ShopItemStackSettingKeys.values()) {
            shopSettings.putIfAbsent(key, key.getDefaultValue());
        }
    }

    public ShopItemStack clone() {
        try {
            ShopItemStack clone = (ShopItemStack) super.clone();
            if (itemStack != null)
                clone.itemStack = this.itemStack.clone();

            return clone;
        } catch (CloneNotSupportedException var2) {
            throw new Error(var2);
        }
    }

    public boolean setShopSettings(ShopItemStackSettingKeys key, ObjectHolder<?> value) {
        if (shopSettings == null) {
            shopSettings = new HashMap<>();
            buildMap();
        }

        shopSettings.put(key, value);
        return false;
    }

    public int getAmount() {
        if (itemStack == null) //TODO this fixes an NPE from this method when itemstack is null(idk why itemstack would be null, this fixes for now so hopefully it will be enough)
            return 0;
        return itemStack.getAmount();
    }

    public void setAmount(int amount) {
        itemStack.setAmount(amount);
        toBase64();
    }

    public String getItemStackB64() {
        return itemStackB64;
    }

    public boolean hasBase64() {
        return itemStackB64 != null && !itemStackB64.isEmpty();
    }

    public boolean isSimilar(ItemStack toCompare) {
        debugger = new Utils().debugger;

        // Return False if either item is null
        if (itemStack == null || toCompare == null) {
            return false;
        }

        // Return True if items are equal
        if (itemStack == toCompare) {
            return false;
        }

        // Return False if ItemStacks are different MaterialTypes
        if (itemStack.getType() != toCompare.getType()) {
            debugger.log("itemstack material: " + itemStack.getType(), DebugLevels.ITEM_COMPARE);
            debugger.log("toCompare material: " + toCompare.getType(), DebugLevels.ITEM_COMPARE);
            return false;
        }

        ItemMeta itemStackMeta = itemStack.getItemMeta(),
                toCompareMeta = toCompare.getItemMeta();
        BookMeta itemStackBookMeta = itemStack.hasItemMeta() && itemStack.getItemMeta() instanceof BookMeta ? ((BookMeta) itemStackMeta) : null,
                toCompareBookMeta = toCompare.hasItemMeta() && toCompare.getItemMeta() instanceof BookMeta ? ((BookMeta) toCompareMeta) : null;

        boolean useMeta = itemStack.hasItemMeta() == toCompare.hasItemMeta() && itemStack.hasItemMeta(),
                useBookMeta = itemStackBookMeta != null && toCompareBookMeta != null;

        debugger.log("itemstack useMeta: " + useMeta, DebugLevels.ITEM_COMPARE);
        debugger.log("toCompare useMeta: " + useMeta, DebugLevels.ITEM_COMPARE);

        // If compareShulkerInventory is on
        if (itemStack.getType().toString().endsWith("SHULKER_BOX") &&
                getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_SHULKER_INVENTORY)) {
            try {
                ArrayList<ItemStack> itemStackContents = Lists.newArrayList(((ShulkerBox) ((BlockStateMeta) toCompareMeta).getBlockState()).getInventory().getContents()),
                        toCompareContents = Lists.newArrayList(((ShulkerBox) ((BlockStateMeta) itemStackMeta).getBlockState()).getInventory().getContents());

                itemStackContents.removeIf(Objects::isNull);
                toCompareContents.removeIf(Objects::isNull);

                if (itemStackContents.isEmpty() != toCompareContents.isEmpty())
                    return false;

                for (ItemStack itm : toCompareContents) {
                    if (!itemStackContents.remove(itm))
                        return false;
                }

                if (!itemStackContents.isEmpty())
                    return false;

            } catch (ClassCastException ex) {
                return false;
            }
        }

        // If compareBundleInventory is on and version is above 1.17 also check Bundles
        if (new Utils().plugin.getVersion().isAtLeast(1, 17) &&
                itemStack.getType().equals(Material.BUNDLE) &&
                getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BUNDLE_INVENTORY)) {
            try {
                ArrayList<ItemStack> itemStackContents = Lists.newArrayList(((BundleMeta) toCompareMeta).getItems()),
                        toCompareContents = Lists.newArrayList(((BundleMeta) itemStackMeta).getItems());

                itemStackContents.removeIf(Objects::isNull);
                toCompareContents.removeIf(Objects::isNull);

                if (itemStackContents.isEmpty() != toCompareContents.isEmpty())
                    return false;

                for (ItemStack itm : toCompareContents) {
                    if (!itemStackContents.remove(itm))
                        return false;
                }

                if (!itemStackContents.isEmpty())
                    return false;

            } catch (ClassCastException ex) {
                return false;
            }
        }

        // If compareDurability is on
        int compareDurability = getShopSettingAsInteger(ShopItemStackSettingKeys.COMPARE_DURABILITY);
        if (compareDurability > -1 && compareDurability < 3 && useMeta) {

            // Return False if Damageable is not equal (one has and one doesn't)
            if (itemStackMeta instanceof Damageable != toCompareMeta instanceof Damageable) {
                debugger.log("toCompareMeta isDamageable: " + (itemStackMeta instanceof Damageable), DebugLevels.ITEM_COMPARE);
                debugger.log("toCompareMeta isDamageable: " + (toCompareMeta instanceof Damageable), DebugLevels.ITEM_COMPARE);
                return false;
            }

            if (itemStackMeta instanceof Damageable) {

                Damageable itemStackDamageable = (Damageable) itemStackMeta, toCompareDamageable = (Damageable) toCompareMeta;

                // Return False compareDurability is set to '==' and ItemStack Damage is not equal
                if (compareDurability == 1 && itemStackDamageable.getDamage() != toCompareDamageable.getDamage()) {
                    debugger.log("itemstack Durabilty (==): " + itemStackDamageable.getDamage(), DebugLevels.ITEM_COMPARE);
                    debugger.log("toCompare Durabilty (==): " + toCompareDamageable.getDamage(), DebugLevels.ITEM_COMPARE);
                    return false;
                }

                // Return False compareDurability is set to '<=' and ItemStack Damage less than toCompare Damage
                if (compareDurability == 0 && itemStackDamageable.getDamage() > toCompareDamageable.getDamage()) {
                    debugger.log("itemstack Durabilty (<=): " + itemStackDamageable.getDamage(), DebugLevels.ITEM_COMPARE);
                    debugger.log("toCompare Durabilty (<=): " + toCompareDamageable.getDamage(), DebugLevels.ITEM_COMPARE);
                    return false;
                }

                // Return False compareDurability is set to '>=' and ItemStack Damage greater than toCompare Damage
                if (compareDurability == 2 && itemStackDamageable.getDamage() < toCompareDamageable.getDamage()) {
                    debugger.log("itemstack Durabilty (>=): " + itemStackDamageable.getDamage(), DebugLevels.ITEM_COMPARE);
                    debugger.log("toCompare Durabilty (>=): " + toCompareDamageable.getDamage(), DebugLevels.ITEM_COMPARE);
                    return false;
                }
            }

        }

        // If compareEnchantments is on
        if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ENCHANTMENTS) && useMeta) {
            if (itemStackMeta instanceof EnchantmentStorageMeta && toCompareMeta instanceof EnchantmentStorageMeta) {
                EnchantmentStorageMeta itemStackEnchantmentStorageMeta = (EnchantmentStorageMeta) itemStackMeta,
                        toCompareEnchantmentStorageMeta = (EnchantmentStorageMeta) toCompareMeta;

                debugger.log("itemStackEnchantmentStorageMeta Enchants: " + itemStackEnchantmentStorageMeta.getStoredEnchants(), DebugLevels.ENCHANT_CHECKS);
                debugger.log("toCompareEnchantmentStorageMeta Enchants: " + toCompareEnchantmentStorageMeta.getStoredEnchants(), DebugLevels.ENCHANT_CHECKS);

                // Return False if hasEnchantments differs (one has one doesn't)
                if (itemStackEnchantmentStorageMeta.hasStoredEnchants() != toCompareEnchantmentStorageMeta.hasStoredEnchants())
                    return false;

                // Return False if itemStack hasEnchantments && Enchant maps are not equal
                if (itemStackEnchantmentStorageMeta.hasStoredEnchants() && !itemStackEnchantmentStorageMeta.getStoredEnchants().equals(toCompareEnchantmentStorageMeta.getStoredEnchants()))
                    return false;
            } else {

                // Return False if hasEnchantments differs (one has one doesn't)
                if (itemStackMeta.hasEnchants() != toCompareMeta.hasEnchants()) {
                    debugger.log("itemStackMeta hasEnchants: " + itemStackMeta.hasEnchants(), DebugLevels.ITEM_COMPARE);
                    debugger.log("toCompareMeta hasEnchants: " + toCompareMeta.hasEnchants(), DebugLevels.ITEM_COMPARE);
                    return false;
                }

                // Return False if itemStack hasEnchantments && Enchant maps are not equal
                if (itemStackMeta.hasEnchants() && !itemStackMeta.getEnchants().equals(toCompareMeta.getEnchants()))
                    return false;
            }
        }

        // If compareName is on
        if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_NAME)) {
            debugger.log("ShopItemStack > isSimilar > getDisplayName: " + itemStackMeta.getDisplayName() + " - " + toCompareMeta.getDisplayName(), DebugLevels.NAME_COMPARE);

            // If ItemStack Meta are BookMeta then compare title, otherwise compare displayname
            if (useBookMeta) {
                // Return False if hasTitle differs (one has one doesn't)
                if (itemStackBookMeta.hasTitle() != toCompareBookMeta.hasTitle()) return false;

                // Return False if itemStack hasTitle && Title is not equal
                if (itemStackBookMeta.hasTitle() && !Objects.equals(itemStackBookMeta.getTitle(), toCompareBookMeta.getTitle()))
                    return false;
            } else {
                // Return False if hasDisplayName differs (one has one doesn't)
                if (itemStackMeta.hasDisplayName() != toCompareMeta.hasDisplayName()) return false;

                // Return False if itemStack hasDisplayName && DisplayName is not equal
                if (itemStackMeta.hasDisplayName() && !itemStackMeta.getDisplayName().equals(toCompareMeta.getDisplayName()))
                    return false;
            }
        }

        // If useBookMeta and compareBookAuthor are true
        if (useBookMeta && getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BOOK_AUTHOR)) {
            // Return False if hasAuthor differs (one has one doesn't)
            debugger.log("itemStackBookMeta hasAuthor: " + itemStackBookMeta.hasAuthor(), DebugLevels.ITEM_COMPARE);
            debugger.log("toCompareBookMeta hasAuthor: " + toCompareBookMeta.hasAuthor(), DebugLevels.ITEM_COMPARE);
            if (itemStackBookMeta.hasAuthor() != toCompareBookMeta.hasAuthor()) {
                return false;
            }

            // Return False if itemStack hasAuthor && Author is not equal
            debugger.log("itemStackBookMeta getAuthor: " + itemStackBookMeta.getAuthor(), DebugLevels.ITEM_COMPARE);
            debugger.log("toCompareBookMeta getAuthor: " + toCompareBookMeta.getAuthor(), DebugLevels.ITEM_COMPARE);
            if (itemStackBookMeta.hasAuthor() && !Objects.equals(itemStackBookMeta.getAuthor(), toCompareBookMeta.getAuthor())) {
                return false;
            }
        }

        // If useBookMeta and compareBookPages are true
        if (useBookMeta && getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_BOOK_PAGES)) {
            // Return False if hasPages differs (one has one doesn't)
            debugger.log("itemStackBookMeta hasPages: " + itemStackBookMeta.hasPages(), DebugLevels.ITEM_COMPARE);
            debugger.log("toCompareBookMeta hasPages: " + toCompareBookMeta.hasPages(), DebugLevels.ITEM_COMPARE);
            if (itemStackBookMeta.hasPages() != toCompareBookMeta.hasPages()) {
                return false;
            }

            // Return False if itemStack hasPages && Pages is not equal
            debugger.log("itemStackBookMeta isNull: " + itemStackBookMeta.getPages(), DebugLevels.ITEM_COMPARE);
            debugger.log("toCompareBookMeta isNull: " + toCompareBookMeta.getPages(), DebugLevels.ITEM_COMPARE);
            if (itemStackBookMeta.hasPages() && !Objects.equals(itemStackBookMeta.getPages(), toCompareBookMeta.getPages())) {
                return false;
            }
        }

        // If compareLore is on
        if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_LORE) && useMeta) {
            // Return False if hasLore differs (one has one doesn't)
            if (itemStackMeta.hasLore() != toCompareMeta.hasLore()) return false;

            // Return False if itemStack hasLore && Lore is not equal
            if (itemStackMeta.hasLore() && !Objects.equals(itemStackMeta.getLore(), toCompareMeta.getLore()))
                return false;
        }

        // If compareCustomModelData is on
        if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_CUSTOM_MODEL_DATA) && useMeta) {
            // Return False if hasCustomModelData differs (one has one doesn't)
            if (itemStackMeta.hasCustomModelData() != toCompareMeta.hasCustomModelData()) return false;

            // Return False if itemStack hasCustomModelData && Custom Model Data is not equal
            if (itemStackMeta.hasCustomModelData() && itemStackMeta.getCustomModelData() != toCompareMeta.getCustomModelData())
                return false;
        }

        // If compareItemFlags is on
        if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ITEM_FLAGS) && useMeta) {
            // Return False if getItemFlags sizes differs
            if (itemStackMeta.getItemFlags().size() != toCompareMeta.getItemFlags().size()) return false;

            // Return False if Lore is not equal
            if (!itemStackMeta.getItemFlags().equals(toCompareMeta.getItemFlags())) return false;
        }

        // Return False if compareUnbreakable is on and isUnbreakable differs
        if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_UNBREAKABLE) && useMeta && itemStackMeta.isUnbreakable() != toCompareMeta.isUnbreakable())
            return false;

        // If item is firework rocket
        if (itemStack.getType() == Material.FIREWORK_ROCKET) {
            FireworkMeta fireworkMeta = (FireworkMeta) itemStackMeta;
            FireworkMeta toCompareFireworkMeta = (FireworkMeta) toCompareMeta;

            // If server compare firework duration is disabled local setting is ignores
            if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_FIREWORK_DURATION)) {
                if (fireworkMeta.getPower() != toCompareFireworkMeta.getPower()) {
                    return false;
                }
            }

            if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_FIREWORK_EFFECTS)) {
                if (fireworkMeta.hasEffects()) {
                    if (fireworkMeta.getEffects().size() != toCompareFireworkMeta.getEffects().size()) {
                        return false;
                    }

                    for (int i = 0; i < fireworkMeta.getEffects().size(); ++i) {
                        FireworkEffect effect = fireworkMeta.getEffects().get(i);
                        FireworkEffect effectCompare = toCompareFireworkMeta.getEffects().get(i);
                        if (!effect.equals(effectCompare)) {
                            return false;
                        }
                    }
                }
            }
        }

        // If compareAttributeModifier is on
        if (getShopSettingAsBoolean(ShopItemStackSettingKeys.COMPARE_ATTRIBUTE_MODIFIER) && useMeta) {
            if (itemStackMeta.hasAttributeModifiers() != toCompareMeta.hasAttributeModifiers()) return false;

            // Return False if itemStack hasAttributeModifiers && getAttributeModifiers are not equal
            return !itemStackMeta.hasAttributeModifiers() || Objects.equals(itemStackMeta.getAttributeModifiers(), toCompareMeta.getAttributeModifiers());
        }

        return true;
    }

    public ItemStack getItemStack() {
        if (itemStack == null)
            fromBase64();
        return itemStack;
    }

    public String getItemName() {
        return itemStack.hasItemMeta() && itemStack.getItemMeta().hasDisplayName() ?
                itemStack.getItemMeta().getDisplayName() :
                itemStack.getType().toString();
    }

    public String serialize() {
        return new Gson().toJson(this);
    }

    /**
     *
     * Original code from https://gist.github.com/graywolf336/8153678
     * Tweaked for use with single itemstacks
     *
     */

    /**
     * Sets the objects Base64 from its {@link ItemStack}
     */
    private void toBase64() {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);

            // Save every element in the list
            dataOutput.writeObject(itemStack);

            // Serialize that array
            dataOutput.close();
            itemStackB64 = Base64Coder.encodeLines(outputStream.toByteArray());
        } catch (IOException e) {
            itemStackB64 = null;
        }
    }

    /**
     * Sets the objects {@link ItemStack} from its Base64.
     */
    private void fromBase64() {
        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(itemStackB64));
            BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);

            // Read the serialized inventory
            itemStack = new ItemStack((ItemStack) dataInput.readObject());

            dataInput.close();
        } catch (ClassNotFoundException | IOException e) {
            itemStack = null;
        }
    }

    public String toConsoleText() {
        return new GsonBuilder().setPrettyPrinting().create().toJson(this);
    }

}


text:
import json
import pygame

class AssetManager:
    'Use this to get all of the resources'
    asset_dictionary = {}
    json_dict = {}

    def __init__(self):
        if len(AssetManager.json_dict) == 0:
            asset_file = open("assets/asset_map.json")
            file_text = asset_file.read()
            AssetManager.json_dict = json.loads(file_text)

    def request_texture(self, name):
        'Get a texture surface with specified name'
        texture_key = "Texture_" + name
        if AssetManager.asset_dictionary.get(texture_key) is None:
            textures_array = AssetManager.json_dict['textures']
            for texture in textures_array:
                if texture['name'] == name:
                    main_surface = pygame.image.load(texture['filename'])
                    origin_json = texture['origin']
                    dimension_json = texture['dimensions']
                    origin = (origin_json['x'], origin_json['y'])
                    dimensions = (dimension_json['w'], dimension_json['h'])
                    AssetManager.asset_dictionary[texture_key] = main_surface.subsurface(pygame.Rect(origin, dimensions))
                    return AssetManager.asset_dictionary[texture_key]
        else:
            return AssetManager.asset_dictionary.get(texture_key)
        print("No such texture with name: {}".format(name))

    def request_sound(self, name):
        'Get a mixer sound with specified name'
        sound_key = "Sound_" + name
        if AssetManager.asset_dictionary.get(sound_key) is None:
            sound_array = AssetManager.json_dict['sound']
            for sound in sound_array:
                if sound['name'] == name:
                    AssetManager.asset_dictionary[sound_key] = pygame.mixer.Sound(sound['filename'])
                    return AssetManager.asset_dictionary[sound_key]
        else:
            return AssetManager.asset_dictionary.get(sound_key)
        print("No such sound with name: {}".format(name))

    def load_song(self, name):
        'Loads song with specified name into pygame.mixer.music, does not start playback'
        song_key = "Song_" + name
        if AssetManager.asset_dictionary.get(song_key) is None:
            song_array = AssetManager.json_dict['song']
            for song in song_array:
                if song['name'] == name:
                    AssetManager.asset_dictionary[song_key] = song['filename']
        if AssetManager.asset_dictionary.get(song_key) is not None:
            pygame.mixer.music.load(AssetManager.asset_dictionary[song_key])
            pygame.mixer.music.play(-1)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Composition;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace StackPanelUWPApp1
{
    public static class FrameworkElementExtensions
    {
        public static T TraverseCTFindShape<T>(DependencyObject root, String name) where T : Windows.UI.Xaml.Shapes.Shape
        {
            T control = null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
            {
                var child = VisualTreeHelper.GetChild(root, i);

                string childName = child.GetValue(FrameworkElement.NameProperty) as string;
                control = child as T;

                if (childName == name)
                {
                    return control;
                }
                else
                {
                    control = TraverseCTFindShape<T>(child, name);

                    if (control != null)
                    {
                        return control;
                    }
                }
            }

            return control;
        }
    }
}


text:
timeline_loaded = false;
timeline_vm_address = undefined;
timeline_isolates = undefined;

function registerForMessages() {
  window.addEventListener("message", onMessage, false);
  window.addEventListener("hashchange", onHashChange, false);
}

registerForMessages();

function onMessage(event) {
  var request = JSON.parse(event.data);
  var method = request['method'];
  var params = request['params'];
  console.log('method: ' + method)
  switch (method) {
    case 'loading':
      showLoadingOverlay('Fetching timeline...');
    break;
    case 'refresh':
      timeline_vm_address = params['vmAddress'];
      timeline_isolates = params['isolateIds'];
      if (typeof fetchTimeline === "undefined") {
        console.log('Delaying timeline refresh until loaded.');
      } else {
        fetchTimeline(timeline_vm_address, timeline_isolates);
      }
    break;
    case 'clear':
      clearTimeline();
    break;
    case 'save':
      saveTimeline();
    break;
    case 'load':
      loadTimeline();
    break;
    default:
      console.log('Unknown method:' + method + '.');
  }
}

function onHashChange() {
  refreshTimeline();
}

console.log('message handler registered');


text:
[Presentation](https://andifalk.github.io/cf-summit-2017/presentation/index.html) and demos for
[Manage Distributed Secrets in Applications on Cloud Foundry With Spring Cloud Vault](https://cfeu17.sched.com/event/Bity) at
[CloudFoundry Summit Europe 2017](https://www.cloudfoundry.org/event/europe-2017).

## Presentation

The presentation for this session can be found [here](https://andifalk.github.io/cf-summit-2017/presentation/index.html).

## Spring Vault Demo

This demonstrates the usage of the _transit_ secret backend of vault in a typical spring boot based web application with JPA.
In this sample sensible data like social security and credit card numbers are encrypted before storing in the database and
decrypted before returning these to the rest api.

## Spring Cloud Config Vault Server

This demo implements a spring cloud config server both providing access to a...

* ...Git repository for all configuration properties that are not sensible
* ...Vault secret store for all sensible configuration data

## Spring Cloud Config Vault Client

This demo implements a spring cloud config client connecting to the corresponding
demo server and reads two configuration properties, one from git repo and one from vault.


text:
#include "libavutil/common.h"
#include "libavutil/libm.h"
#include "libavutil/log.h"
#include "internal.h"
#include "resample.h"
#include "audio_data.h"

struct ResampleContext {
    AVAudioResampleContext *avr;
    AudioData *buffer;
    uint8_t *filter_bank;
    int filter_length;
    int ideal_dst_incr;
    int dst_incr;
    int index;
    int frac;
    int src_incr;
    int compensation_distance;
    int phase_shift;
    int phase_mask;
    int linear;
    enum AVResampleFilterType filter_type;
    int kaiser_beta;
    double factor;
    void (*set_filter)(void *filter, double *tab, int phase, int tap_count);
    void (*resample_one)(struct ResampleContext *c, int no_filter, void *dst0,
                         int dst_index, const void *src0, int src_size,
                         int index, int frac);
};

/* double template */
#define CONFIG_RESAMPLE_DBL
#include "resample_template.c"
#undef CONFIG_RESAMPLE_DBL

/* float template */
#define CONFIG_RESAMPLE_FLT
#include "resample_template.c"
#undef CONFIG_RESAMPLE_FLT

/* s32 template */
#define CONFIG_RESAMPLE_S32
#include "resample_template.c"
#undef CONFIG_RESAMPLE_S32

/* s16 template */
#include "resample_template.c"

/* 0th order modified bessel function of the first kind. */
static double bessel(double x)
{
    double v     = 1;
    double lastv = 0;
    double t     = 1;
    int i;

    x = x * x / 4;
    for (i = 1; v != lastv; i++) {
        lastv = v;
        t    *= x / (i * i);
        v    += t;
    }
    return v;
}

/* Build a polyphase filterbank. */
static int build_filter(ResampleContext *c)
{
    int ph, i;
    double x, y, w, factor;
    double *tab;
    int tap_count    = c->filter_length;
    int phase_count  = 1 << c->phase_shift;
    const int center = (tap_count - 1) / 2;

    tab = av_malloc(tap_count * sizeof(*tab));
    if (!tab)
        return AVERROR(ENOMEM);

    /* if upsampling, only need to interpolate, no filter */
    factor = FFMIN(c->factor, 1.0);

    for (ph = 0; ph < phase_count; ph++) {
        double norm = 0;
        for (i = 0; i < tap_count; i++) {
            x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;
            if (x == 0) y = 1.0;
            else        y = sin(x) / x;
            switch (c->filter_type) {
            case AV_RESAMPLE_FILTER_TYPE_CUBIC: {
                const float d = -0.5; //first order derivative = -0.5
                x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);
                if (x < 1.0) y = 1 - 3 * x*x + 2 * x*x*x + d * (                -x*x + x*x*x);
                else         y =                           d * (-4 + 8 * x - 5 * x*x + x*x*x);
                break;
            }
            case AV_RESAMPLE_FILTER_TYPE_BLACKMAN_NUTTALL:
                w  = 2.0 * x / (factor * tap_count) + M_PI;
                y *= 0.3635819 - 0.4891775 * cos(    w) +
                                 0.1365995 * cos(2 * w) -
                                 0.0106411 * cos(3 * w);
                break;
            case AV_RESAMPLE_FILTER_TYPE_KAISER:
                w  = 2.0 * x / (factor * tap_count * M_PI);
                y *= bessel(c->kaiser_beta * sqrt(FFMAX(1 - w * w, 0)));
                break;
            }

            tab[i] = y;
            norm  += y;
        }
        /* normalize so that an uniform color remains the same */
        for (i = 0; i < tap_count; i++)
            tab[i] = tab[i] / norm;

        c->set_filter(c->filter_bank, tab, ph, tap_count);
    }

    av_free(tab);
    return 0;
}

ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)
{
    ResampleContext *c;
    int out_rate    = avr->out_sample_rate;
    int in_rate     = avr->in_sample_rate;
    double factor   = FFMIN(out_rate * avr->cutoff / in_rate, 1.0);
    int phase_count = 1 << avr->phase_shift;
    int felem_size;

    if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P &&
        avr->internal_sample_fmt != AV_SAMPLE_FMT_S32P &&
        avr->internal_sample_fmt != AV_SAMPLE_FMT_FLTP &&
        avr->internal_sample_fmt != AV_SAMPLE_FMT_DBLP) {
        av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "
               "resampling: %s\n",
               av_get_sample_fmt_name(avr->internal_sample_fmt));
        return NULL;
    }
    c = av_mallocz(sizeof(*c));
    if (!c)
        return NULL;

    c->avr           = avr;
    c->phase_shift   = avr->phase_shift;
    c->phase_mask    = phase_count - 1;
    c->linear        = avr->linear_interp;
    c->factor        = factor;
    c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);
    c->filter_type   = avr->filter_type;
    c->kaiser_beta   = avr->kaiser_beta;

    switch (avr->internal_sample_fmt) {
    case AV_SAMPLE_FMT_DBLP:
        c->resample_one  = resample_one_dbl;
        c->set_filter    = set_filter_dbl;
        break;
    case AV_SAMPLE_FMT_FLTP:
        c->resample_one  = resample_one_flt;
        c->set_filter    = set_filter_flt;
        break;
    case AV_SAMPLE_FMT_S32P:
        c->resample_one  = resample_one_s32;
        c->set_filter    = set_filter_s32;
        break;
    case AV_SAMPLE_FMT_S16P:
        c->resample_one  = resample_one_s16;
        c->set_filter    = set_filter_s16;
        break;
    }

    felem_size = av_get_bytes_per_sample(avr->internal_sample_fmt);
    c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * felem_size);
    if (!c->filter_bank)
        goto error;

    if (build_filter(c) < 0)
        goto error;

    memcpy(&c->filter_bank[(c->filter_length * phase_count + 1) * felem_size],
           c->filter_bank, (c->filter_length - 1) * felem_size);
    memcpy(&c->filter_bank[c->filter_length * phase_count * felem_size],
           &c->filter_bank[(c->filter_length - 1) * felem_size], felem_size);

    c->compensation_distance = 0;
    if (!av_reduce(&c->src_incr, &c->dst_incr, out_rate,
                   in_rate * (int64_t)phase_count, INT32_MAX / 2))
        goto error;
    c->ideal_dst_incr = c->dst_incr;

    c->index = -phase_count * ((c->filter_length - 1) / 2);
    c->frac  = 0;

    /* allocate internal buffer */
    c->buffer = ff_audio_data_alloc(avr->resample_channels, 0,
                                    avr->internal_sample_fmt,
                                    "resample buffer");
    if (!c->buffer)
        goto error;

    av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",
           av_get_sample_fmt_name(avr->internal_sample_fmt),
           avr->in_sample_rate, avr->out_sample_rate);

    return c;

error:
    ff_audio_data_free(&c->buffer);
    av_free(c->filter_bank);
    av_free(c);
    return NULL;
}

void ff_audio_resample_free(ResampleContext **c)
{
    if (!*c)
        return;
    ff_audio_data_free(&(*c)->buffer);
    av_free((*c)->filter_bank);
    av_freep(c);
}

int avresample_set_compensation(AVAudioResampleContext *avr, int sample_delta,
                                int compensation_distance)
{
    ResampleContext *c;
    AudioData *fifo_buf = NULL;
    int ret = 0;

    if (compensation_distance < 0)
        return AVERROR(EINVAL);
    if (!compensation_distance && sample_delta)
        return AVERROR(EINVAL);

    if (!avr->resample_needed) {
#if FF_API_RESAMPLE_CLOSE_OPEN
        /* if resampling was not enabled previously, re-initialize the
           AVAudioResampleContext and force resampling */
        int fifo_samples;
        int restore_matrix = 0;
        double matrix[AVRESAMPLE_MAX_CHANNELS * AVRESAMPLE_MAX_CHANNELS] = { 0 };

        /* buffer any remaining samples in the output FIFO before closing */
        fifo_samples = av_audio_fifo_size(avr->out_fifo);
        if (fifo_samples > 0) {
            fifo_buf = ff_audio_data_alloc(avr->out_channels, fifo_samples,
                                           avr->out_sample_fmt, NULL);
            if (!fifo_buf)
                return AVERROR(EINVAL);
            ret = ff_audio_data_read_from_fifo(avr->out_fifo, fifo_buf,
                                               fifo_samples);
            if (ret < 0)
                goto reinit_fail;
        }
        /* save the channel mixing matrix */
        if (avr->am) {
            ret = avresample_get_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
            if (ret < 0)
                goto reinit_fail;
            restore_matrix = 1;
        }

        /* close the AVAudioResampleContext */
        avresample_close(avr);

        avr->force_resampling = 1;

        /* restore the channel mixing matrix */
        if (restore_matrix) {
            ret = avresample_set_matrix(avr, matrix, AVRESAMPLE_MAX_CHANNELS);
            if (ret < 0)
                goto reinit_fail;
        }

        /* re-open the AVAudioResampleContext */
        ret = avresample_open(avr);
        if (ret < 0)
            goto reinit_fail;

        /* restore buffered samples to the output FIFO */
        if (fifo_samples > 0) {
            ret = ff_audio_data_add_to_fifo(avr->out_fifo, fifo_buf, 0,
                                            fifo_samples);
            if (ret < 0)
                goto reinit_fail;
            ff_audio_data_free(&fifo_buf);
        }
#else
        av_log(avr, AV_LOG_ERROR, "Unable to set resampling compensation\n");
        return AVERROR(EINVAL);
#endif
    }
    c = avr->resample;
    c->compensation_distance = compensation_distance;
    if (compensation_distance) {
        c->dst_incr = c->ideal_dst_incr - c->ideal_dst_incr *
                      (int64_t)sample_delta / compensation_distance;
    } else {
        c->dst_incr = c->ideal_dst_incr;
    }
    return 0;

reinit_fail:
    ff_audio_data_free(&fifo_buf);
    return ret;
}

static int resample(ResampleContext *c, void *dst, const void *src,
                    int *consumed, int src_size, int dst_size, int update_ctx)
{
    int dst_index;
    int index         = c->index;
    int frac          = c->frac;
    int dst_incr_frac = c->dst_incr % c->src_incr;
    int dst_incr      = c->dst_incr / c->src_incr;
    int compensation_distance = c->compensation_distance;

    if (!dst != !src)
        return AVERROR(EINVAL);

    if (compensation_distance == 0 && c->filter_length == 1 &&
        c->phase_shift == 0) {
        int64_t index2 = ((int64_t)index) << 32;
        int64_t incr   = (1LL << 32) * c->dst_incr / c->src_incr;
        dst_size       = FFMIN(dst_size,
                               (src_size-1-index) * (int64_t)c->src_incr /
                               c->dst_incr);

        if (dst) {
            for(dst_index = 0; dst_index < dst_size; dst_index++) {
                c->resample_one(c, 1, dst, dst_index, src, 0, index2 >> 32, 0);
                index2 += incr;
            }
        } else {
            dst_index = dst_size;
        }
        index += dst_index * dst_incr;
        index += (frac + dst_index * (int64_t)dst_incr_frac) / c->src_incr;
        frac   = (frac + dst_index * (int64_t)dst_incr_frac) % c->src_incr;
    } else {
        for (dst_index = 0; dst_index < dst_size; dst_index++) {
            int sample_index = index >> c->phase_shift;

            if (sample_index + c->filter_length > src_size ||
                -sample_index >= src_size)
                break;

            if (dst)
                c->resample_one(c, 0, dst, dst_index, src, src_size, index, frac);

            frac  += dst_incr_frac;
            index += dst_incr;
            if (frac >= c->src_incr) {
                frac -= c->src_incr;
                index++;
            }
            if (dst_index + 1 == compensation_distance) {
                compensation_distance = 0;
                dst_incr_frac = c->ideal_dst_incr % c->src_incr;
                dst_incr      = c->ideal_dst_incr / c->src_incr;
            }
        }
    }
    if (consumed)
        *consumed = FFMAX(index, 0) >> c->phase_shift;

    if (update_ctx) {
        if (index >= 0)
            index &= c->phase_mask;

        if (compensation_distance) {
            compensation_distance -= dst_index;
            if (compensation_distance <= 0)
                return AVERROR_BUG;
        }
        c->frac     = frac;
        c->index    = index;
        c->dst_incr = dst_incr_frac + c->src_incr*dst_incr;
        c->compensation_distance = compensation_distance;
    }

    return dst_index;
}

int ff_audio_resample(ResampleContext *c, AudioData *dst, AudioData *src)
{
    int ch, in_samples, in_leftover, consumed = 0, out_samples = 0;
    int ret = AVERROR(EINVAL);

    in_samples  = src ? src->nb_samples : 0;
    in_leftover = c->buffer->nb_samples;

    /* add input samples to the internal buffer */
    if (src) {
        ret = ff_audio_data_combine(c->buffer, in_leftover, src, 0, in_samples);
        if (ret < 0)
            return ret;
    } else if (!in_leftover) {
        /* no remaining samples to flush */
        return 0;
    } else {
        /* TODO: pad buffer to flush completely */
    }

    /* calculate output size and reallocate output buffer if needed */
    /* TODO: try to calculate this without the dummy resample() run */
    if (!dst->read_only && dst->allow_realloc) {
        out_samples = resample(c, NULL, NULL, NULL, c->buffer->nb_samples,
                               INT_MAX, 0);
        ret = ff_audio_data_realloc(dst, out_samples);
        if (ret < 0) {
            av_log(c->avr, AV_LOG_ERROR, "error reallocating output\n");
            return ret;
        }
    }

    /* resample each channel plane */
    for (ch = 0; ch < c->buffer->channels; ch++) {
        out_samples = resample(c, (void *)dst->data[ch],
                               (const void *)c->buffer->data[ch], &consumed,
                               c->buffer->nb_samples, dst->allocated_samples,
                               ch + 1 == c->buffer->channels);
    }
    if (out_samples < 0) {
        av_log(c->avr, AV_LOG_ERROR, "error during resampling\n");
        return out_samples;
    }

    /* drain consumed samples from the internal buffer */
    ff_audio_data_drain(c->buffer, consumed);

    av_dlog(c->avr, "resampled %d in + %d leftover to %d out + %d leftover\n",
            in_samples, in_leftover, out_samples, c->buffer->nb_samples);

    dst->nb_samples = out_samples;
    return 0;
}

int avresample_get_delay(AVAudioResampleContext *avr)
{
    if (!avr->resample_needed || !avr->resample)
        return 0;

    return avr->resample->buffer->nb_samples;
}


text:
namespace mojo {

class WindowManagerTestSuite : public base::TestSuite {
 public:
  WindowManagerTestSuite(int argc, char** argv) : TestSuite(argc, argv) {}
  virtual ~WindowManagerTestSuite() {}

 protected:
  virtual void Initialize() OVERRIDE {
#if defined(USE_X11)
    // Each test ends up creating a new thread for the native viewport service.
    // In other words we'll use X on different threads, so tell it that.
    gfx::InitializeThreadedX11();
#endif
    base::TestSuite::Initialize();
    gfx::GLSurface::InitializeOneOffForTests();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(WindowManagerTestSuite);
};

}  // namespace mojo

int main(int argc, char** argv) {
  mojo::WindowManagerTestSuite test_suite(argc, argv);

  return base::LaunchUnitTests(
      argc, argv, base::Bind(&TestSuite::Run, base::Unretained(&test_suite)));
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>reactive-plumber</artifactId>
        <groupId>li.chee.reactive.plumber</groupId>
        <version>0.25</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>reactive-plumber-test</artifactId>

    <dependencies>
        <dependency>
            <groupId>li.chee.reactive.plumber</groupId>
            <artifactId>reactive-plumber-core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>li.chee.reactive.plumber</groupId>
            <artifactId>reactive-plumber-reactor</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>io.javaslang</groupId>
            <artifactId>javaslang</artifactId>
            <version>2.0.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <exclusions>
                <exclusion>
                    <groupId>org.hamcrest</groupId>
                    <artifactId>hamcrest-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>org.bitstrings.test</groupId>
            <artifactId>junit-clptr</artifactId>
            <version>1.2.2</version>
        </dependency>
    </dependencies>
    <profiles>
        <profile>
            <id>graphs</id>
            <build>
                <defaultGoal>gplus:execute</defaultGoal>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.gmavenplus</groupId>
                        <artifactId>gmavenplus-plugin</artifactId>
                        <configuration>
                            <scripts>
                                <script><![CDATA[
                                    import li.chee.reactive.plumber.GraphGen
                                    GraphGen.generateGraphs("src/main/resources/examples/four", "Four", "target/apidocs/graphs")
                                ]]></script>
                            </scripts>
                        </configuration>
                        <dependencies>
                            <dependency>
                                <groupId>org.codehaus.groovy</groupId>
                                <artifactId>groovy</artifactId>
                                <version>3.0.11</version>
                                <scope>runtime</scope>
                            </dependency>
                            <dependency>
                                <groupId>org.codehaus.groovy</groupId>
                                <artifactId>groovy-ant</artifactId>
                                <version>3.0.11</version>
                                <scope>runtime</scope>
                            </dependency>
                        </dependencies>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Kárpát-Medence Üszöggombái 147 (1950)

#### Original name
Sorosporium holci-sorghi f. holci-sorghi (Rivolta) Moesz

### Remarks
null


text:
from collections import namedtuple
import unittest
import discord
from gather.discord_gather import DiscordGather, report
from .helper import async_test, get_mock_coro

class TestDiscordGather(unittest.TestCase):
    @async_test
    async def test_on_ready(self):
        gather = DiscordGather('token')
        gather.client = unittest.mock.Mock()
        gather.client.user.name = 'testuser'
        await gather.on_ready()
        self.assertEqual(gather.bot.username, 'testuser')

    @async_test
    async def test_on_member_update_player_goes_offline(self):
        gather = DiscordGather('token')
        gather.bot = unittest.mock.Mock()
        gather.bot.member_went_offline = get_mock_coro(True)
        before = unittest.mock.Mock()
        before.status = discord.Status.online
        after = unittest.mock.Mock()
        after.status = discord.Status.offline
        await gather.on_member_update(before, after)
        self.assertTrue(gather.bot.member_went_offline.called)

    @async_test
    async def test_on_member_update_player_goes_afk(self):
        gather = DiscordGather('token')
        gather.bot = unittest.mock.Mock()
        gather.bot.member_went_afk = get_mock_coro(True)
        before = unittest.mock.Mock()
        before.status = discord.Status.online
        after = unittest.mock.Mock()
        after.status = discord.Status.idle
        await gather.on_member_update(before, after)
        self.assertTrue(gather.bot.member_went_afk.called)

    def test_report(self):
        organiser = unittest.mock.Mock()
        MockChannel = namedtuple('Channel', ['server'])
        key = MockChannel('testserver')
        organiser.queues = {key: ['player1']}
        organiser.games_count = {key: 1}

        self.assertEqual("Report:\ntestserver-Channel(server='testserver'): 1 current players - 1 games to date", report(organiser))


text:
package org.wikiup.modules.jsp;

import org.apache.jasper.servlet.JspServlet;
import org.wikiup.core.bean.WikiupDynamicSingleton;
import org.wikiup.core.impl.iterable.BeanPropertyNames;
import org.wikiup.core.inf.ExpressionLanguage;
import org.wikiup.core.inf.Dictionary;
import org.wikiup.core.inf.Releasable;
import org.wikiup.core.inf.ext.Context;
import org.wikiup.core.util.Dictionaries;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.util.Iterator;

public class JspServletContainer extends WikiupDynamicSingleton<JspServletContainer> implements Context<Object, Object>, Iterable<String>, Releasable {
    private JspServlet jspServlet;
    private ServletConfig servletConfig;
    private ExpressionLanguage<Dictionary<?>, String> el;

    public void firstBuilt() {
    }

    public Object get(String name) {
        return Dictionaries.getBeanProperty(this, name);
    }

    public void set(String name, Object obj) {
        Dictionaries.setBeanProperty(this, name, obj);
    }

    public Iterator<String> iterator() {
        return new BeanPropertyNames(getClass(), true).iterator();
    }

    public JspServlet getJspServlet() {
        return jspServlet;
    }

    public ServletConfig getServletConfig() {
        return servletConfig;
    }

    public void setServletConfig(ServletConfig servletConfig) {
        this.servletConfig = servletConfig;
    }

    public void setJspServlet(JspServlet jspServlet) throws ServletException {
        this.jspServlet = jspServlet;
        this.jspServlet.init(servletConfig);
    }

    public ExpressionLanguage<Dictionary<?>, String> getEl() {
        return el;
    }

    public void setEl(ExpressionLanguage<Dictionary<?>, String> el) {
        this.el = el;
    }

    public void release() {
        if(jspServlet != null)
            jspServlet.destroy();
        jspServlet = null;
    }
}


text:
'use strict';

const _ = require('lodash');
const OGMNeo = require('./ogmneo');

/**
    * @class OGMNeoCypher

 */
class OGMNeoCypher {

    /**
        * Executes one or more cypher read statements in a transaction.
        *
        * @static
        * @param {string|array} statements - The cypher read statements to be executed.
        * @returns {Promise<object|Error>} - Execute cypher query and return a result if successfully completes or a neo4j error.
    */
    static transactionalRead(statements) {
        return new Promise((resolve, reject) => {
            if (!_validateStatements(statements)) {
                reject(new Error('Cypher statements must to be a string or a non empty string array'));
            } else {
                let session = OGMNeo.session();
                let readTxResultPromise = session.readTransaction((transaction) => {
                    if (isStatement(statements)) {
                        return transaction.run(statements);
                    } else {
                        return Promise.all(statements.map(statement => transaction.run(statement)));
                    }
                });
                readTxResultPromise.then((result) => {
                    session.close();
                    resolve(result);

                }).catch( (error) => {
                    reject(error);
                });

            }
        });
    }

    /**
        * Executes one or more cypher write statements in a transaction.
        *
        * @static
        * @param {string|array} statements - The cypher write statements to be executed.
        * @returns {Promise<object|Error>} - Execute cypher query and return a result if successfully completes or a neo4j error.
    */
    static transactionalWrite(statements) {
        return new Promise((resolve, reject) => {
            if (!_validateStatements(statements)) {
                reject(new Error('Cypher statements must to be a string or a non empty string array'));
            } else {
                let session = OGMNeo.session();
                let writeTxResultPromise = session.writeTransaction((transaction) => {
                    if (isStatement(statements)) {
                        return transaction.run(statements);
                    } else {
                        return Promise.all(statements.map(statement => transaction.run(statement)));
                    }
                });
                writeTxResultPromise.then((result) => {
                    session.close();
                    resolve(result);

                }).catch( (error) => {
                    reject(error);
                });
            }
        });
    }
}

function isStatement(s) {
    return _.isString(s) || Object.prototype.hasOwnProperty.call(s, 'text');
}

//Private validate statements
function _validateStatements(statements) {
    if (isStatement(statements)) {
        return true;
    } else if (_.isArray(statements)) {
        let filtered = statements.filter(statement => isStatement(statement));
        return !_.isEmpty(filtered);
    }
    return false;
}
module.exports = OGMNeoCypher;


text:
package org.wso2.carbon.webapp.authenticator.framework.authenticator;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;

import java.util.Properties;

public interface WebappAuthenticator {

    enum Status {
        SUCCESS, FAILURE, CONTINUE
    }

    void init();

    boolean canHandle(Request request);

    AuthenticationInfo authenticate(Request request, Response response);

    String getName();

    void setProperties(Properties properties);

    Properties getProperties();

    String getProperty(String name);

}


text:
import java.util.ArrayList;
import java.util.Comparator;

public class PriorityQueueImp<E> implements PriorityQueue<E> {
    private Heap<E> heap;

    PriorityQueueImp(Comparator<E> comparator) {
	this.heap = new HeapImp<E>(new ArrayList<E>(), comparator);
    }

    @Override
    public void push(E e) {
	heap.insert(e);
    }

    @Override
    public E pop() {
	return heap.extractMin();
    }

    public String toString() {
	return heap.toString();
    }

}


text:
module LightweightActivityHelper
  # include ReportService::Sender

  def toggle_all(label='all', id_prefix='details_')
    link_to_function("show/hide #{label}", "$('div[id^=#{id_prefix}]').toggle();")
  end

  def has_good_content(value)
    return false if value.nil?
    related = value.gsub(/(<([^>]+)>)/,'')
    return (!related.blank?)
  end

  # Try to find the most specific path for the passed in activity, and the current state
  # of the sequence_run, sequence, and run
  def runnable_activity_path(activity, opts ={})
    if @sequence && @sequence_run
      append_white_list_params sequence_activity_with_run_path(@sequence, activity, @sequence_run.run_for_activity(activity), opts)
    elsif @sequence
      append_white_list_params sequence_activity_path(@sequence, activity, opts)
    elsif @run && @run.activity == activity
      append_white_list_params activity_with_run_path(activity, @run, opts)
    else
      append_white_list_params activity_path(activity, opts)
    end
  end

  def runnable_summary_path(activity)
    ReportService::report_url(@run, activity, @sequence)
  end

  def runnable_single_page_activity_path(activity, opts={})
    if @sequence
      append_white_list_params sequence_activity_single_page_with_run_path(@sequence, @activity, @run.key, opts)
    else
      append_white_list_params activity_single_page_with_run_path(@activity, @run.key, opts)
    end
  end

  def activity_name_for_menu
    results = t("ACTIVITY")
    if @sequence
      results << " #{@activity.position(@sequence)}"
    end
    return "#{results}: #{@activity.name}"
  end

  def complete_badge_for(activity)
    return unless @sequence_run
    run = @sequence_run.run_for_activity(activity)
    if run.completed?
      return ribbon(t("COMPLETED"),"my-ribbon")
    end
  end

  def activity_player_conversion_url(resource)
    if resource.is_a? Sequence
      lara_resource = "#{api_v1_sequence_url(resource.id)}.json"
      resource_name = resource.title
    else
      lara_resource = "#{api_v1_activity_url(resource.id)}.json"
      resource_name = resource.name
    end

    uri = URI.parse(ENV['CONVERSION_SCRIPT_URL'])
    query = Rack::Utils.parse_query(uri.query)
    query["lara_resource"] = lara_resource
    query["resource_name"] = resource_name
    uri.query = Rack::Utils.build_query(query)
    return uri.to_s
  end

  def activity_preview_options(activity, page=nil)
    base_url = request.base_url

    activity_player_url = activity.activity_player_url(base_url, page: page)
    activity_player_te_url = activity.activity_player_url(base_url, page: page, mode: "teacher-edition")
    if page
      lara_runtime_url = preview_activity_page_path(activity, page)
      lara_runtime_te_url = preview_activity_page_path(activity, page, mode: "teacher-edition")
    else
      lara_runtime_url = preview_activity_path(activity)
      lara_runtime_te_url = preview_activity_path(activity, mode: "teacher-edition")
    end

    preview_options = {
                       'Select an option...' => '',
                       'Activity Player' => activity_player_url,
                       'Activity Player Teacher Edition' => activity_player_te_url
                      }

    if activity.runtime != "Activity Player"
      preview_options['LARA Runtime'] = lara_runtime_url
      preview_options['LARA Runtime Teacher Edition'] = lara_runtime_te_url
    end

    return preview_options
  end

  def activity_preview_url(activity, page=nil)
    if activity.runtime == "Activity Player"
      activity.activity_player_url(request.base_url, preview: true, page: page)
    else
      preview_activity_page_path(activity, page)
    end
  end

  def itsi_preview_url(activity)
    if activity.runtime == "Activity Player"
      preview_activity_url = activity.activity_player_url(request.base_url, preview: true)
    else
      preview_activity_url = preview_activity_path(activity)
    end
    return preview_activity_url
  end

  def runtime_url(activity)
    if activity.runtime == "Activity Player"
      view_activity_url = activity.activity_player_url(request.base_url, preview: true)
    else
      view_activity_url = activity_path(activity)
    end
    return view_activity_url
  end
end


text:
drop index idx_gateway_gateway_profile_id;
alter table gateway
    drop column gateway_profile_id;

drop index idx_gateway_profile_extra_channel_gw_profile_id;
drop table gateway_profile_extra_channel;

drop index idx_gateway_profile_updated_at;
drop index idx_gateway_profile_created_at;
drop table gateway_profile;


text:
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://www.knime.org/2008/09/XMLConfig" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.knime.org/2008/09/XMLConfig http://www.knime.org/XMLConfig_2008_09.xsd" key="settings.xml">
<entry key="node_file" type="xstring" value="settings.xml"/>
<config key="flow_stack">
<config key="Variable_0">
<entry key="type" type="xstring" value="variable"/>
<entry key="name" type="xstring" value="output_fn"/>
<entry key="class" type="xstring" value="STRING"/>
<entry key="value" type="xstring" value="/tmp/knime_align_it_pharma20685/knime_tc_dl2p9yvzgtfr/output.phar"/>
</config>
</config>
<config key="internal_node_subsettings">
<entry key="memory_policy" type="xstring" value="CacheSmallInMemory"/>
</config>
<config key="model">
<config key="FileExtension_Internals">
<entry key="SettingsModelID" type="xstring" value="SMID_string"/>
<entry key="EnabledStatus" type="xboolean" value="true"/>
</config>
<entry key="FileExtension" type="xstring" value=".phar"/>
<config key="FileName_Internals">
<entry key="SettingsModelID" type="xstring" value="SMID_string"/>
<entry key="EnabledStatus" type="xboolean" value="true"/>
</config>
<entry key="FileName" type="xstring" value="output"/>
<config key="BaseDir_Internals">
<entry key="SettingsModelID" type="xstring" value="SMID_string"/>
<entry key="EnabledStatus" type="xboolean" value="true"/>
</config>
<entry key="BaseDir" type="xstring" value="/tmp/knime_Workflow Manage10316/knime_tc_svz1frznfv1k"/>
<config key="previewArea_Internals">
<entry key="SettingsModelID" type="xstring" value="SMID_string"/>
<entry key="EnabledStatus" type="xboolean" value="true"/>
</config>
<entry key="previewArea" type="xstring" value="/tmp/knime_Workflow Manage10243/knime_tc_mlduvck66lin/input.sdf"/>
<config key="OutputFlowVarName_Internals">
<entry key="SettingsModelID" type="xstring" value="SMID_string"/>
<entry key="EnabledStatus" type="xboolean" value="true"/>
</config>
<entry key="OutputFlowVarName" type="xstring" value="output_fn"/>
<config key="OverwriteFlag_Internals">
<entry key="SettingsModelID" type="xstring" value="SMID_boolean"/>
<entry key="EnabledStatus" type="xboolean" value="true"/>
</config>
<entry key="OverwriteFlag" type="xboolean" value="false"/>
</config>
<config key="variables">
<config key="BaseDir">
<entry key="used_variable" type="xstring" value="temp_path"/>
<entry key="exposed_variable" type="xstring" isnull="true" value=""/>
</config>
</config>
<config key="nodeAnnotation">
<entry key="text" type="xstring" value="output.phar"/>
<entry key="bgcolor" type="xint" value="16777215"/>
<entry key="x-coordinate" type="xint" value="409"/>
<entry key="y-coordinate" type="xint" value="182"/>
<entry key="width" type="xint" value="115"/>
<entry key="height" type="xint" value="14"/>
<entry key="alignment" type="xstring" value="CENTER"/>
<entry key="borderSize" type="xint" value="0"/>
<entry key="borderColor" type="xint" value="16777215"/>
<entry key="defFontSize" type="xint" value="11"/>
<entry key="annotation-version" type="xint" value="20151123"/>
<config key="styles"/>
</config>
<entry key="customDescription" type="xstring" isnull="true" value=""/>
<entry key="state" type="xstring" value="IDLE"/>
<entry key="factory" type="xstring" value="org.knime.base.node.flowvariable.createfilename.CreateFilenameNodeFactory"/>
<entry key="node-name" type="xstring" value="Create File Name"/>
<entry key="node-bundle-name" type="xstring" value="KNIME Base Nodes"/>
<entry key="node-bundle-symbolic-name" type="xstring" value="org.knime.base"/>
<entry key="node-bundle-vendor" type="xstring" value="KNIME GmbH, Konstanz, Germany"/>
<entry key="node-bundle-version" type="xstring" value="3.3.2.v201704060940"/>
<entry key="node-feature-name" type="xstring" value="KNIME Core"/>
<entry key="node-feature-symbolic-name" type="xstring" value="org.knime.features.base.feature.group"/>
<entry key="node-feature-vendor" type="xstring" value="KNIME GmbH, Konstanz, Germany"/>
<entry key="node-feature-version" type="xstring" value="3.3.2.v201704061137"/>
<config key="factory_settings"/>
<entry key="name" type="xstring" value="Create File Name"/>
<entry key="hasContent" type="xboolean" value="false"/>
<entry key="isInactive" type="xboolean" value="false"/>
<config key="ports">
<config key="port_1">
<entry key="index" type="xint" value="1"/>
<entry key="port_dir_location" type="xstring" isnull="true" value=""/>
</config>
</config>
<config key="filestores">
<entry key="file_store_location" type="xstring" isnull="true" value=""/>
<entry key="file_store_id" type="xstring" isnull="true" value=""/>
</config>
</config>


text:
	<%= lblSelect %>:

		<form>
			<div class="media-type-wrapper <% if( ! hasMap ) { %> disabled <% } %>">

					<input type="radio" name="media-type" value="map"> <%= lblMap %>

					<input type="radio" name="media-type" value="image"> <%= lblImage %>

					<input type="radio" name="media-type" value="video"> <%= lblVideo %>

					<input type="radio" name="media-type" value="webpage"> <%= lblExternal %>

		</form>

		<div class="mainMediaTypeContainer mapMediaContainer <% if( ! hasMap ) { %> disabled <% } %>">


text:
import {expectTranslate} from './test_support';

// We want to ignore decorators on JS interop for now.
// These tests make sure we haven't accidentally left in historic code from
// ts2dart that export decorators.
describe('ignore decorators', () => {
  it('translates plain decorators', () => {
    expectTranslate('@A class X {}').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
}`);
  });
  it('ignore plain decorators applied to abstract classes', () => {
    expectTranslate('@A abstract class X {}').to.equal(`@JS()
abstract class X {
  // @Ignore
  X.fakeConstructor$();
}`);
  });
  it('translates arguments', () => {
    expectTranslate('@A(a, b) class X {}').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
}`);
  });
  it('translates const arguments', () => {
    expectTranslate('@A([1]) class X {}').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
}`);
    expectTranslate('@A({"a": 1}) class X {}').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
}`);
    expectTranslate('@A(new B()) class X {}').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
}`);
  });
  it('translates on functions', () => {
    expectTranslate('@A function f() {}').to.equal(`@JS()
external f();`);
  });
  it('translates on properties', () => {
    expectTranslate('class X { @A p; }').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
  external get p;
  external set p(v);
}`);
  });
  it('translates on parameters', () => {
    expectTranslate('function f (@A p) {}').to.equal(`@JS()
external f(p);`);
  });
  it('ignore special cases @CONST', () => {
    expectTranslate('@CONST class X {}').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
}`);
    expectTranslate('@CONST() class X {}').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
}`);
    expectTranslate(`@CONST class X {
                       x: number;
                       y;
                       constructor() { super(3); this.x = 1; this.y = 2; }
                     }`)
        .to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
  external num get x;
  external set x(num v);
  external get y;
  external set y(v);
  external factory X();
}`);

    // @CONST constructors.
    expectTranslate('@CONST class X { constructor() {} }').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
  external factory X();
}`);
    // For backwards-compatibility for traceur inputs (not valid TS input)
    expectTranslate('class X { @CONST constructor() {} }').to.equal(`@JS()
class X {
  // @Ignore
  X.fakeConstructor$();
  external factory X();
}`);

    // @CONST properties.
    expectTranslate('class Foo { @CONST() static foo = 1; }').to.equal(`@JS()
class Foo {
  // @Ignore
  Foo.fakeConstructor$();
  external static get foo;
  external static set foo(v);
}`);
  });
});


text:
var _ = require('lodash');

function API() {
  if (!(this instanceof API)) return new API();
  this.methods = [];
}

API.prototype.method = function(verb, name, fn) {
  if (_.isFunction(name)) {
    fn = name;
    name = verb;
    verb = 'post';
  }

  this.methods.push({
    name: name,
    verb: verb,
    fn: fn
  });
};

module.exports = API;


text:
package com.ibm.watson.developer_cloud.service

import com.ibm.watson.developer_cloud.utils._
import com.ibm.watson.developer_cloud.utils.VCAPServicesProtocol._
import org.apache.commons.codec.binary.Base64
import org.slf4j.LoggerFactory
import spray.json._
case class WatsonServiceConfig(username: String, password: String, endpoint: String)  {

  val logger = LoggerFactory.getLogger(classOf[WatsonServiceConfig])

  def apiKey : String = {
    "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes("ISO-8859-1"))
  }
  def host: String = {
    endpoint.split("://").tail.mkString.split("/").head
  }
}

abstract class ConfigFactory(serviceName: Option[String] = None) {
  def getConfigForServiceType(serviceType: String) : WatsonServiceConfig
}

class VCAPConfigFactory(serviceName: Option[String] = None) extends JsonConfigFactory(serviceName) {
  def getJsonConfigString : String = sys.env("VCAP_SERVICES")
}

case class LocalFileConfigFactory(filename: String, serviceName: Option[String] = None) extends JsonConfigFactory(serviceName) {
  def getJsonConfigString : String = scala.io.Source.fromURL(getClass.getResource(filename)).mkString
}

abstract class JsonConfigFactory(serviceName: Option[String] = None) extends ConfigFactory(serviceName) {
  def getJsonConfigString : String

  def getConfigForServiceType(serviceType: String): WatsonServiceConfig = {
    Validation.notEmpty(serviceType, "ServiceType cannot be empty")
    val vcapProperties: VCAPProperties = getJsonConfigString.parseJson.convertTo[VCAPProperties]
    val serviceProperties = serviceName match {
      case Some(s) if !s.isEmpty => vcapProperties.properties(serviceType).filter(_.name == s).head
      case _ => vcapProperties.properties(serviceType).head
    }
    val credentials = serviceProperties.credentials
    new WatsonServiceConfig(credentials.username, credentials.password, credentials.url)
  }
}

class ManualConfig(username: String, password: String, endpoint: String) extends ConfigFactory {
  override def getConfigForServiceType(serviceType: String): WatsonServiceConfig = new WatsonServiceConfig(username, password, endpoint)
}


text:
/**
 * Mnemonist TrieMap Typings
 * ==========================
 */
export default class TrieMap<K, V> implements Iterable<[K, V]> {

  // Members
  size: number;

  // Constructor
  constructor(Token?: new () => K);

  // Methods
  clear(): void;
  set(prefix: K, value: V): this;
  update(prefix: K, updateFunction: (oldValue: V | undefined) => V): this
  get(prefix: K): V;
  delete(prefix: K): boolean;
  has(prefix: K): boolean;
  find(prefix: K): Array<[K, V]>;
  values(): IterableIterator<V>;
  prefixes(): IterableIterator<K>;
  keys(): IterableIterator<K>;
  entries(): IterableIterator<[K, V]>;
  [Symbol.iterator](): IterableIterator<[K, V]>;
  inspect(): any;

  // Statics
  static from<I, J>(iterable: Iterable<[I, J]> | {[key: string]: J}): TrieMap<I, J>;
}


text:
public class ExAgenda {

	public static void main(String[] args) throws Exception {
		Agenda agenda = new Agenda();
		boolean x = true;

		while(x) {
			System.out.println("1 - insere na agenda");
			System.out.println("2 - remove da agenda");
			System.out.println("3 - imprime a agenda");
			System.out.println("4 - imprime dados da pessoa");
			System.out.println("Outro - Sair");
			switch(EntradaTeclado.leInt()) {
				case 1:  System.out.println("Digite nome, idade e altura: ");
						 agenda.armazenaPessoa(EntradaTeclado.leString(),EntradaTeclado.leInt(), (float)EntradaTeclado.leDouble());
						 break;
				case 2:  System.out.println("Digite o nome da pessoa que quer remover:");
						 agenda.removePessoa(EntradaTeclado.leString());
						 break;
				case 3:  agenda.imprimeAgenda();
						 break;
				case 4:  System.out.println("Digite o indice da pessoa q deseja mostrar:");
						 agenda.imprimePessoa(EntradaTeclado.leInt());
						 break;
				default: x = false;
						 break;
			}
		}

	}

}