text:
package net.dempsy.util.io;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 *

 * This is literally a copy of the {@link ByteArrayOutputStream} from the runtime library except it's been modified in the following ways:
 *

 *
 *

 *
All synchronization has been removed.

 *
The internal buffer's length is cached in a separate variable to avoid repeated dereferencing of the byte[] object

 *
You can access the underlying buffer directly using {@link MessageBufferOutput#getBuffer()}.

 *
Has a {@link #grow()} method to externally increase the internal buffer size.

 *
Has a {@link #replace(byte[])} method that will allow replacing the underlying buffer with a different one.

 *
Has a {@link #setPosition(int)} method that will set the current output position.

 *
The 'size' method is renamed to {@link MessageBufferOutput#getPosition()} for clarity.

 *

 *
 *

 * Remember, with great power comes great responsibility
 *

 *
 */
public class MessageBufferOutput extends OutputStream {
    /**
     * The buffer where data is stored.
     */
    protected byte buf[];

    /**
     * The number of valid bytes in the buffer.
     */
    protected int position;

    /**
     * This is a cache for the length of the underlying byte[] to avoid constant dereferencing.
     */
    protected int length;

    /**
     * Creates a new byte array output stream. The buffer capacity is initially 32 bytes, though its size increases if necessary.
     */
    public MessageBufferOutput() {
        this(32);
    }

    /**
     * Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.
     *
     * @param size
     *     the initial size.
     * @exception IllegalArgumentException
     *     if size is negative.
     */
    public MessageBufferOutput(final int size) {
        if(size < 0) {
            throw new IllegalArgumentException("Negative initial size: "
                + size);
        }
        buf = new byte[size];
        length = buf.length;
    }

    /**
     * Doubles the internal buffer size while preserving the data
     */
    public void grow() {
        buf = Arrays.copyOf(buf, length << 1);
        length = buf.length;
    }

    /**
     * Doubles the internal buffer size, or sets to the capacity provided if that's higher, while preserving the data
     */
    public void grow(final int newcap) {
        buf = Arrays.copyOf(buf, Math.max(length << 1, newcap));
        length = buf.length;
    }

    /**
     * Completely replace the underlying buffer.
     */
    public void replace(final byte[] buffer) {
        this.buf = buffer;
        this.length = buffer.length;
    }

    /**
     * Explicitly set the current position in the buffer.
     */
    public void setPosition(final int newPosition) {
        this.position = newPosition;
    }

    /**
     * Creates a newly allocated byte array. Its size is the current size of this output stream and the valid contents of the buffer have been copied into it.
     *
     * @return the current contents of this output stream, as a byte array.
     * @see java.io.ByteArrayOutputStream#size()
     */
    public synchronized byte toByteArray()[] {
        return Arrays.copyOf(buf, position);
    }

    /**
     * Writes the specified byte to this byte array output stream.
     *
     * @param b
     *     the byte to be written.
     */
    @Override
    public void write(final int b) {
        final int newcount = position + 1;
        if(newcount > length) {
            buf = Arrays.copyOf(buf, Math.max(length << 1, newcount));
            length = buf.length;
        }
        buf[position] = (byte)b;
        position = newcount;
    }

    /**
     * Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
     *
     * @param b
     *     the data.
     * @param off
     *     the start offset in the data.
     * @param len
     *     the number of bytes to write.
     */
    @Override
    public void write(final byte b[], final int off, final int len) {
        if((off < 0) || (off > b.length) || (len < 0) ||
            ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if(len == 0) {
            return;
        }
        final int newcount = position + len;
        if(newcount > length) {
            buf = Arrays.copyOf(buf, Math.max(length << 1, newcount));
            length = buf.length;
        }
        System.arraycopy(b, off, buf, position, len);
        position = newcount;
    }

    public void writeShort(final short x) {
        final int newcount = position + 2; // sizeof short in bytes
        if(newcount > length) {
            buf = Arrays.copyOf(buf, Math.max(length << 1, newcount));
            length = buf.length;
        }
        // standard java bigendian interpretation of a short
        buf[position++] = (byte)(x >> 8);
        buf[position++] = (byte)x;
    }

    /**
     * Writes an int to the underlying buffer as four
     * bytes, high byte first.
     */
    public void writeInt(final int v) throws IOException {
        final int newcount = position + 4; // sizeof int in bytes
        if(newcount > length) {
            buf = Arrays.copyOf(buf, Math.max(length << 1, newcount));
            length = buf.length;
        }
        buf[position++] = (byte)((v >>> 24) & 0xFF);
        buf[position++] = (byte)((v >>> 16) & 0xFF);
        buf[position++] = (byte)((v >>> 8) & 0xFF);
        buf[position++] = (byte)((v >>> 0) & 0xFF);
    }

    /**
     * Writes the complete contents of this byte array output stream to the specified output stream argument, as if by calling the output stream's write method
     * using out.write(buf, 0, count).
     *
     * @param out
     *     the output stream to which to write the data.
     * @exception IOException
     *     if an I/O error occurs.
     */
    public void writeTo(final OutputStream out) throws IOException {
        out.write(buf, 0, position);
    }

    /**
     * Resets the count field of this byte array output stream to zero, so that all currently accumulated output in the output stream is discarded.
     * The output stream can be used again, reusing the
     * already allocated buffer space.
     */
    public void reset() {
        position = 0;
    }

    /**
     * Returns the underlying byte[]
     *
     * @return the current contents of this output stream, as a byte array.
     */
    public byte getBuffer()[] {
        return buf;
    }

    /**
     * Returns the current position in the buffer where the next byte will be written to.
     *
     * @return the value of the count field, which is the number of valid bytes in this output stream.
     */
    public int getPosition() {
        return position;
    }

    /**
     * Converts the buffer's contents into a string decoding bytes using the platform's default character set. The length of the new {@code String} is a
     * function of the character set, and hence may not be
     * equal to the size of the buffer.
     *
     *

     * This method always replaces malformed-input and unmappable-character sequences with the default replacement string for the platform's default character
     * set. The
     * {@linkplain java.nio.charset.CharsetDecoder} class should be used when more control over the decoding process is required.
     *
     * @return String decoded from the buffer's contents.
     * @since JDK1.1
     */
    @Override
    public String toString() {
        return new String(buf, 0, position);
    }

    /**
     * Converts the buffer's contents into a string by decoding the bytes using the specified {@link java.nio.charset.Charset} name. The length of the new
     * {@code String} is a function of the charset, and hence
     * may not be equal to the length of the byte array.
     *
     *

     * This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement string. The
     * {@link java.nio.charset.CharsetDecoder} class should be used when more
     * control over the decoding process is required.
     *
     * @param charsetName
     *     the name of a supported {@linkplain java.nio.charset.Charset} charset
     * @return String decoded from the buffer's contents.
     * @exception UnsupportedEncodingException
     *     If the named charset is not supported
     * @since JDK1.1
     */
    public String toString(final String charsetName) throws UnsupportedEncodingException {
        return new String(buf, 0, position, charsetName);
    }

    /**
     * Closing a {@code ByteArrayOutputStream} has no effect. The methods in this class can be called after the stream has been closed without generating an
     * {@code IOException}.
     *

     *
     */
    @Override
    public void close() {}

}


text:
YahooMySQLImporter
==================

redpajama_set_name: RedPajamaGithub


text:
package ca.uhn.fhir.validation;

import java.io.InputStream;
import java.io.Reader;

import org.w3c.dom.ls.LSInput;

class LSInputImpl implements LSInput {

	private Reader myCharacterStream;
	private InputStream myByteStream;
	private String myStringData;
	private String mySystemId;
	private String myPublicId;
	private String myBaseURI;
	private String myEncoding;
	private boolean myCertifiedText;

	@Override
	public Reader getCharacterStream() {
		return myCharacterStream;
	}

	@Override
	public void setCharacterStream(Reader theCharacterStream) {
		myCharacterStream=theCharacterStream;
	}

	@Override
	public InputStream getByteStream() {
		return myByteStream;
	}

	@Override
	public void setByteStream(InputStream theByteStream) {
		myByteStream=theByteStream;
	}

	@Override
	public String getStringData() {
		return myStringData;
	}

	@Override
	public void setStringData(String theStringData) {
		myStringData=theStringData;
	}

	@Override
	public String getSystemId() {
		return mySystemId;
	}

	@Override
	public void setSystemId(String theSystemId) {
		mySystemId=theSystemId;
	}

	@Override
	public String getPublicId() {
		return myPublicId;
	}

	@Override
	public void setPublicId(String thePublicId) {
		myPublicId=thePublicId;
	}

	@Override
	public String getBaseURI() {
		return myBaseURI;
	}

	@Override
	public void setBaseURI(String theBaseURI) {
		myBaseURI=theBaseURI;
	}

	@Override
	public String getEncoding() {
		return myEncoding;
	}

	@Override
	public void setEncoding(String theEncoding) {
		myEncoding=theEncoding;
	}

	@Override
	public boolean getCertifiedText() {
		return myCertifiedText;
	}

	@Override
	public void setCertifiedText(boolean theCertifiedText) {
		myCertifiedText=theCertifiedText;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetLeft="7dp"
    android:insetRight="7dp"
    android:drawable="@drawable/rc_cs_group_list_divide_line">
</inset>


text:
from PyQt4.QtGui import QGraphicsView, QPainter

from ..scene import CanvasScene
from .. import items
from ... import scheme

from ...gui.test import QAppTestCase

class TestScene(QAppTestCase):
    def setUp(self):
        QAppTestCase.setUp(self)
        self.scene = CanvasScene()
        self.view = QGraphicsView(self.scene)
        self.view.setRenderHints(QPainter.Antialiasing | \
                                 QPainter.TextAntialiasing)
        self.view.show()
        self.view.resize(400, 300)

    def test_scene(self):
        """Test basic scene functionality.
        """
        file_desc, disc_desc, bayes_desc = self.widget_desc()

        file_item = items.NodeItem(file_desc)
        disc_item = items.NodeItem(disc_desc)
        bayes_item = items.NodeItem(bayes_desc)

        file_item = self.scene.add_node_item(file_item)
        disc_item = self.scene.add_node_item(disc_item)
        bayes_item = self.scene.add_node_item(bayes_item)

        # Remove a node
        self.scene.remove_node_item(bayes_item)
        self.assertSequenceEqual(self.scene.node_items(),
                                 [file_item, disc_item])

        # And add it again
        self.scene.add_node_item(bayes_item)
        self.assertSequenceEqual(self.scene.node_items(),
                                 [file_item, disc_item, bayes_item])

        # Adding the same item again should raise an exception
        with self.assertRaises(ValueError):
            self.scene.add_node_item(bayes_item)

        # Add links
        link1 = self.scene.new_link_item(file_item, "Data", disc_item, "Data")
        link2 = self.scene.new_link_item(disc_item, "Data", bayes_item, "Data")

        link1a = self.scene.add_link_item(link1)
        link2a = self.scene.add_link_item(link2)
        self.assertEqual(link1, link1a)
        self.assertEqual(link2, link2a)
        self.assertSequenceEqual(self.scene.link_items(), [link1, link2])

        # Remove links
        self.scene.remove_link_item(link2)
        self.scene.remove_link_item(link1)
        self.assertSequenceEqual(self.scene.link_items(), [])

        self.assertTrue(link1.sourceItem is None and link1.sinkItem is None)
        self.assertTrue(link2.sourceItem is None and link2.sinkItem is None)

        self.assertSequenceEqual(file_item.outputAnchors(), [])
        self.assertSequenceEqual(disc_item.inputAnchors(), [])
        self.assertSequenceEqual(disc_item.outputAnchors(), [])
        self.assertSequenceEqual(bayes_item.outputAnchors(), [])

        # And add one link again
        link1 = self.scene.new_link_item(file_item, "Data", disc_item, "Data")
        link1 = self.scene.add_link_item(link1)
        self.assertSequenceEqual(self.scene.link_items(), [link1])

        self.assertTrue(file_item.outputAnchors())
        self.assertTrue(disc_item.inputAnchors())

        self.app.exec_()

    def test_scene_with_scheme(self):
        """Test scene through modifying the scheme.
        """
        test_scheme = scheme.Scheme()
        self.scene.set_scheme(test_scheme)

        node_items = []
        link_items = []

        self.scene.node_item_added.connect(node_items.append)
        self.scene.node_item_removed.connect(node_items.remove)
        self.scene.link_item_added.connect(link_items.append)
        self.scene.link_item_removed.connect(link_items.remove)

        file_desc, disc_desc, bayes_desc = self.widget_desc()
        file_node = scheme.SchemeNode(file_desc)
        disc_node = scheme.SchemeNode(disc_desc)
        bayes_node = scheme.SchemeNode(bayes_desc)

        nodes = [file_node, disc_node, bayes_node]
        test_scheme.add_node(file_node)
        test_scheme.add_node(disc_node)
        test_scheme.add_node(bayes_node)

        self.assertTrue(len(self.scene.node_items()) == 3)
        self.assertSequenceEqual(self.scene.node_items(), node_items)

        for node, item in zip(nodes, node_items):
            self.assertIs(item, self.scene.item_for_node(node))

        # Remove a widget
        test_scheme.remove_node(bayes_node)
        self.assertTrue(len(self.scene.node_items()) == 2)
        self.assertSequenceEqual(self.scene.node_items(), node_items)

        # And add it again
        test_scheme.add_node(bayes_node)
        self.assertTrue(len(self.scene.node_items()) == 3)
        self.assertSequenceEqual(self.scene.node_items(), node_items)

        # Add links
        link1 = test_scheme.new_link(file_node, "Data", disc_node, "Data")
        link2 = test_scheme.new_link(disc_node, "Data", bayes_node, "Data")
        self.assertTrue(len(self.scene.link_items()) == 2)
        self.assertSequenceEqual(self.scene.link_items(), link_items)

        # Remove links
        test_scheme.remove_link(link1)
        test_scheme.remove_link(link2)
        self.assertTrue(len(self.scene.link_items()) == 0)
        self.assertSequenceEqual(self.scene.link_items(), link_items)

        # And add one link again
        test_scheme.add_link(link1)
        self.assertTrue(len(self.scene.link_items()) == 1)
        self.assertSequenceEqual(self.scene.link_items(), link_items)
        self.app.exec_()

    def test_scheme_construction(self):
        """Test construction (editing) of the scheme through the scene.
        """
        test_scheme = scheme.Scheme()
        self.scene.set_scheme(test_scheme)

        node_items = []
        link_items = []

        self.scene.node_item_added.connect(node_items.append)
        self.scene.node_item_removed.connect(node_items.remove)
        self.scene.link_item_added.connect(link_items.append)
        self.scene.link_item_removed.connect(link_items.remove)

        file_desc, disc_desc, bayes_desc = self.widget_desc()
        file_node = scheme.SchemeNode(file_desc)

        file_item = self.scene.add_node(file_node)
        self.scene.commit_scheme_node(file_node)

        self.assertSequenceEqual(self.scene.node_items(), [file_item])
        self.assertSequenceEqual(node_items, [file_item])
        self.assertSequenceEqual(test_scheme.nodes, [file_node])

        disc_node = scheme.SchemeNode(disc_desc)
        bayes_node = scheme.SchemeNode(bayes_desc)

        disc_item = self.scene.add_node(disc_node)
        bayes_item = self.scene.add_node(bayes_node)

        self.assertSequenceEqual(self.scene.node_items(),
                                 [file_item, disc_item, bayes_item])
        self.assertSequenceEqual(self.scene.node_items(), node_items)

        # The scheme is still the same.
        self.assertSequenceEqual(test_scheme.nodes, [file_node])

        # Remove items
        self.scene.remove_node(disc_node)
        self.scene.remove_node(bayes_node)

        self.assertSequenceEqual(self.scene.node_items(), [file_item])
        self.assertSequenceEqual(node_items, [file_item])
        self.assertSequenceEqual(test_scheme.nodes, [file_node])

        # Add them again this time also in the scheme.
        disc_item = self.scene.add_node(disc_node)
        bayes_item = self.scene.add_node(bayes_node)

        self.scene.commit_scheme_node(disc_node)
        self.scene.commit_scheme_node(bayes_node)

        self.assertSequenceEqual(self.scene.node_items(),
                                 [file_item, disc_item, bayes_item])
        self.assertSequenceEqual(self.scene.node_items(), node_items)
        self.assertSequenceEqual(test_scheme.nodes,
                                 [file_node, disc_node, bayes_node])

        link1 = scheme.SchemeLink(file_node, "Data", disc_node, "Data")
        link2 = scheme.SchemeLink(disc_node, "Data", bayes_node, "Data")
        link_item1 = self.scene.add_link(link1)
        link_item2 = self.scene.add_link(link2)

        self.assertSequenceEqual(self.scene.link_items(),
                                 [link_item1, link_item2])
        self.assertSequenceEqual(self.scene.link_items(), link_items)
        self.assertSequenceEqual(test_scheme.links, [])

        # Commit the links
        self.scene.commit_scheme_link(link1)
        self.scene.commit_scheme_link(link2)

        self.assertSequenceEqual(self.scene.link_items(),
                                 [link_item1, link_item2])
        self.assertSequenceEqual(self.scene.link_items(), link_items)
        self.assertSequenceEqual(test_scheme.links,
                                 [link1, link2])

        self.app.exec_()

    def widget_desc(self):
        from ...registry.tests import small_testing_registry
        reg = small_testing_registry()

        file_desc = reg.widget(
            "Orange.widgets.data.owfile.OWFile"
        )

        discretize_desc = reg.widget(
            "Orange.widgets.data.owdiscretize.OWDiscretize"
        )

        bayes_desc = reg.widget(
            "Orange.widgets.classify.ownaivebayes.OWNaiveBayes"
        )

        return file_desc, discretize_desc, bayes_desc


text:
<?php

namespace Application\Controller;

use Application\DAO\RoleDAO;
use Application\DAO\UserDAO;
use Application\Entity\User;
use Application\Form\UserForm;
use Zend\Mvc\Controller\AbstractActionController;

class UsersController extends AbstractActionController
{

    public function indexAction() {
        $userDAO = UserDAO::getInstance($this->getServiceLocator());
        $users = $userDAO->getAllUsers();

        return array('users' => $users);
    }

    public function editAction() {
        $form = new UserForm();
        $userId = (int)$this->params()->fromRoute('id', '');
        $request = $this->getRequest();
        $view = $request->getQuery()->view;
        $userDAO = UserDAO::getInstance($this->getServiceLocator());
        if (!empty($userId)) {
            $editableUser = $userDAO->findOneById($userId);
            if ($editableUser !== null) {
                if (!$request->isPost()) {
                    $userData = array(
                        'displayName' => $editableUser->getDisplayName(),
                        'email' => $editableUser->getEmail(),
                        'password' => $editableUser->getPassword(),
                        'role' => $editableUser->getRole()->getId(),
                    );
                    $form->setData($userData);
                    $form->setAttribute('action', '/users/edit/'.$editableUser->getId());
                }
            } else {
                return $this->redirect()->toRoute('users');
            }
        }

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $post['password'] = $editableUser !== null ? $editableUser->getPassword() : md5($post['password']);
            $form->setData($post);

            if ($form->isValid()) {
                $data = $form->getData();

                $userData = $editableUser !== null ? $editableUser : new User();
                $userData->setDisplayName($data['displayName']);
                $userData->getEmail($data['email']);
                $userData->setPassword($data['password']);
                $userData->setRole(RoleDAO::getInstance($this->getServiceLocator())->findOneById($data['role']));

                $userDAO->save($userData);
                return $this->redirect()->toRoute('users');
            } else {
                $form->getMessages();
            }
        }

        if ($editableUser) {
            $form->get('password')->setAttribute('disabled', 'disabled');
            $form->get('password')->setAttribute('type', 'password');
        }

        return array('form' => $form, 'view' => $view);
    }

    public function addAction() {
        $form = new UserForm();
        $request = $this->getRequest();
        $userDAO = UserDAO::getInstance($this->getServiceLocator());

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($post);

            if ($form->isValid()) {
                $data = $form->getData();

                $userData = new User();
                $userData->setDisplayName($data['displayName']);
                $userData->setEmail($data['email']);
                $userData->setPassword(md5($data['password']));
                $userData->setRole(RoleDAO::getInstance($this->getServiceLocator())->findOneById($data['role']));

                $userDAO->save($userData);

                return $this->redirect()->toRoute('users');
            } else {
                $form->getMessages();
            }
        }

        return array('form' => $form);
    }

    public function deleteAction() {
        $userId = (int)$this->params()->fromRoute('id', '');
        if ($userId) {
            $userDAO = UserDAO::getInstance($this->getServiceLocator());
            $removableUser = $userDAO->findOneById($userId);

            if ($removableUser !== null) {
                $userDAO->removeById($userId);
            }
        }

        return $this->redirect()->toRoute('users');
    }
}


text:
package sagan.site.learn;

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

import sagan.site.blog.Post;
import sagan.site.blog.support.PostView;
import sagan.site.blog.BlogService;
import sagan.site.support.DateFactory;
import sagan.site.support.nav.PageableFactory;

import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class LearnController {

	private final BlogService blogService;

	private final DateFactory dateFactory;

	public LearnController(BlogService blogService, DateFactory dateFactory) {
		this.blogService = blogService;
		this.dateFactory = dateFactory;
	}

	@GetMapping("/learn")
	public String learn(Model model) {
		Page<Post> page = this.blogService.getPublishedPosts(PageableFactory.first(4));
		Page<PostView> postViewPage = PostView.pageOf(page, dateFactory);
		List<PostView> posts = new ArrayList<>(postViewPage.getContent());
		model.addAttribute("newestPost", posts.remove(0));
		model.addAttribute("posts", posts);
		return "learn/index";
	}
}


text:
package service

import (
	"net/http"

	"tplgo/pkg/ent"
	"tplgo/pkg/ent/user"
	"tplgo/pkg/helpers"
	"tplgo/pkg/logger"
	"tplgo/pkg/result"

	"go.uber.org/zap"
)

type User interface {
	Info(w http.ResponseWriter, r *http.Request)
}

func NewUser() User {
	return new(users)
}

type users struct{}

type RespUserInfo struct {
	ID       int64  `json:"id"`
	Nickname string `json:"nickname"`
	Avatar   string `json:"avatar"`
}

func (u *users) Info(w http.ResponseWriter, r *http.Request) {
	uid := helpers.URLParamInt(r, "id")

	record, err := ent.DB.User.Query().Where(user.ID(uid)).First(r.Context())

	if err != nil {
		if ent.IsNotFound(err) {
			result.ErrNotFound().JSON(w, r)

			return
		}

		logger.Err(r.Context(), "err query user", zap.Error(err))

		result.ErrSystem(result.Err(err)).JSON(w, r)

		return
	}

	result.OK(result.Data(&RespUserInfo{
		ID:       uid,
		Nickname: record.Nickname,
		Avatar:   record.Avatar,
	})).JSON(w, r)
}


text:
async_test(function () {
    var page = require("webpage").create();
    var url1 = TEST_HTTP_BASE + "navigation/index.html";
    var url2 = TEST_HTTP_BASE + "navigation/dest.html";

    var onLoadFinished1 = this.step_func(function (status) {
        assert_equals(status, "success");
        assert_equals(page.url, url1);
        assert_equals(page.evaluate(function () {
            return document.body.innerHTML;
        }), "INDEX\n");

        page.onLoadFinished = onLoadFinished2;
        page.evaluate(function() {
            window.location = "dest.html";
        });
    });

    var onLoadFinished2 = this.step_func_done(function (status) {
        assert_equals(status, "success");
        assert_equals(page.url, url2);
        assert_equals(page.evaluate(function () {
            return document.body.innerHTML;
        }), "DEST\n");
    });

    page.onLoadFinished = onLoadFinished1;
    page.open(url1);

}, "navigating to a relative URL using window.location");


text:
@interface DDCollectionViewFlowLayout(){
    NSMutableArray			*sectionRects;
    NSMutableArray			*columnRectsInSection;

    NSMutableArray			*layoutItemAttributes;
    NSDictionary            *headerFooterItemAttributes;

    NSMutableArray          *sectionInsetses;

    UIEdgeInsets            currentEdgeInsets;
}

@end

@implementation DDCollectionViewFlowLayout

#pragma mark - UISubclassingHooks Category Methods

- (CGSize)collectionViewContentSize {
    [super collectionViewContentSize];

    CGRect lastSectionRect = [[sectionRects lastObject] CGRectValue];
    CGSize lastSize = CGSizeMake(CGRectGetWidth(self.collectionView.bounds), CGRectGetMaxY(lastSectionRect));
    return lastSize;
}

- (void)prepareLayout{

    NSUInteger numberOfSections = self.collectionView.numberOfSections;
    sectionRects = [[NSMutableArray alloc] initWithCapacity:numberOfSections];
    columnRectsInSection = [[NSMutableArray alloc] initWithCapacity:numberOfSections];
    layoutItemAttributes = [[NSMutableArray alloc] initWithCapacity:numberOfSections];
    sectionInsetses = [[NSMutableArray alloc] initWithCapacity:numberOfSections];
    headerFooterItemAttributes = @{UICollectionElementKindSectionHeader:[NSMutableArray array], UICollectionElementKindSectionFooter:[NSMutableArray array]};

    for (NSUInteger section = 0; section < numberOfSections; ++section) {
        NSUInteger itemsInSection = [self.collectionView numberOfItemsInSection:section];
        [layoutItemAttributes addObject:[NSMutableArray array]];
        [self prepareSectionLayout:section withNumberOfItems:itemsInSection];
    }
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind
                                                                     atIndexPath:(NSIndexPath *)indexPath {
    return headerFooterItemAttributes[kind][indexPath.section];
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    return layoutItemAttributes[indexPath.section][indexPath.item];
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    return [self searchVisibleLayoutAttributesInRect:rect];
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}

#pragma mark - Private Methods

- (void)prepareSectionLayout:(NSUInteger)section withNumberOfItems:(NSUInteger)numberOfItems{
    UICollectionView *cView = self.collectionView;

    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:section];

    //# hanlde the section header
    CGFloat headerHeight = 0.0f;

    CGRect previousSectionRect = [self rectForSectionAtIndex:indexPath.section - 1];
    CGRect sectionRect;
    sectionRect.origin.x = 0;
    sectionRect.origin.y = CGRectGetHeight(previousSectionRect) + CGRectGetMinY(previousSectionRect);
    sectionRect.size.width = cView.bounds.size.width;

    if([self.delegate respondsToSelector:@selector(collectionView:layout:referenceSizeForHeaderInSection:)]){

        //# Define the rect of the header
        CGRect headerFrame;
        headerFrame.origin.x = 0.0f;
        headerFrame.origin.y = sectionRect.origin.y;

        CGSize headerSize = [self.delegate collectionView:self.collectionView layout:self referenceSizeForHeaderInSection:indexPath.section];
        headerFrame.size.height = headerSize.height;
        headerFrame.size.width = headerSize.width;

        UICollectionViewLayoutAttributes *headerAttributes =
        [UICollectionViewLayoutAttributes
         layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader
         withIndexPath:indexPath];
        headerAttributes.frame = headerFrame;
        if (headerAttributes.size.width == 0) {
            headerAttributes.hidden = YES;
        }

        headerHeight = headerFrame.size.height;
        [headerFooterItemAttributes[UICollectionElementKindSectionHeader] addObject:headerAttributes];
    }

    //# get the insets of section
    UIEdgeInsets sectionInset = UIEdgeInsetsZero;

    if([self.delegate respondsToSelector:@selector(collectionView:layout:insetForSectionAtIndex:)]){
        sectionInset = [self.delegate collectionView:cView layout:self insetForSectionAtIndex:section];
    }

    [sectionInsetses addObject:[NSValue valueWithUIEdgeInsets:sectionInset]];

    CGRect itemsContentRect;

    //# the the lineSpacing & interitemSpacing default values
    CGFloat lineSpacing = 0.0f;
    CGFloat interitemSpacing = 0.0f;

    if([self.delegate respondsToSelector:@selector(collectionView:layout:minimumInteritemSpacingForSectionAtIndex:)]){
        interitemSpacing = [self.delegate collectionView:cView layout:self minimumInteritemSpacingForSectionAtIndex:section];
    }

    if([self.delegate respondsToSelector:@selector(collectionView:layout:minimumLineSpacingForSectionAtIndex:)]){
        lineSpacing = [self.delegate collectionView:cView layout:self minimumLineSpacingForSectionAtIndex:section];
    }

    itemsContentRect.origin.x = sectionInset.left;
    itemsContentRect.origin.y = headerHeight + sectionInset.top;

    NSUInteger numberOfColumns = [self.delegate collectionView:cView layout:self numberOfColumnsInSection:section];
    itemsContentRect.size.width = CGRectGetWidth(cView.frame) - (sectionInset.left + sectionInset.right);

    CGFloat columnSpace = itemsContentRect.size.width - (interitemSpacing * (numberOfColumns-1));
    CGFloat columnWidth = (columnSpace/numberOfColumns);

    // # store space for each column
    [columnRectsInSection addObject:[NSMutableArray arrayWithCapacity:numberOfColumns]];
    for (NSUInteger colIdx = 0; colIdx < numberOfColumns; ++colIdx)
        [columnRectsInSection[section] addObject:[NSMutableArray array]];

    // # Define the rect of the of each item
    for (NSInteger itemIdx = 0; itemIdx < numberOfItems; ++itemIdx) {
        NSIndexPath *itemPath = [NSIndexPath indexPathForItem:itemIdx inSection:section];
        CGSize itemSize = [self.delegate collectionView:cView layout:self sizeForItemAtIndexPath:itemPath];

        NSInteger destColumnIdx = [self preferredColumnIndexInSection:section];
        NSInteger destRowInColumn = [self numberOfItemsInColumn:destColumnIdx ofSection:section];
        CGFloat lastItemInColumnOffset = [self lastItemOffsetInColumn:destColumnIdx inSection:section];

        if(destRowInColumn == 0){
            lastItemInColumnOffset += sectionRect.origin.y;
        }

        CGRect itemRect;
        itemRect.origin.x = itemsContentRect.origin.x + destColumnIdx * (interitemSpacing + columnWidth);
        itemRect.origin.y = lastItemInColumnOffset + (destRowInColumn > 0 ? lineSpacing: sectionInset.top);
        itemRect.size.width = columnWidth;
        itemRect.size.height = itemSize.height;

        UICollectionViewLayoutAttributes *itemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:itemPath];
        itemAttributes.frame = itemRect;
        [layoutItemAttributes[section] addObject:itemAttributes];
        [columnRectsInSection[section][destColumnIdx] addObject:[NSValue valueWithCGRect:itemRect]];
    }

    itemsContentRect.size.height = [self heightOfItemsInSection:indexPath.section] + sectionInset.bottom;

    // # define the section footer
    CGFloat footerHeight = 0.0f;
    if([self.delegate respondsToSelector:@selector(collectionView:layout:referenceSizeForFooterInSection:)]){
        CGRect footerFrame;
        footerFrame.origin.x = 0;
        footerFrame.origin.y = itemsContentRect.size.height;

        CGSize footerSize = [self.delegate collectionView:self.collectionView layout:self referenceSizeForFooterInSection:indexPath.section];
        footerFrame.size.height = footerSize.height;
        footerFrame.size.width = footerSize.width;

        UICollectionViewLayoutAttributes *footerAttributes = [UICollectionViewLayoutAttributes
                                                              layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                                              withIndexPath:indexPath];
        footerAttributes.frame = footerFrame;

        footerHeight = footerFrame.size.height;

        [headerFooterItemAttributes[UICollectionElementKindSectionFooter] addObject:footerAttributes];
    }

    if(section > 0){
        if ([self.delegate respondsToSelector:@selector(numberOfItemsInSection:)]) {
            NSUInteger numberOfItems = [self.delegate numberOfItemsInSection:section];
            if (numberOfItems > 0) {
                itemsContentRect.size.height -= sectionRect.origin.y;
            }
        }

    }

    sectionRect.size.height = itemsContentRect.size.height + footerHeight;

    [sectionRects addObject:[NSValue valueWithCGRect:sectionRect]];
}

- (CGFloat)heightOfItemsInSection:(NSUInteger)sectionIdx {
    CGFloat maxHeightBetweenColumns = 0.0f;
    NSArray *columnsInSection = columnRectsInSection[sectionIdx];
    for (NSUInteger columnIdx = 0; columnIdx < columnsInSection.count; ++columnIdx) {
        CGFloat heightOfColumn = [self lastItemOffsetInColumn:columnIdx inSection:sectionIdx];
        maxHeightBetweenColumns = MAX(maxHeightBetweenColumns, heightOfColumn);
    }
    return maxHeightBetweenColumns;
}

- (NSInteger)numberOfItemsInColumn:(NSInteger)columnIdx ofSection:(NSInteger)sectionIdx {
    return [columnRectsInSection[sectionIdx][columnIdx] count];
}

- (CGFloat)lastItemOffsetInColumn:(NSInteger)columnIdx inSection:(NSInteger)sectionIdx {
    NSArray *itemsInColumn = columnRectsInSection[sectionIdx][columnIdx];
    if (itemsInColumn.count == 0) {
        if([headerFooterItemAttributes[UICollectionElementKindSectionHeader] count] > sectionIdx){
            CGRect headerFrame = [headerFooterItemAttributes[UICollectionElementKindSectionHeader][sectionIdx] frame];
            return headerFrame.size.height;
        }
        return 0.0f;
    } else {
        CGRect lastItemRect = [[itemsInColumn lastObject] CGRectValue];
        return CGRectGetMaxY(lastItemRect);
    }
}

- (NSInteger)preferredColumnIndexInSection:(NSInteger)sectionIdx {
    NSUInteger shortestColumnIdx = 0;
    CGFloat heightOfShortestColumn = CGFLOAT_MAX;
    for (NSUInteger columnIdx = 0; columnIdx < [columnRectsInSection[sectionIdx] count]; ++columnIdx) {
        CGFloat columnHeight = [self lastItemOffsetInColumn:columnIdx inSection:sectionIdx];
        if (columnHeight < heightOfShortestColumn) {
            shortestColumnIdx = columnIdx;
            heightOfShortestColumn = columnHeight;
        }
    }
    return shortestColumnIdx;
}

- (CGRect)rectForSectionAtIndex:(NSInteger)sectionIdx {
    if (sectionIdx < 0 || sectionIdx >= sectionRects.count)
        return CGRectZero;
    return [sectionRects[sectionIdx] CGRectValue];
}

#pragma mark - Show Attributes Methods
- (NSArray *)searchVisibleLayoutAttributesInRect:(CGRect)rect {
    NSMutableArray *itemAttrs = [[NSMutableArray alloc] init];
    NSIndexSet *visibleSections = [self sectionIndexesInRect:rect];
    [visibleSections enumerateIndexesUsingBlock:^(NSUInteger sectionIdx, BOOL *stop) {

        //# items
        for (UICollectionViewLayoutAttributes *itemAttr in layoutItemAttributes[sectionIdx]) {
            CGRect itemRect = itemAttr.frame;
            itemAttr.zIndex = 1;
            BOOL isVisible = CGRectIntersectsRect(rect, itemRect);
            if (isVisible)
                [itemAttrs addObject:itemAttr];
        }

        //# footer
        if([headerFooterItemAttributes[UICollectionElementKindSectionFooter] count] > sectionIdx){
            UICollectionViewLayoutAttributes *footerAttribute = headerFooterItemAttributes[UICollectionElementKindSectionFooter][sectionIdx];
            BOOL isVisible = CGRectIntersectsRect(rect, footerAttribute.frame);
            if (isVisible && footerAttribute)
                [itemAttrs addObject:footerAttribute];
            currentEdgeInsets = UIEdgeInsetsZero;
        }else{
            currentEdgeInsets = [sectionInsetses[sectionIdx] UIEdgeInsetsValue];
        }

        //# header
        if([headerFooterItemAttributes[UICollectionElementKindSectionHeader] count] > sectionIdx){
            UICollectionViewLayoutAttributes *headerAttribute = headerFooterItemAttributes[UICollectionElementKindSectionHeader][sectionIdx];

            if(!self.enableStickyHeaders){
                BOOL isVisibleHeader = CGRectIntersectsRect(rect, headerAttribute.frame);

                if (isVisibleHeader && headerAttribute)
                    [itemAttrs addObject:headerAttribute];
            }else{
                UICollectionViewLayoutAttributes *lastCell = [itemAttrs lastObject];

                if(headerAttribute)
                   [itemAttrs addObject:headerAttribute];

                [self updateHeaderAttributes:headerAttribute lastCellAttributes:lastCell];
            }
        }
    }];
    return itemAttrs;
}

- (NSIndexSet *)sectionIndexesInRect:(CGRect)rect {
    CGRect theRect = rect;
    NSMutableIndexSet *visibleIndexes = [[NSMutableIndexSet alloc] init];
    NSUInteger numberOfSections = self.collectionView.numberOfSections;
    for (NSUInteger sectionIdx = 0; sectionIdx < numberOfSections; ++sectionIdx) {
        CGRect sectionRect = [sectionRects[sectionIdx] CGRectValue];
        BOOL isVisible = CGRectIntersectsRect(theRect, sectionRect);
        if (isVisible)
            [visibleIndexes addIndex:sectionIdx];
    }
    return visibleIndexes;
}

#pragma mark - Sticky Header implementation methods

- (void)updateHeaderAttributes:(UICollectionViewLayoutAttributes *)attributes
            lastCellAttributes:(UICollectionViewLayoutAttributes *)lastCellAttributes
{
    CGRect currentBounds = self.collectionView.bounds;
    attributes.zIndex = 1024;
    attributes.hidden = NO;

    CGPoint origin = attributes.frame.origin;

    CGFloat sectionMaxY = CGRectGetMaxY(lastCellAttributes.frame) - attributes.frame.size.height + currentEdgeInsets.bottom;

    CGFloat y = CGRectGetMaxY(currentBounds) - currentBounds.size.height + self.collectionView.contentInset.top;

    CGFloat maxY = MIN(MAX(y, attributes.frame.origin.y), sectionMaxY);

    origin.y = maxY;

    attributes.frame = (CGRect){
        origin,
        attributes.frame.size
    };
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <com.nhaarman.listviewanimations.itemmanipulation.DynamicListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list"
        android:layout_alignParentTop="true"
        android:transcriptMode="normal"
        android:background="@android:color/black"
        android:scrollbarStyle="outsideOverlay"
        android:choiceMode="singleChoice"
        android:focusable="false"
        android:drawSelectorOnTop="true"
        android:fastScrollEnabled="false"
        android:fastScrollAlwaysVisible="false"/>
</RelativeLayout>


text:
//  (C) Copyright John Maddock 2001 - 2003.
//  (C) Copyright Jens Maurer 2001 - 2003.
//  (C) Copyright Aleksey Gurtovoy 2002.
//  (C) Copyright David Abrahams 2002 - 2003.
//  (C) Copyright Toon Knapen 2003.
//  (C) Copyright Boris Gubenko 2006 - 2007.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org for most recent version.

//  HP aCC C++ compiler setup:

#if defined(__EDG__)
#include "autoboost/config/compiler/common_edg.hpp"
#endif

#if (__HP_aCC <= 33100)
#    define AUTOBOOST_NO_INTEGRAL_INT64_T
#    define AUTOBOOST_NO_OPERATORS_IN_NAMESPACE
#  if !defined(_NAMESPACE_STD)
#     define AUTOBOOST_NO_STD_LOCALE
#     define AUTOBOOST_NO_STRINGSTREAM
#  endif
#endif

#if (__HP_aCC <= 33300)
// member templates are sufficiently broken that we disable them for now
#    define AUTOBOOST_NO_MEMBER_TEMPLATES
#    define AUTOBOOST_NO_DEPENDENT_NESTED_DERIVATIONS
#    define AUTOBOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE
#endif

#if (__HP_aCC <= 38000)
#  define AUTOBOOST_NO_TWO_PHASE_NAME_LOOKUP
#endif

#if (__HP_aCC > 50000) && (__HP_aCC < 60000)
#    define AUTOBOOST_NO_UNREACHABLE_RETURN_DETECTION
#    define AUTOBOOST_NO_TEMPLATE_TEMPLATES
#    define AUTOBOOST_NO_SWPRINTF
#    define AUTOBOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS
#    define AUTOBOOST_NO_IS_ABSTRACT
#    define AUTOBOOST_NO_MEMBER_TEMPLATE_FRIENDS
#endif

// optional features rather than defects:
#if (__HP_aCC >= 33900)
#    define AUTOBOOST_HAS_LONG_LONG
#    define AUTOBOOST_HAS_PARTIAL_STD_ALLOCATOR
#endif

#if (__HP_aCC >= 50000 ) && (__HP_aCC <= 53800 ) || (__HP_aCC < 31300 )
#    define AUTOBOOST_NO_MEMBER_TEMPLATE_KEYWORD
#endif

// This macro should not be defined when compiling in strict ansi
// mode, but, currently, we don't have the ability to determine
// what standard mode we are compiling with. Some future version
// of aCC6 compiler will provide predefined macros reflecting the
// compilation options, including the standard mode.
#if (__HP_aCC >= 60000) || ((__HP_aCC > 38000) && defined(__hpxstd98))
#    define AUTOBOOST_NO_TWO_PHASE_NAME_LOOKUP
#endif

#define AUTOBOOST_COMPILER "HP aCC version " AUTOBOOST_STRINGIZE(__HP_aCC)

//
// versions check:
// we don't support HP aCC prior to version 33000:
#if __HP_aCC < 33000
#  error "Compiler not supported or configured - please reconfigure"
#endif

//
// Extended checks for supporting aCC on PA-RISC
#if __HP_aCC > 30000 && __HP_aCC < 50000
#  if __HP_aCC < 38000
      // versions prior to version A.03.80 not supported
#     error "Compiler version not supported - version A.03.80 or higher is required"
#  elif !defined(__hpxstd98)
      // must compile using the option +hpxstd98 with version A.03.80 and above
#     error "Compiler option '+hpxstd98' is required for proper support"
#  endif //PA-RISC
#endif

//
// C++0x features
//
//   See autoboost\config\suffix.hpp for AUTOBOOST_NO_LONG_LONG
//
#if !defined(__EDG__)

#define AUTOBOOST_NO_CXX11_AUTO_DECLARATIONS
#define AUTOBOOST_NO_CXX11_AUTO_MULTIDECLARATIONS
#define AUTOBOOST_NO_CXX11_CHAR16_T
#define AUTOBOOST_NO_CXX11_CHAR32_T
#define AUTOBOOST_NO_CXX11_CONSTEXPR
#define AUTOBOOST_NO_CXX11_DECLTYPE
#define AUTOBOOST_NO_CXX11_DECLTYPE_N3276
#define AUTOBOOST_NO_CXX11_DEFAULTED_FUNCTIONS
#define AUTOBOOST_NO_CXX11_DELETED_FUNCTIONS
#define AUTOBOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
#define AUTOBOOST_NO_CXX11_EXTERN_TEMPLATE
#define AUTOBOOST_NO_CXX11_FUNCTION_TEMPLATE_DEFAULT_ARGS
#define AUTOBOOST_NO_CXX11_HDR_INITIALIZER_LIST
#define AUTOBOOST_NO_CXX11_LAMBDAS
#define AUTOBOOST_NO_CXX11_LOCAL_CLASS_TEMPLATE_PARAMETERS
#define AUTOBOOST_NO_CXX11_NOEXCEPT
#define AUTOBOOST_NO_CXX11_NULLPTR
#define AUTOBOOST_NO_CXX11_RANGE_BASED_FOR
#define AUTOBOOST_NO_CXX11_RAW_LITERALS
#define AUTOBOOST_NO_CXX11_RVALUE_REFERENCES
#define AUTOBOOST_NO_CXX11_SCOPED_ENUMS
#define AUTOBOOST_NO_SFINAE_EXPR
#define AUTOBOOST_NO_CXX11_STATIC_ASSERT
#define AUTOBOOST_NO_CXX11_TEMPLATE_ALIASES
#define AUTOBOOST_NO_CXX11_UNICODE_LITERALS
#define AUTOBOOST_NO_CXX11_VARIADIC_TEMPLATES
#define AUTOBOOST_NO_CXX11_USER_DEFINED_LITERALS
#define AUTOBOOST_NO_CXX11_ALIGNAS
#define AUTOBOOST_NO_CXX11_TRAILING_RESULT_TYPES
#define AUTOBOOST_NO_CXX11_INLINE_NAMESPACES
#define AUTOBOOST_NO_CXX11_REF_QUALIFIERS

/*
  See https://forums13.itrc.hp.com/service/forums/questionanswer.do?threadId=1443331 and
      https://forums13.itrc.hp.com/service/forums/questionanswer.do?threadId=1443436
*/

#if (__HP_aCC < 62500) || !defined(HP_CXX0x_SOURCE)
  #define AUTOBOOST_NO_CXX11_VARIADIC_MACROS
#endif

#endif

//
// last known and checked version for HP-UX/ia64 is 61300
// last known and checked version for PA-RISC is 38000
#if ((__HP_aCC > 61300) || ((__HP_aCC > 38000) && defined(__hpxstd98)))
#  if defined(AUTOBOOST_ASSERT_CONFIG)
#     error "Unknown compiler version - please run the configure tests and report the results"
#  endif
#endif


text:
<?php

namespace Cjm\Behat\Psr7Extension\Slim;

use Slim\App as Application;

class AppFactoryTest extends \PHPUnit\Framework\TestCase
{
    private $factory;

    function setUp()
    {
        $this->factory = new AppFactory;
    }

    function testItDoesNotCreateAppFromNonSlimApp()
    {
        $app = $this->factory->createFrom(new \StdClass);

        $this->assertSame(null, $app);
    }

    function testItCreatesAnAppFromASlimApp()
    {
        $app = $this->factory->createFrom($this->createMock(Application::class));

        $this->assertInstanceOf(App::class, $app);
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
    public class PartialTypeDocumentationCommentTests : CSharpTestBase
    {
        private readonly CSharpCompilation _compilation;
        private readonly NamedTypeSymbol _fooClass;

        public PartialTypeDocumentationCommentTests()
        {
            var tree1 = Parse(
                @"
/// Summary on first file's Foo.
partial class Foo
{
    /// Summary on MethodWithNoImplementation.
    partial void MethodWithNoImplementation();

    /// Summary in file one which should be shadowed.
    partial void ImplementedMethodWithNoSummaryOnImpl();

    partial void ImplementedMethod();
}", options: TestOptions.RegularWithDocumentationComments);

            var tree2 = Parse(
                @"
/// Summary on second file's Foo.
partial class Foo
{
    /// <remarks>Foo.</remarks>
    partial void ImplementedMethodWithNoSummaryOnImpl() { }

    /// Implemented method.
    partial void ImplementedMethod() { }
}", options: TestOptions.RegularWithDocumentationComments);

            _compilation = CreateCompilationWithMscorlib(new[] { tree1, tree2 });

            _fooClass = _compilation.GlobalNamespace.GetTypeMembers("Foo").Single();
        }

        [Fact]
        public void TestSummaryOfType()
        {
            Assert.Equal(
@"<member name=""T:Foo"">
    Summary on first file's Foo.
    Summary on second file's Foo.
</member>
", _fooClass.GetDocumentationCommentXml());
        }

        [Fact]
        public void TestSummaryOfMethodWithNoImplementation()
        {
            var method = _fooClass.GetMembers("MethodWithNoImplementation").Single();
            Assert.Equal(string.Empty, method.GetDocumentationCommentXml()); //Matches what would be written to an XML file.
        }

        [Fact]
        public void TestImplementedMethodWithNoSummaryOnImpl()
        {
            // This is an interesting behavior; as long as there is any XML at all on the implementation, it overrides
            // any XML on the latent declaration. Since we don't have a summary on this implementation, this should be
            // null!
            var method = _fooClass.GetMembers("ImplementedMethodWithNoSummaryOnImpl").Single();
            Assert.Equal(
@"<member name=""M:Foo.ImplementedMethodWithNoSummaryOnImpl"">
    <remarks>Foo.</remarks>
</member>
", method.GetDocumentationCommentXml());
        }

        [Fact]
        public void TestImplementedMethod()
        {
            var method = _fooClass.GetMembers("ImplementedMethod").Single();
            Assert.Equal(
@"<member name=""M:Foo.ImplementedMethod"">
    Implemented method.
</member>
", method.GetDocumentationCommentXml());
        }
    }
}


text:
[![Latest version](https://img.shields.io/npm/v/backbone.composite-model)](https://www.npmjs.com/package/backbone.composite-model)
![Bower version](https://img.shields.io/bower/v/backbone.composite-model.svg)
[![Dependency status](https://img.shields.io/librariesio/release/npm/backbone.composite-model)](https://www.npmjs.com/package/backbone.composite-model)
[![Test code coverage](https://codecov.io/gh/prantlf/backbone.composite-model/branch/master/graph/badge.svg?token=8itqsA2HVj)](https://codecov.io/gh/prantlf/backbone.composite-model)
[![Code Climate](https://codeclimate.com/github/prantlf/backbone.composite-model/badges/gpa.svg)](https://codeclimate.com/github/prantlf/backbone.composite-model)

Supports composite [`Backbone.Model`] objects which represent a "master"
model containing "slave" models or collections maintained automatically
according to the composite model configuration

* [Motivation Example](#motivation-example)
  + [Flat Model](#flat-model)
  + [Manual Composite Model](#manual-composite-model)
  + [Reusable Composite Model](#reusable-composite-model)
* [Synopsis](#synopsis)
  + [Composite Configuration](#composite-configuration)
  + [Configuration Examples](#configuration-examples)
* [What Is It For?](#what-is-it-for)
* [What Is It Not For?](#what-is-it-not-for)
* [Installation](#installation)
* [Build](#build)
* [Contributing](#contributing)
* [Release History](#release-history)
* [License](#license)

## Motivation Example

Let's have a versioned file-system model: folders containing files, files
consisting of versions:

![File-System Model](https://raw.githubusercontent.com/prantlf/backbone.composite-model/master/docs/file-system.png)

A JSON object representing a file would look like this:

```text
{
  "id": ...,        // unique ID of the file
  "name": '...',    // display name of the file
  "parent": {...},  // object describing the parent folder
  "versions": [...] // array of file version description objects
}
```

### Flat Model

Modelling it with a flat [`Backbone.Model`] would look like this:

```javascript
var FileModel = Backbone.Model.extend({
      urlRoot: '/files'
    });
```

[Backbone] events for attribute changes in models and model additions /
removals in collections work only for "flat" models; only for first-level
attributes of the main model:

```javascript
// Declare a model representing a file information
var file = new FileModel({id: 1});
// Inform whenever the file information has been fetched and is ready
file.on('sync', function (file) {
  console.log('File information ready for', file.get('name'));
});
// Inform whenever the parent folder of the current file has changed
// THIS DOES NOT WORK: watching 'parent.id'
file.on('change:parent.id', function (parent) {
  console.log('Location changed to', parent.get('name'));
});
// Fetch information about the initial file - only the first event above
// will be triggered; the second will be never triggered
file.fetch();
```

We would not be able to pass the parent or version information alone to some
view and let it refreshed as another file would be fetched, for example.

### Manual Composite Model

If the `parent` and `versions` child objects should be exposed like real
[Backbone] objects, to be able to work with their events in controllers
and views, associated objects can be created and maintained whenever the
"master" model changes, for example:

```javascript
var FolderModel = Backbone.Model.extend({...}),
    VersionModel = Backbone.Model.extend({...}),
    VersionCollection = Backbone.Collection.extend({
      model: VersionModel,
      ...
    }),
    FileModel = Backbone.Model.extend({
      initialize: function (attributes, options) {
        // Initialize the child models and collections
        attributes || (attributes = {});
        this.parent = new FolderModel(attributes.parent, options);
        this.versions = new VersionCollection(attributes.versions, options);
        // Whenever the "master" model is re-fetched, update the child ones
        this.on('sync', function (model, response, options) {
          this.parent.set(this.attributes.parent, options);
          this.versions.reset(this.attributes.versions, options);
        }, this);
      },
      urlRoot: '/files'
    });
```

Accessing the child models or collections is possible using the
[Backbone] interface, including the change events:

```javascript
// Declare a model representing a file information
var file = new FileModel({id: 1});
// Inform whenever the file information has been fetched and is ready
file.on('sync', function (file) {
  console.log('File information ready for', file.get('name'));
});
// Inform whenever the parent folder of the current file has changed
// THIS WORKS NOW: watching 'id' of the child model `file.parent`
file.parent.on('change:id', function (parent) {
  console.log('Location changed to', parent.get('name'));
});
// Fetch information about the initial file - both events above will be
// triggered
file.fetch();
// Fetch information about another file - the first event will be always
// triggered, the second one will be triggered only if the new file has
// a different parent folder than the previous one
file.set('id', 2)
    .fetch();
```

### Reusable Composite Model

Modelling the same scenario with the help of the `Backbone.CompositeModel`
would look like this:

```javascript
var FileModel = Backbone.Model.extend({
      // Declare what attributes map to what child models or collections
      composite: {
        parent: FolderModel,
        versions: VersionCollection
      },
      initialize: function (attributes, options) {
        // Initialize the child models and collections
        this.makeComposite(options);
      },
      urlRoot: '/files'
    });
// Extend the prototype with methods managing the child models and collections
Backbone.mixinCompositeModel(FileModel.prototype);
```

The `FileModel` above will have the child objects `parent` and `versions`
maintained automatically, whenever they change in the "master" model.

## Synopsis

The `Backbone.CompositeModel` offers a common implementation of the so-called
"master-slave" or "parent-child" model/collection pattern, that propagates
the changes caused by `set`, `unset`, `clear`, `fetch` and `save` methods on
the "master" model to the "slave" models and/or collections, which are fully
owned by the "master" model, including their creation.

Child models are supposed to be created from object literals:

![Slave Model](https://raw.githubusercontent.com/prantlf/backbone.composite-model/master/docs/slave-model.png)

Child collections are supposed to be created from arrays:

![Slave Collection](https://raw.githubusercontent.com/prantlf/backbone.composite-model/master/docs/slave-collection.png)

Initialization of a *composite model* should include the following parts:

1. Provide the `composite` configuration object as a property in the
   prototype or in the new instance initialization `options`
2. Call the `makeComposite` method from the `constructor` or from the
   `initialize` method
3. Extend the "master" model's prototype by calling the
   `Backbone.mixinCompositeModel` method

```javascript
var MasterModel = Backbone.Model.extend({
      // Declare what attributes map to what child models or collections
      composite: {
        child: SlaveModel,
      },
      initialize: function (attributes, options) {
        // Initialize the child models and collections
        this.makeComposite(options);
      },
      ...
    });
// Extend the prototype with methods managing the child models and collections
Backbone.mixinCompositeModel(MasterModel.prototype);
```

### Composite Configuration

The `composite` configuration object maps an attribute name to the "slave"
model specification:

```text
'<attribute name>': <"slave" model specification>
```

The *attribute name* has to exist in the `this.attributes` of the "master"
model and will back up the "slave" model or collection.  The property on the
"master" model will be created using the attribute name by default.

The *"slave" model specification* can be either a [`Backbone.Model`]
descendant for "slave" models or a [`Backbone.Collection`] descendant for
"slave" collections.  It will be the function object to create the "slave"
model or collection from:

```text
'<attribute name>': Backbone.Model | Backbone.Collection
```

The default creation and maintenance of the "slave" models and collections
can be overridden by passing an object literal as the "slave" model
specification:

```text
'<attribute name>': {
  type: Backbone.Model | Backbone.Collection,
  ...
}
```

The following properties of the "slave" model specification object are
supported:

* `type`: [`Backbone.Model`] descendant for "slave" models or a
  [`Backbone.Collection`] descendant for "slave" collections (required)
* `property`: Property name to store the "slave" model or collection on the
  "master" model with (optional; the attribute name is the default)
* `options`: Additional options to pass to the constructor of the "slave"
  model or collection (optional; undefined by default)
* `method`: Method to call on the "slave" model or collection if updated data
  are being set (optional; `set` is the default for models, `add` for
  collections)
* `parse`: Function to call before the value is passed to child model or
  collection constructor or to the `set` / `add` method to "massage" the
  input data (optional; `undefined` is the default)

### Configuration Examples

Maintain a `parent` model based on the `this.attributes.parent` object
and a `versions` collection based on the `this.attributes.versions` array
from the composite model:

```javascript
composite: {
  parent: FolderModel,
  versions: VersionCollection
}
```

Name the property on the composite model "parent", although the backing up
property is called "parent_expanded":

```javascript
composite: {
  parent_expanded: {
    type: FolderModel,
    property: 'parent'
  }
}
```

Ensure that the "slave" model has always a property `child_id` with the value
of the `id` property of the "master" model:

```javascript
composite: {
  parent: {
    type: FolderModel,
    parse: function (attributes, options) {
             var id = this.get('id');
             if (id != null) {
               attributes || (attributes = {});
               attributes.child_id = id;
             }
             return attributes;
           }
  }
}
```

Use the `reset` method to populate the "slave" collection instead of the
`add` method, which is used by default:

```javascript
composite: {
  versions: {
    type: VersionCollection,
    method: 'reset'
  }
}
```

## What Is It For?

* Forward changes (main model attributes -> child model or collection):
  + Create a property on the main model with the child model or collection
    automatically
  + If the root attribute on the main model, which backs up the child model
    or collection, changes by calling the `set` method, propagate the change
    to the child model or collection
* You need to fetch or constantly re-fetch the main model and have the
  listeners (views) notified about changes in the child models or collections.

You can get the up-to-date content of all nested models and collections by
calling `toJSON` of the master model.

## What Is It Not For?

* Backward changes (child model or collection: -> main model attributes):
  + If an attribute of the child model or a model in the child collection
    changes, propagate the change to the object under the root attribute,
    which backs up the child model or collection

Instead of updating `attributes` of the master model directly, you can
consider calling `set/unset/clear/add/remove/reset` methods of nested models
and collections. You will be able to get the up-to-date content of all nested
models and collections by calling `toJSON` of the master model.

## Installation

Make sure that you have [NodeJS] >= 6 installed.  You can use either `npm`
or `bower` to install this package and its dependencies.

With [NPM]:

```shell
npm install backbone.composite-model
```

With [Bower]:

```shell
bower install backbone.composite-model
```

## Build

Make sure that you have [NodeJS] >= 6 installed.  Clone the Github
repository to a local directory, enter it and install the package
dependencies (including the development dependencies) by `npm`:

```shell
git clone https://github.com/prantlf/backbone.composite-model.git
cd backbone.composite-model
npm install
```

Examples and tests will be functional now.

## Contributing

In lieu of a formal styleguide, take care to maintain the existing coding
style.  Add unit tests for any new or changed functionality.

Before you start, make sure that you have satisfied native dependencies
of the [node-canvas](https://github.com/Automattic/node-canvas) module,
which are described for every operating system at the [documentation wiki
of the project](https://github.com/Automattic/node-canvas/wiki/_pages).

First fork this repository and clone your fork locally instead of cloning
the original.  See the "Build" chapter above for more details about how to
clone it and install the build dependencies.

Before you commit, update minified files and source maps, re-generate
documentation and check if tests succeed:

```shell
npm run-script build
npm run-script doc
npm test
```

Commit your changes to a separtate branch, so that you can create a pull
request for it:

```shell
git checkout -b <branch name>
git commit -a
git push origin <branch name>
```

## License

Copyright (c) 2015-2022 Ferdinand Prantl

Licensed under the MIT license.

[Backbone]: http://backbonejs.org/
[`Backbone.Model`]: http://backbonejs.org/#Model
[`Backbone.Collection`]: http://backbonejs.org/#Collection
[Bower]: http://bower.io/
[NodeJS]: http://nodejs.org/
[NPM]: https://www.npmjs.com/


text:
SF.Vehicles = {}

--- Vehicle type for GMod Vehicles

-- They still behave exactly as Entities, see Entities Type for defined functions
local vehicle_methods, vehicle_metamethods = SF.Typedef( "Vehicle", SF.Entities.Metatable )

local vwrap = SF.WrapObject

SF.Vehicles.Methods = vehicle_methods
SF.Vehicles.Metatable = vehicle_metamethods

--- Using a custom wrapper / unwrapper similar to the player wrapper

local function wrap ( obj )
	obj = SF.Entities.Wrap( obj )
	debug.setmetatable( obj, vehicle_metamethods )
	return obj
end

local unwrap = SF.Entities.Unwrap

SF.AddObjectWrapper( debug.getregistry().Vehicle, vehicle_metamethods, wrap )
SF.AddObjectUnwrapper( vehicle_metamethods, unwrap )

--- Adding the wrap / unwrap functions to the SF.Vehicles table
SF.Vehicles.Wrap = wrap
SF.Vehicles.Unwrap = unwrap

--- toString
--@shared
function vehicle_metamethods:__tostring ()
	local ent = unwrap( self )
	if not ent then
		return "(NULL Entity)"
	else
		return tostring( ent )
	end
end


text:
package io.avalia.samba;

import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.assertNotNull;

public class ApitoTest {

    @Test
    public void thereShouldBeAnIInstrumentInterfaceAndAApitoClass() {
        IInstrument apito = new Apito();
        assertNotNull(apito);
    }

    @Test
    public void itShouldBePossibleToPlayAnInstrument() {
        IInstrument apito = new Apito();
        String sound = apito.play();
        assertNotNull(sound);
    }

    @Test
    public void aApitoShouldMakePee() {
        IInstrument apito = new Apito();
        String sound = apito.play();
        Assert.assertEquals("pee", sound);
    }

    @Test
    public void aApitoShouldBeMetallic() {
        IInstrument apito = new Apito();
        String color = apito.getColor();
        Assert.assertEquals("metallic", color);
    }
}


text:
<?php

/**
 * Returns the Mapped Diagnostic Context value corresponding to the given key.
 *
 * Options:
 *  [0] the MDC key
 *
 * @package log4php
 * @subpackage pattern
 * @version $Revision: 1326626 $
 * @since 2.3
 */
class LoggerPatternConverterMDC extends LoggerPatternConverter {

	private $key;

	public function activateOptions() {
		if (isset($this->option) && $this->option !== '') {
			$this->key = $this->option;
		}
	}

	public function convert(LoggerLoggingEvent $event) {
		if (isset($this->key)) {
			return $event->getMDC($this->key);
		} else {
			$buff = array();
			$map = $event->getMDCMap();
			foreach($map as $key => $value) {
				$buff []= "$key=$value";
			}
			return implode(', ', $buff);
		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Refiner — DH_Doc 0.1 documentation</title>

    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="DH_Doc 0.1 documentation" href="index.html" />
    <link rel="up" title="Core Apps" href="Core Apps.html" />
    <link rel="next" title="Sentiment" href="django-app-sentiment.html" />
    <link rel="prev" title="DBWipes App" href="django-app-dbwipes.html" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

 Generated by Sphinx

Refiner¶

primary(s):   Anant Bhardwaj

maintainer(s): Anant Bhardwaj

location: src/apps/refiner

presentation: src/apps/refiner/presentation

Refiner takes semi-structured data and example data, and structures it for
table creation.

NOTE: Refiner is currently for research purposes only. Structing data works,
but automated table creation currently does not work

How to use¶

Run DataHub

Navigate to apps/refiner

Select one of the example datasets

Click Refine

Table Of Contents

Refiner

How to use

Related Topics

Documentation overview

Core Apps

Previous: DBWipes App

Next: Sentiment

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

      ©2015, MIT Living Lab.

      |
      Powered by Sphinx 1.3.1
      & Alabaster 0.7.7

      |
      Page source


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.08.30 at 11:05:06 오전 KST
//

package com.athena.chameleon.engine.entity.xml.application.v1_4;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *
 * 	The jndi-nameType type designates a JNDI name in the
 * 	Deployment Component's environment and is relative to the
 * 	java:comp/env context.  A JNDI name must be unique within the
 * 	Deployment Component.
 *
 *
 *
 *
Java class for jndi-nameType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="jndi-nameType">
 *   <simpleContent>
 *     <restriction base="<http://java.sun.com/xml/ns/j2ee>string">
 *     </restriction>
 *   </simpleContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "jndi-nameType")
@XmlSeeAlso({
    EjbRefNameType.class
})
public class JndiNameType
    extends String
{

}


text:
const config = require('./config');

module.exports = function (grunt) {
    //Setup for OG's deploy scripts (used internally)
    grunt.registerTask('ts:dev', 'Placeholder for deploy build', () => {
        grunt.task.run('webpack:dev');

    });

    grunt.registerTask('ts:dist', 'Placeholder for deploy build', () => {
        grunt.task.run('webpack:dist');
    });
};


text:
"""TestTAPublic.py contains a series of tests for TAPublic"""

import logging, unittest
import webapp2, webtest

from google.appengine.api   import memcache
from google.appengine.ext   import db, testbed

from ffe.gae                import read_counter
import TAPublic
from TASeries import TASeries

class TestTAPublic(unittest.TestCase):

    def setUp(self):
        self.app = TAPublic.app
        self.testApp = webtest.TestApp(self.app)
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

        logger = logging.getLogger()
        logger.level = logging.DEBUG

    def tearDown(self):
        self.testbed.deactivate()

    def test_handler(self):
        self.assertFalse(self.app.debug,
                         "FRS 4.1.1 Debug-mode in TAPublic must be switched off")
        response = self.testApp.get('/trajectory', status=404)
        self.assertEqual(response.status, '404 Not Found',
                         "FRS 4.1.2 Requests with incomplete parameters must be answered with 404")
        response = self.testApp.get('/mission', status=404)
        self.assertEqual(response.status, '404 Not Found',
                         "FRS 4.1.2 Requests with incomplete parameters must be answered with 404")

    def test_trajectory(self):
        TASeries.import_xml('TestTAPublic.data/series_trajectory.xml')

        expected = '{"origin": "nl.ut", "destination": "nl.ehv", "options": [{"id": "nl.829", "v": "2013-05-16T09:08:00"}, {"id": "nl.3529", "v": "2013-05-16T09:23:00"}, {"id": "nl.831", "v": "2013-05-16T09:38:00"}, {"id": "nl.3531", "v": "2013-05-16T09:53:00"}]}'
        response = self.testApp.get('/trajectory?from=nl.ut&to=nl.ehv&start=2013-05-16T09:00:00&span=1')
        self.assertEqual(expected, response.body)  # "FRS 4.2.1 TAPublic must publish a list with travel options")

        expected = '{"origin": "nl.ut", "options": [{"id": "nl.829", "v": "2013-05-16T09:08:00"}, {"id": "nl.831", "v": "2013-05-16T09:38:00"}]}'
        response = self.testApp.get('/departures?series=nl.008&dir=up&from=nl.ut&start=2013-05-16T09:00:00&span=1')
        self.assertEqual(expected, response.body, "FRS 4.2.4 TAPublic must publish a list with departure times: %s" % response.body)

        expected = '{"origin": "nl.ut", "options": [{"id": "nl.828", "v": "2013-05-16T09:55:00"}]}'
        response = self.testApp.get('/departures?series=nl.008&dir=down&from=nl.ut&start=2013-05-16T09:00:00&span=1')
        self.assertEqual(expected, response.body, "FRS 4.2.4 TAPublic must publish a list with departure times: %s" % response.body)

        expected = '{"id": "nl.828", "stops": []}'
        response = self.testApp.get('/mission?id=nl.828')
        self.assertEqual(expected, response.body)

        self.assertEqual(read_counter('req_trajectory'), 1)
        self.assertEqual(read_counter('req_mission'), 1)
        self.assertEqual(read_counter('req_departures'), 2)


text:
struct NDIlib_v3;

class FNdi
{
public:

	static const NDIlib_v3* Lib;

	static bool Initialize();
	static bool IsInitialized();
	static void Shutdown();

private:

	static void* LibHandle;
};


text:
using Content.Shared.Administration;
using Robust.Client.Console;
using Robust.Shared.ContentPack;
using Robust.Shared.Network;
using Robust.Shared.Utility;

namespace Content.Client.Administration.Managers
{
    public sealed class ClientAdminManager : IClientAdminManager, IClientConGroupImplementation, IPostInjectInit
    {
        [Dependency] private readonly IClientNetManager _netMgr = default!;
        [Dependency] private readonly IClientConGroupController _conGroup = default!;
        [Dependency] private readonly IResourceManager _res = default!;

        private AdminData? _adminData;
        private readonly HashSet<string> _availableCommands = new();

        private readonly AdminCommandPermissions _localCommandPermissions = new();

        public event Action? AdminStatusUpdated;

        public bool IsActive()
        {
            return _adminData?.Active ?? false;
        }

        public bool HasFlag(AdminFlags flag)
        {
            return _adminData?.HasFlag(flag) ?? false;
        }

        public bool CanCommand(string cmdName)
        {
            if (_adminData != null && _adminData.HasFlag(AdminFlags.Host))
            {
                // Host can execute all commands when connected.
                // Kind of a shortcut to avoid pains during development.
                return true;
            }

            if (_localCommandPermissions.CanCommand(cmdName, _adminData))
                return true;

            return _availableCommands.Contains(cmdName);
        }

        public bool CanViewVar()
        {
            return CanCommand("vv");
        }

        public bool CanAdminPlace()
        {
            return _adminData?.CanAdminPlace() ?? false;
        }

        public bool CanScript()
        {
            return _adminData?.CanScript() ?? false;
        }

        public bool CanAdminMenu()
        {
            return _adminData?.CanAdminMenu() ?? false;
        }

        public void Initialize()
        {
            _netMgr.RegisterNetMessage<MsgUpdateAdminStatus>(UpdateMessageRx);

            // Load flags for engine commands, since those don't have the attributes.
            if (_res.TryContentFileRead(new ResourcePath("/clientCommandPerms.yml"), out var efs))
            {
                _localCommandPermissions.LoadPermissionsFromStream(efs);
            }
        }

        private void UpdateMessageRx(MsgUpdateAdminStatus message)
        {
            _availableCommands.Clear();
            var host = IoCManager.Resolve<IClientConsoleHost>();

            // Anything marked as Any we'll just add even if the server doesn't know about it.
            foreach (var (command, instance) in host.RegisteredCommands)
            {
                if (Attribute.GetCustomAttribute(instance.GetType(), typeof(AnyCommandAttribute)) == null) continue;
                _availableCommands.Add(command);
            }

            _availableCommands.UnionWith(message.AvailableCommands);
            Logger.DebugS("admin", $"Have {message.AvailableCommands.Length} commands available");

            _adminData = message.Admin;
            if (_adminData != null)
            {
                var flagsText = string.Join("|", AdminFlagsHelper.FlagsToNames(_adminData.Flags));
                Logger.InfoS("admin", $"Updated admin status: {_adminData.Active}/{_adminData.Title}/{flagsText}");
            }
            else
            {
                Logger.InfoS("admin", "Updated admin status: Not admin");
            }

            AdminStatusUpdated?.Invoke();
            ConGroupUpdated?.Invoke();
        }

        public event Action? ConGroupUpdated;

        void IPostInjectInit.PostInject()
        {
            _conGroup.Implementation = this;
        }
    }
}


text:
<?php
namespace Xi\Fixtures;

class IncorrectUsageTest extends TestCase
{
    /**
     * @test
     */
    public function throwsWhenTryingToDefineTheSameEntityTwice()
    {
        $this->factory->define('SpaceShip');

        $self = $this;
        $this->assertThrows(function() use ($self) {
            $self->factory->define('SpaceShip');
        });
    }

    /**
     * @test
     */
    public function throwsWhenTryingToDefineEntitiesThatAreNotEvenClasses()
    {
        $self = $this;
        $this->assertThrows(function() use ($self) {
            $self->factory->define('NotAClass');
            $self->factory->get('NotAClass');
        });
    }

    /**
     * @test
     */
    public function throwsWhenTryingToDefineEntitiesThatAreNotEntities()
    {
        $this->assertTrue(class_exists('Xi\Fixtures\TestEntity\NotAnEntity', true));

        $self = $this;
        $this->assertThrows(function() use ($self) {
            $self->factory->define('NotAnEntity');
            $self->factory->get('NotAnEntity');
        });
    }

    /**
     * @test
     */
    public function throwsWhenTryingToDefineNonexistentFields()
    {
        $self = $this;
        $this->assertThrows(function() use ($self) {
            $self->factory->define('SpaceShip')
                ->field('pieType', 'blueberry');

            $self->factory->get('SpaceShip');
        });
    }

    /**
     * @test
     */
    public function throwsWhenTryingToGiveNonexistentFieldsWhileConstructing()
    {
        $this->factory->define('SpaceShip')
            ->field('name', 'Alpha');

        $self = $this;
        $this->assertThrows(function() use ($self) {
            $self->factory->get('SpaceShip', array(
                'pieType' => 'blueberry'
            ));
        });
    }

    /**
     * @test
     */
    public function throwsWhenTryingToGetFixtureThatIsNotDefined()
    {
        $self = $this;
        $this->assertThrows(function() use ($self) {
            $self->factory->get('Undefined');
        });
    }
}


text:
<mwl-demo-utils-calendar-header [(view)]="view" [(viewDate)]="viewDate">
</mwl-demo-utils-calendar-header>

<ng-template #customCellTemplate let-day="day" let-locale="locale">

     0"
      >{{ day.badgeTotal }}
    {{ day.date | calendarDate:'monthViewDayNumber':locale }}

      {{ group[1].length }}

</ng-template>

<ng-template
  #customEventTemplate
  let-weekEvent="weekEvent"
  let-tooltipPlacement="tooltipPlacement"
  let-eventClicked="eventClicked"
  let-tooltipTemplate="tooltipTemplate"
  let-tooltipAppendToBody="tooltipAppendToBody"
  let-tooltipDisabled="tooltipDisabled"
  let-tooltipDelay="tooltipDelay"
  let-column="column"
>
  <ng-template #groupedEventsTemplate>

        <mwl-calendar-event-actions [event]="event">
        </mwl-calendar-event-actions>
        &ngsp;
        <mwl-calendar-event-title [event]="event" view="week">
        </mwl-calendar-event-title>

  </ng-template>

  <div
    [ngbPopover]="groupedEventsTemplate"
    [disablePopover]="!weekEvent.event.meta.groupedEvents"
    class="cal-event"
    [ngStyle]="{
          backgroundColor: weekEvent.event.color?.secondary,
          borderColor: weekEvent.event.color?.primary
        }"
    [mwlCalendarTooltip]="
          !tooltipDisabled && !weekEvent.event.meta.groupedEvents
            ? (weekEvent.event.title
              | calendarEventTitle: 'weekTooltip':weekEvent.event)
            : ''
        "
    [tooltipPlacement]="tooltipPlacement"
    [tooltipEvent]="weekEvent.event"
    [tooltipTemplate]="tooltipTemplate"
    [tooltipAppendToBody]="tooltipAppendToBody"
    [tooltipDelay]="tooltipDelay"
    (mwlClick)="eventClicked.emit()"
  >
    <ng-container *ngIf="!weekEvent.event.meta.groupedEvents">
      <mwl-calendar-event-actions [event]="weekEvent.event">
      </mwl-calendar-event-actions>
      &ngsp;
    </ng-container>
    <mwl-calendar-event-title [event]="weekEvent.event" view="week">
    </mwl-calendar-event-title>

</ng-template>

  <mwl-calendar-month-view
    *ngSwitchCase="'month'"
    [viewDate]="viewDate"
    [events]="events"
    [cellTemplate]="customCellTemplate"
    (beforeViewRender)="beforeMonthViewRender($event)"
    [activeDayIsOpen]="true"
  >
  </mwl-calendar-month-view>
  <mwl-calendar-week-view
    *ngSwitchCase="'week'"
    [viewDate]="viewDate"
    [events]="groupedSimilarEvents"
    [eventTemplate]="customEventTemplate"
  >
  </mwl-calendar-week-view>
  <mwl-calendar-day-view
    *ngSwitchCase="'day'"
    [viewDate]="viewDate"
    [events]="groupedSimilarEvents"
    [eventTemplate]="customEventTemplate"
  >
  </mwl-calendar-day-view>


text:
'use strict'

AppServices.Controllers.controller('OrgCtrl', ['$scope', '$rootScope', 'ug', 'utility',
  function ($scope, $rootScope, ug,utility) {
    $scope.org = {};
    $scope.currentOrgPage = {};
    var createOrgsArray = function () {
      var orgs = [];
      for (var org in $scope.organizations) {
        orgs.push($scope.organizations[org]);
      }
      $scope.orgs = orgs;
      $scope.selectOrganization(orgs[0])
    }

    $scope.selectOrganization = function(org){
      org.usersArray = [];
      for(var user in org.users){
        org.usersArray.push(org.users[user]);
      }
      org.applicationsArray = [];
      for(var app in org.applications){
        org.applicationsArray.push({name:app.replace(org.name+'/',''),uuid:org.applications[app]});
      }
      $scope.selectedOrg =org;
      $scope.applyScope();
      return false;
    }

    $scope.addOrganization = function(modalId){
      $scope.hideModal(modalId);
      ug.addOrganization($rootScope.currentUser,$scope.org.name);
    }

    $scope.$on('user-add-org-success',function(evt,orgs){
      $scope.org = {};
      $scope.applyScope();
      ug.reAuthenticate($rootScope.userEmail,'org-reauthenticate');//call reauthenticate to refresh events

      $rootScope.$broadcast('alert', 'success', 'successfully added the new organization.');
    });

    $scope.$on('user-add-org-error',function(evt,data){
      $rootScope.$broadcast('alert', 'error', 'An error occurred attempting to add the organization.');
    });

    $scope.$on('org-reauthenticate-success',function(){
      createOrgsArray();
      $scope.applyScope();
    });

    $scope.doesOrgHaveUsers = function(org){
      var test =  org.usersArray.length > 1;
      return test;
    };

    $scope.leaveOrganization = function (org) {
      ug.leaveOrganization($rootScope.currentUser, org);
    };

    $scope.$on('user-leave-org-success', function (evt, orgs) {
      ug.reAuthenticate($rootScope.userEmail,'org-reauthenticate');//call reauthenticate to refresh events
      $rootScope.$broadcast('alert', 'success', 'User has left the selected organization(s).');
    });

    $scope.$on('user-leave-org-error',function(evt,data){
      $rootScope.$broadcast('alert', 'error', 'An error occurred attempting to leave the selected organization(s).');

    });
    createOrgsArray();

  }]
);


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
const core_1 = require('@angular/core');
const router_1 = require('@angular/router');
const Releve_1 = require("../../../model/Releve");
const CompteurService_1 = require("../../.././Services/CompteurService");
const ReleveService_1 = require("../../../Services/ReleveService");
let AddReleveComponent = class AddReleveComponent {
    constructor(route, router, cptService, relService) {
        this.route = route;
        this.router = router;
        this.cptService = cptService;
        this.relService = relService;
    }
    get openingAnimation() {
        return true;
    }
    get display() {
        return 'block';
    }
    get dateModel() {
        return this._dateModel;
    }
    set dateModel(date) {
        this._dateModel = date;
        this.releve.date = new Date(date.year, date.month - 1, date.day);
    }
    onChangeObj(newObj) {
        this.selectedCompteur = newObj;
    }
    formSubmit() {
        this.relService.add(this.releve)
            .subscribe((value) => {
            this.cancel();
        }, (error) => {
            alert(error);
        });
        // this.service.update(this.compteur).subscribe((value: Compteur) => {
        // 	this.gotoCompteurs(true);
        // }, (error) => {
        // 	alert(error);
        // });
    }
    cancel() {
        this.router.navigate(['/Releves']);
    }
    ngOnInit() {
        this.compteurs = this.cptService.getList();
        this.releve = new Releve_1.Releve();
        var newDate = new Date();
        this.dateModel = { day: newDate.getUTCDate(), month: newDate.getUTCMonth() + 1, year: newDate.getUTCFullYear() };
        this.relService.getByCompteur(1).subscribe(function (x) {
            console.log(JSON.stringify(x));
        });
        this.relService.getByCompteur(2).subscribe(function (x) {
            console.log(JSON.stringify(x));
        });
    }
    ngOnDestroy() {
    }
};
__decorate([
    core_1.HostBinding('@openingAnimation'),
    __metadata('design:type', Object)
], AddReleveComponent.prototype, "openingAnimation", null);
__decorate([
    core_1.HostBinding('style.display'),
    __metadata('design:type', Object)
], AddReleveComponent.prototype, "display", null);
AddReleveComponent = __decorate([
    core_1.Component({
        moduleId: module.id,
        selector: 'my-app',
        template: `

 Détails de votre relevé

	<form *ngIf="releve" (ngSubmit)="formSubmit()" >

			idCompteur
			<select [(ngModel)]="releve.idCompteur" (ngModelChange)="onChangeObj($event)" name="compteur" class="form-control">
				<option [ngValue]="i.idCompteur" *ngFor="let i of compteurs | async">{{i.name}}</option>
			</select>

		Date
			<ngb-datepicker name="date" [(ngModel)]="dateModel"></ngb-datepicker>

			Valeur
			<input name="valeur" type="number" required class="form-control" [(ngModel)]="releve.valeur" placeholder="Valeur">

			Commentaire
			<input name="commentaire" type="text" class="form-control" [(ngModel)]="releve.comment" placeholder="Commentaire">

			<input type="submit" class="btn btn-success" value="Valider"/>
			<input type="button" class="btn btn-default" value="Annuler" (click)="cancel()"/>

	</form>
	`,
        animations: [
            core_1.trigger('openingAnimation', [
                core_1.state('*', core_1.style({
                    opacity: 1,
                    transform: 'translateX(0)'
                })),
                core_1.transition('void => *', [
                    core_1.style({
                        opacity: 0,
                        transform: 'translateX(-100%)'
                    }),
                    core_1.animate('0.2s ease-in')
                ]),
                core_1.transition('* => void', [
                    core_1.animate('0.5s ease-out', core_1.style({
                        opacity: 0,
                        transform: 'translateY(100%)'
                    }))
                ])
            ])
        ]
    }),
    __param(2, core_1.Inject(CompteurService_1.CompteurService)),
    __param(3, core_1.Inject(ReleveService_1.ReleveService)),
    __metadata('design:paramtypes', [router_1.ActivatedRoute, router_1.Router, CompteurService_1.CompteurService, ReleveService_1.ReleveService])
], AddReleveComponent);
exports.AddReleveComponent = AddReleveComponent;
//# sourceMappingURL=releve.saisie.component.js.map


text:
using Microsoft.Extensions.Options;
using Smidge;
using Smidge.Cache;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Extensions;

namespace Umbraco.Cms.Web.Common.RuntimeMinification;

///
///     Constructs a cache buster string with sensible defaults.
///
/// <remarks>
///     <para>
///         Had planned on handling all of this in SmidgeRuntimeMinifier, but that only handles some urls.
///     </para>
///     <para>
///         A lot of the work is delegated e.g. to <see cref="SmidgeHelper.GenerateJsUrlsAsync(string, bool)" />
///         which doesn't care about the cache buster string in our classes only the value returned by the resolved
///         ICacheBuster.
///     </para>
///     <para>
///         Then I thought fine I'll just use a IConfigureOptions to tweak upstream <see cref="ConfigCacheBuster" />, but
///         that only cares about the <see cref="SmidgeConfig" />
///         class we instantiate and pass through in
///         <see cref="Umbraco.Extensions.UmbracoBuilderExtensions.AddRuntimeMinifier" />
///     </para>
///     <para>
///         So here we are, create our own to ensure we cache bust in a reasonable fashion.
///     </para>
///

///     <para>
///         Note that this class makes some other bits of code pretty redundant e.g.
///         <see cref="UrlHelperExtensions.GetUrlWithCacheBust" /> will
///         concatenate version with CacheBuster value and hash again, but there's no real harm so can think about that
///         later.
///     </para>
/// </remarks>
internal class UmbracoSmidgeConfigCacheBuster : ICacheBuster
{
    private readonly IEntryAssemblyMetadata _entryAssemblyMetadata;
    private readonly IOptions<RuntimeMinificationSettings> _runtimeMinificationSettings;
    private readonly IUmbracoVersion _umbracoVersion;

    private string? _cacheBusterValue;

    public UmbracoSmidgeConfigCacheBuster(
        IOptions<RuntimeMinificationSettings> runtimeMinificationSettings,
        IUmbracoVersion umbracoVersion,
        IEntryAssemblyMetadata entryAssemblyMetadata)
    {
        _runtimeMinificationSettings = runtimeMinificationSettings ??
                                       throw new ArgumentNullException(nameof(runtimeMinificationSettings));
        _umbracoVersion = umbracoVersion ?? throw new ArgumentNullException(nameof(umbracoVersion));
        _entryAssemblyMetadata =
            entryAssemblyMetadata ?? throw new ArgumentNullException(nameof(entryAssemblyMetadata));
    }

    private string CacheBusterValue
    {
        get
        {
            if (_cacheBusterValue != null)
            {
                return _cacheBusterValue;
            }

            // Assembly Name adds a bit of uniqueness across sites when version missing from config.
            // Adds a bit of security through obscurity that was asked for in standup.
            var prefix = _runtimeMinificationSettings.Value.Version ?? _entryAssemblyMetadata.Name;
            var umbracoVersion = _umbracoVersion.SemanticVersion.ToString();
            var downstreamVersion = _entryAssemblyMetadata.InformationalVersion;

            _cacheBusterValue = $"{prefix}_{umbracoVersion}_{downstreamVersion}".GenerateHash();

            return _cacheBusterValue;
        }
    }

    public string GetValue() => CacheBusterValue;
}


text: {{ include.username }}


text:
"use strict";

import Base from "./Base";

/**
 * The Blog resource
 *
 * @extends {Base}
 */
class Blog extends Base {
  constructor() {
    super("blog", {
      countable: true,
      createable: true,
      destroyable: true
    });
  }
}

/** @ignore */
export default new Blog();


text:
package com.example.office.data;

import java.io.Serializable;
import java.util.List;

import com.example.office.logger.Logger;
import com.example.office.utils.NetworkUtils;

/**
 * Implements mails configuration class. Stores list of {@link MailItem} received from the server and time when it was received.
 */
public class MailConfig implements Serializable {

    /**
     * Default UID for serializable class.
     */
    private static final long serialVersionUID = 4L;

    /**
     * Time, configuration was retrieved from server side.
     */
    private long mTimeStamp;

    /**
     * Valid SIM number for the configuration.
     */
    private String mSimNumber;

    /**
     * Notification mails.
     */
    private List<MailItem> mMailItems;

    /**
     * Creates new instance of the class.
     *
     * @param timeStamp Time stamp when application configuration was updated last time.
     */
    public MailConfig(long timeStamp) {
        mTimeStamp = timeStamp;
        mSimNumber = NetworkUtils.getCurrentSimCardNumber();
    }

    /**
     * Retrieves email with specified id (case matters!) if it exists.
     *
     * @param id Id of the email.
     *
     * @return {@linkplain MailItem} if one exists with specified id, null otherwise.
     */
    public MailItem getMailById(String id) {
        try {
            if (mMailItems == null || id == null) return null;
            for (MailItem mail : mMailItems) {
                if (mail != null && id.equals(mail.getId())) return mail;
            }
            return null;
        } catch (Exception e) {
            Logger.logApplicationException(e, getClass().getSimpleName() + ".getMailById(): Failed.");
        }
        return null;
    }

    /**
     * Updates email with specified id (case matters!) if it exists.
     *
     * @param id Id of the email.
     *
     * @return true if item with specified id exists and has been updated, null otherwise.
     */
    public boolean updateMailById(String id, MailItem newItem) {
        try {
            if (mMailItems == null || id == null) return false;
            for (int i = 0; i < mMailItems.size(); i++) {
                MailItem mail = mMailItems.get(i);
                if (mail != null && id.equals(mail.getId())) {
                    mMailItems.set(i, newItem);
                    return true;
                }
            }
        } catch (Exception e) {
            Logger.logApplicationException(e, getClass().getSimpleName() + ".getMailById(): Failed.");
        }
        return false;
    }

    /**
     * Removes email with specified id (case matters!) if it exists.
     * @param id Id of the email.
     */
    public void removeMailById(String id) {
        try {
            if (mMailItems == null || id == null) return;
            for (int i = 0; i < mMailItems.size(); i++) {
                MailItem mail = mMailItems.get(i);
                if (mail != null && id.equals(mail.getId())) {
                    mMailItems.remove(mail);
                    return;
                }
            }
        } catch (Exception e) {
            Logger.logApplicationException(e, getClass().getSimpleName() + ".getMailById(): Failed.");
        }
    }

    /**
     * Time configuration was retrieved from server side.
     *
     * @return Time, configuration was retrieved from server side.
     */
    public long getTimeStamp() {
        return mTimeStamp;
    }

    /**
     * Sets time configuration was retrieved from server side.
     *
     * @param timeStamp Time, configuration was retrieved from server side.
     */
    public void setTimeStamp(long timeStamp) {
        mTimeStamp = timeStamp;
    }

    /**
     * Retrieves valid SIM number for current configuration.
     *
     * @return Valid SIM number for current configuration.
     */
    public String getSimNumber() {
        return mSimNumber;
    }

    /**
     * Sets new mails.
     *
     * @param mails New mails.
     */
    public void setMails(List<MailItem> mails) {
        mMailItems = mails;
    }

    /**
     * Returns mails.
     *
     * @return mails.
     */
    public List<MailItem> getMails() {
        return mMailItems;
    }
}