text:
package com.jme3.network.kernel.tcp;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.channels.spi.SelectorProvider;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.jme3.network.Filter;
import com.jme3.network.kernel.*;

/**
 *  A Kernel implementation based on NIO selectors.
 *
 *  @version   $Revision: 7260 $
 *  @author    Paul Speed
 */
public class SelectorKernel extends AbstractKernel
{
    static Logger log = Logger.getLogger(SelectorKernel.class.getName());

    private InetSocketAddress address;
    private SelectorThread thread;

    private Map<Long,NioEndpoint> endpoints = new ConcurrentHashMap<Long,NioEndpoint>();

    public SelectorKernel( InetAddress host, int port )
    {
        this( new InetSocketAddress(host, port) );
    }

    public SelectorKernel( int port ) throws IOException
    {
        this( new InetSocketAddress(port) );
    }

    public SelectorKernel( InetSocketAddress address )
    {
        this.address = address;
    }

    protected SelectorThread createSelectorThread()
    {
        return new SelectorThread();
    }

    public void initialize()
    {
        if( thread != null )
            throw new IllegalStateException( "Kernel already initialized." );

        thread = createSelectorThread();

        try {
            thread.connect();
            thread.start();
        } catch( IOException e ) {
            throw new KernelException( "Error hosting:" + address, e );
        }
    }

    public void terminate() throws InterruptedException
    {
        if( thread == null )
            throw new IllegalStateException( "Kernel not initialized." );

        try {
            thread.close();
            thread = null;
        } catch( IOException e ) {
            throw new KernelException( "Error closing host connection:" + address, e );
        }
    }

    public void broadcast( Filter<? super Endpoint> filter, ByteBuffer data, boolean reliable,
                           boolean copy )
    {
        if( !reliable )
            throw new UnsupportedOperationException( "Unreliable send not supported by this kernel." );

        if( copy )
            {
            // Copy the data just once
            byte[] temp = new byte[data.remaining()];
            System.arraycopy(data.array(), data.position(), temp, 0, data.remaining());
            data = ByteBuffer.wrap(temp);
            }

        // Hand it to all of the endpoints that match our routing
        for( NioEndpoint p : endpoints.values() ) {
            // Does it match the filter?
            if( filter != null && !filter.apply(p) )
                continue;

            // Give it the data... but let each endpoint track their
            // own completion over the shared array of bytes by
            // duplicating it
            p.send( data.duplicate(), false, false );
        }

        // Wake up the selector so it can reinitialize its
        // state accordingly.
        wakeupSelector();
    }

    protected NioEndpoint addEndpoint( SocketChannel c )
    {
        // Note: we purposely do NOT put the key in the endpoint.
        //       SelectionKeys are dangerous outside the selector thread
        //       and this is safer.
        NioEndpoint p = new NioEndpoint( this, nextEndpointId(), c );

        endpoints.put( p.getId(), p );

        // Enqueue an endpoint event for the listeners
        addEvent( EndpointEvent.createAdd( this, p ) );

        return p;
    }

    protected void removeEndpoint( NioEndpoint p, SocketChannel c )
    {
        endpoints.remove( p.getId() );

        // Enqueue an endpoint event for the listeners
        addEvent( EndpointEvent.createRemove( this, p ) );

        // If there are no pending messages then add one so that the
        // kernel-user knows to wake up if it is only listening for
        // envelopes.
        if( !hasEnvelopes() ) {
            // Note: this is not really a race condition.  At worst, our
            // event has already been handled by now and it does no harm
            // to check again.
            addEnvelope( EVENTS_PENDING );
        }
    }

    /**
     *  Called by the endpoints when they need to be closed.
     */
    protected void closeEndpoint( NioEndpoint p ) throws IOException
    {
        log.log( Level.INFO, "Closing endpoint:{0}.", p );

        thread.cancel(p);
    }

    /**
     *  Used internally by the endpoints to wakeup the selector
     *  when they have data to send.
     */
    protected void wakeupSelector()
    {
        thread.wakeupSelector();
    }

    protected void newData( NioEndpoint p, SocketChannel c, ByteBuffer shared, int size )
    {
        // Note: if ever desirable, it would be possible to accumulate
        //       data per source channel and only 'finalize' it when
        //       asked for more envelopes then were ready.  I just don't
        //       think it will be an issue in practice.  The busier the
        //       server, the more the buffers will fill before we get to them.
        //       And if the server isn't busy, who cares if we chop things up
        //       smaller... the network is still likely to deliver things in
        //       bulk anyway.

        // Must copy the shared data before we use it
        byte[] dataCopy = new byte[size];
		System.arraycopy(shared.array(), 0, dataCopy, 0, size);

        Envelope env = new Envelope( p, dataCopy, true );
        addEnvelope( env );
    }

    /**
     *  This class is purposely tucked neatly away because
     *  messing with the selector from other threads for any
     *  reason is very bad.  This is the safest architecture.
     */
    protected class SelectorThread extends Thread
    {
        private ServerSocketChannel serverChannel;
        private Selector selector;
        private AtomicBoolean go = new AtomicBoolean(true);
        private ByteBuffer working = ByteBuffer.allocate( 8192 );

        /**
         *  Because we want to keep the keys to ourselves, we'll do
         *  the endpoint -> key mapping internally.
         */
        private Map<NioEndpoint,SelectionKey> endpointKeys = new ConcurrentHashMap<NioEndpoint,SelectionKey>();

        public SelectorThread()
        {
            setName( "Selector@" + address );
            setDaemon(true);
        }

        public void connect() throws IOException
        {
            // Create a new selector
            this.selector = SelectorProvider.provider().openSelector();

            // Create a new non-blocking server socket channel
            this.serverChannel = ServerSocketChannel.open();
            serverChannel.configureBlocking(false);

            // Bind the server socket to the specified address and port
            serverChannel.socket().bind(address);

            // Register the server socket channel, indicating an interest in
            // accepting new connections
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);

            log.log( Level.INFO, "Hosting TCP connection:{0}.", address );
        }

        public void close() throws IOException, InterruptedException
        {
            // Set the thread to stop
            go.set(false);

            // Make sure the channel is closed
            serverChannel.close();

            // And wait for it
            join();
        }

        protected void wakeupSelector()
        {
            selector.wakeup();
        }

        protected void setupSelectorOptions()
        {
            // For now, selection keys will either be in OP_READ
            // or OP_WRITE.  So while we are writing a buffer, we
            // will not be reading.  This is way simpler and less
            // error prone... it can always be changed when everything
            // else works if we are looking to micro-optimize.

            // Setup options based on the current state of
            // the endpoints.  This could potentially be more
            // efficiently done as change requests... or simply
            // keeping a thread-safe set of endpoints with pending
            // writes.  For most cases, it shouldn't matter.
            for( Map.Entry<NioEndpoint,SelectionKey> e : endpointKeys.entrySet() ) {
                if( e.getKey().hasPending() ) {
                    e.getValue().interestOps(SelectionKey.OP_WRITE);
                }
            }
        }

        protected void accept( SelectionKey key ) throws IOException
        {
            // Would only get accepts on a server channel
            ServerSocketChannel serverChan = (ServerSocketChannel)key.channel();

            // Setup the connection to be non-blocking
            SocketChannel remoteChan = serverChan.accept();
            remoteChan.configureBlocking(false);

            // And disable Nagle's buffering algorithm... we want
            // data to go when we put it there.
            Socket sock = remoteChan.socket();
            sock.setTcpNoDelay(true);

            // Let the selector know we're interested in reading
            // data from the channel
            SelectionKey endKey = remoteChan.register( selector, SelectionKey.OP_READ );

            // And now create a new endpoint
            NioEndpoint p = addEndpoint( remoteChan );
            endKey.attach(p);
            endpointKeys.put(p, endKey);
        }

        protected void cancel( NioEndpoint p ) throws IOException
        {
            log.log( Level.INFO, "Closing endpoint:{0}.", p );
            SelectionKey key = endpointKeys.remove(p);
            if( key == null ) {
                log.log( Level.INFO, "Endpoint already closed:{0}.", p );
                return;  // already closed it
            }

            SocketChannel c = (SocketChannel)key.channel();

            // Note: key.cancel() is specifically thread safe.  One of
            //       the few things one can do with a key from another
            //       thread.
            key.cancel();
            c.close();
            removeEndpoint( p, c );
        }

        protected void cancel( SelectionKey key, SocketChannel c ) throws IOException
        {
            NioEndpoint p = (NioEndpoint)key.attachment();
            log.log( Level.INFO, "Closing channel endpoint:{0}.", p );
            endpointKeys.remove(p);

            key.cancel();
            c.close();
            removeEndpoint( p, c );
        }

        protected void read( SelectionKey key ) throws IOException
        {
            NioEndpoint p = (NioEndpoint)key.attachment();
            SocketChannel c = (SocketChannel)key.channel();
            working.clear();

            int size;
            try {
                size = c.read(working);
            } catch( IOException e ) {
                // The remove end forcibly closed the connection...
                // close out our end and cancel the key
                cancel( key, c );
                return;
            }

            if( size == -1 ) {
                // The remote end shut down cleanly...
                // close out our end and cancel the key
                cancel( key, c );
                return;
            }

            newData( p, c, working, size );
        }

        protected void write( SelectionKey key ) throws IOException
        {
            NioEndpoint p = (NioEndpoint)key.attachment();
            SocketChannel c = (SocketChannel)key.channel();

            // We will send what we can and move on.
            ByteBuffer current = p.peekPending();
            if( current == NioEndpoint.CLOSE_MARKER ) {
                // This connection wants to be closed now
                closeEndpoint(p);

                // Nothing more to do
                return;
            }

            c.write( current );

            // If we wrote all of that packet then we need to remove it
            if( current.remaining() == 0 ) {
                p.removePending();
            }

            // If we happened to empty the pending queue then let's read
            // again.
            if( !p.hasPending() ) {
                key.interestOps( SelectionKey.OP_READ );
            }
        }

        protected void select() throws IOException
        {
            selector.select();

            for( Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext(); ) {
                SelectionKey key = i.next();
                i.remove();

                if( !key.isValid() )
                    {
                    // When does this happen?
                    log.log( Level.INFO, "Key is not valid:{0}.", key );
                    continue;
                    }

                try {
                    if( key.isAcceptable() )
                        accept(key);
                    else if( key.isWritable() )
                        write(key);
                    else if( key.isReadable() )
                        read(key);
                } catch( IOException e ) {
                    if( !go.get() )
                        return;  // error likely due to shutting down
                    reportError( e );

                    // And at this level, errors likely mean the key is now
                    // dead and it doesn't hurt to kick them anyway.  If we
                    // find IOExceptions that are not fatal, this can be
                    // readdressed
                    cancel( key, (SocketChannel)key.channel() );
                }
            }
        }

        public void run()
        {
            log.log( Level.INFO, "Kernel started for connection:{0}.", address );

            // An atomic is safest and costs almost nothing
            while( go.get() ) {
                // Setup any queued option changes
                setupSelectorOptions();

                // Check for available keys and process them
                try {
                    select();
                } catch( ClosedSelectorException e ) {
                    if( !go.get() )
                        return;  // it's because we're shutting down
                    throw new KernelException( "Premature selector closing", e );
                } catch( IOException e ) {
                    if( !go.get() )
                        return;  // error likely due to shutting down
                    reportError( e );
                }
            }
        }
    }
}


text:
package org.kie.workbench.common.dmn.client.widgets.grid.controls.container;

import java.util.Optional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import com.google.gwt.dom.client.BrowserEvents;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.RootPanel;
import org.jboss.errai.common.client.dom.Body;
import org.jboss.errai.common.client.dom.CSSStyleDeclaration;
import org.jboss.errai.common.client.dom.DOMUtil;
import org.jboss.errai.common.client.dom.Div;
import org.jboss.errai.common.client.dom.Document;
import org.jboss.errai.common.client.dom.Event;
import org.jboss.errai.common.client.dom.EventListener;
import org.jboss.errai.common.client.dom.HTMLElement;
import org.jboss.errai.common.client.ui.ElementWrapperWidget;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.kie.workbench.common.dmn.client.widgets.grid.controls.HasCellEditorControls;

@Templated
@ApplicationScoped
public class CellEditorControlsViewImpl implements CellEditorControlsView {

    private static final String CONTAINER_CLASS = "kie-dmn-cell-editor-controls";

    private static final String BOOTSTRAP_SELECT_CLASS = "bootstrap-select";

    private static final String BOOTSTRAP_SELECT_OPEN_CLASS = "open";

    @DataField("cellEditorControls")
    private Div cellEditorControls;

    @DataField("cellEditorControlsContainer")
    private Div cellEditorControlsContainer;

    private Body body;

    private EventListener hidePopoverHandler = event -> {
        if (!isOverCellEditorControlsContainer(event)) {
            hide();
        }
    };

    private Optional<HasCellEditorControls.Editor> activeEditor = Optional.empty();

    private Optional<ElementWrapperWidget<?>> elementWrapperWidget = Optional.empty();

    public CellEditorControlsViewImpl() {
        //CDI proxy
    }

    @Inject
    public CellEditorControlsViewImpl(final Document document,
                                      final Div cellEditorControls,
                                      final Div cellEditorControlsContainer) {
        this.cellEditorControls = cellEditorControls;
        this.cellEditorControlsContainer = cellEditorControlsContainer;
        this.body = document.getBody();
    }

    @PostConstruct
    public void setup() {
        this.cellEditorControls.setId(DOM.createUniqueId());

        this.elementWrapperWidget = Optional.of(getWidget());
        this.elementWrapperWidget.ifPresent(this::addWidgetToRootPanel);

        this.body.addEventListener(BrowserEvents.MOUSEDOWN,
                                   hidePopoverHandler,
                                   false);
        this.body.addEventListener(BrowserEvents.MOUSEWHEEL,
                                   hidePopoverHandler,
                                   false);
    }

    ElementWrapperWidget<?> getWidget() {
        return ElementWrapperWidget.getWidget(getElement());
    }

    @PreDestroy
    public void destroy() {
        this.elementWrapperWidget.ifPresent(this::removeWidgetFromRootPanel);

        this.body.removeEventListener(BrowserEvents.MOUSEDOWN,
                                      hidePopoverHandler,
                                      false);
        this.body.removeEventListener(BrowserEvents.MOUSEWHEEL,
                                      hidePopoverHandler,
                                      false);
    }

    void addWidgetToRootPanel(final ElementWrapperWidget<?> widget) {
        RootPanel.get().add(widget);
    }

    void removeWidgetFromRootPanel(final ElementWrapperWidget<?> widget) {
        RootPanel.get().remove(widget);
    }

    @Override
    public void show(final HasCellEditorControls.Editor<?> editor,
                     final Optional<String> editorTitle,
                     final int x,
                     final int y) {
        DOMUtil.removeAllChildren(cellEditorControlsContainer);
        cellEditorControlsContainer.appendChild(editor.getElement());

        final CSSStyleDeclaration style = getElement().getStyle();
        style.setProperty("left", x + "px");
        style.setProperty("top", y + "px");

        activeEditor = Optional.of(editor);

        editor.show(editorTitle);
    }

    @Override
    public void hide() {
        activeEditor.ifPresent(HasCellEditorControls.Editor::hide);
        activeEditor = Optional.empty();
    }

    private boolean isOverCellEditorControlsContainer(final Event event) {
        HTMLElement e = (HTMLElement) event.getTarget();
        while (e != null) {
            if (isOverCellEditorContainer(e)) {
                return true;
            }
            if (isOverBootstrapSelectContainer(e)) {
                return true;
            }
            e = (HTMLElement) e.getParentElement();
        }
        return false;
    }

    private boolean isOverCellEditorContainer(final HTMLElement e) {
        return e.getClassList().contains(CONTAINER_CLASS);
    }

    // This is a hack to check whether the Event occurred over an 'open' Bootstrap dropdown.
    // The dropdown content is added dynamically to the DOM when it is opened. If the dropdown container is set to the
    // CellEditorControlsView element the content is incorrectly positioned as it does not work in a parent element
    // that is absolutely positioned. If the dropdown container is set to body the CellEditorControlsView is not an
    // ancestor however content positioning works properly.
    private boolean isOverBootstrapSelectContainer(final HTMLElement e) {
        if (!e.getClassList().contains(BOOTSTRAP_SELECT_CLASS)) {
            return false;
        } else if (!e.getClassList().contains(BOOTSTRAP_SELECT_OPEN_CLASS)) {
            return false;
        }
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.accumulo.core.util.threads;

import static org.apache.accumulo.core.util.threads.AccumuloUncaughtExceptionHandler.isError;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.IOException;
import java.io.UncheckedIOException;

import org.junit.jupiter.api.Test;

public class AccumuloUncaughtExceptionHandlerTest {

  @Test
  public void testIsError_noerror() {
    assertFalse(isError(new IOException()));
    assertFalse(isError(new UncheckedIOException(new IOException())));

    Exception e = new UncheckedIOException(new IOException());
    e.addSuppressed(new RuntimeException());
    e.addSuppressed(new RuntimeException());
    assertFalse(isError(e));
  }

  @Test
  public void testIsError_error() {
    assertTrue(isError(new UnsatisfiedLinkError()));
    assertTrue(isError(new RuntimeException(new OutOfMemoryError())));
    assertTrue(isError(new RuntimeException(new RuntimeException(new UnsatisfiedLinkError()))));

    // check for cases where error has a non-error cause
    assertTrue(isError(new Error(new RuntimeException())));
    assertTrue(isError(new RuntimeException(new Error(new RuntimeException()))));
    assertTrue(
        isError(new RuntimeException(new RuntimeException(new Error(new RuntimeException())))));

    // check for suppressed exception that has error
    Exception e = new UncheckedIOException(new IOException());
    e.addSuppressed(new RuntimeException());
    e.addSuppressed(new RuntimeException());
    e.addSuppressed(new RuntimeException(new UnsatisfiedLinkError()));
    assertTrue(isError(e));
    assertTrue(isError(new RuntimeException(e)));

    // check for suppressed exception that has non terminal error
    Exception e2 = new UncheckedIOException(new IOException());
    e2.addSuppressed(new RuntimeException());
    e2.addSuppressed(new RuntimeException());
    e2.addSuppressed(new RuntimeException(new Error(new RuntimeException())));
    assertTrue(isError(e2));
    assertTrue(isError(new RuntimeException(e2)));

    // test suppressed with error a few levels deep
    Exception ed1 = new UncheckedIOException(new IOException());
    Exception ed2 = new UncheckedIOException(new IOException());
    Exception ed3 = new RuntimeException(new OutOfMemoryError());
    ed1.addSuppressed(ed2);
    ed2.addSuppressed(ed3);
    assertTrue(isError(ed1));
    assertTrue(isError(new RuntimeException(ed1)));

    // test case where suppressed is an error
    Exception e4 = new UncheckedIOException(new IOException());
    e4.addSuppressed(new RuntimeException());
    e4.addSuppressed(new RuntimeException());
    e4.addSuppressed(new Error(new RuntimeException())); // try direct error (not nested as cause)
    assertTrue(isError(e4));
    assertTrue(isError(new RuntimeException(e4)));
  }

  @Test
  public void testIsError_loop() {
    Exception e1 = new UncheckedIOException(new IOException());
    Exception e2 = new RuntimeException(new RuntimeException());
    Exception e3 = new IllegalStateException();

    // create a chain of suppressed exceptions that forms a loop
    e1.addSuppressed(e2);
    e2.addSuppressed(e3);
    e3.addSuppressed(e1);

    assertFalse(isError(e1));
    assertFalse(isError(new RuntimeException(e1)));
  }
}


text:
<?php

namespace app\models;

use Yii;

use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;

/**
 * This is the model class for table "tbl_penyertaan_sukan_pegawai".
 *
 * @property integer $penyertaan_sukan_pegawai_id
 * @property integer $penyertaan_sukan_id
 * @property string $nama
 * @property string $jawatan
 */
class PenyertaanSukanPegawai extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_penyertaan_sukan_pegawai';
    }

    public function behaviors()
    {
        return [
            'bedezign\yii2\audit\AuditTrailBehavior',
            [
                'class' => \yii\behaviors\BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'createdAtAttribute' => 'created',
                'updatedAtAttribute' => 'updated',
                'value' => new \yii\db\Expression('NOW()'),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['nama'], 'required', 'skipOnEmpty' => true, 'message' => GeneralMessage::yii_validation_required],
            [['penyertaan_sukan_id'], 'integer', 'message' => GeneralMessage::yii_validation_integer],
            [['nama', 'jawatan'], 'string', 'max' => 255, 'tooLong' => GeneralMessage::yii_validation_string_max],
            [['nama','jawatan'], function ($attribute, $params) {
                if (!\common\models\general\GeneralFunction::validateXSS($this->$attribute)) {
                    $this->addError($attribute, GeneralMessage::yii_validation_xss);
                }
            }],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'penyertaan_sukan_pegawai_id' => GeneralLabel::id,
            'penyertaan_sukan_id' => GeneralLabel::penyertaan_sukan_id,
            'nama' => GeneralLabel::nama,
            'jawatan' => GeneralLabel::jawatan,
        ];
    }
}


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Sergey Lisitsyn, Heiko Strathmann, Soeren Sonnenburg,
 *          Evan Shelhamer
 */

#ifndef LAPLACIANEIGENMAPS_H_
#define LAPLACIANEIGENMAPS_H_
#include <shogun/lib/config.h>
#include <shogun/converter/EmbeddingConverter.h>
#include <shogun/features/Features.h>
#include <shogun/distance/Distance.h>

namespace shogun
{

class Features;
class Distance;

/** @brief class LaplacianEigenmaps used to construct embeddings of
 * data using Laplacian Eigenmaps algorithm as described in:
 *
 * Belkin, M., & Niyogi, P. (2002).
 * Laplacian Eigenmaps and Spectral Techniques for Embedding and Clustering.
 * Science, 14, 585-591. MIT Press.
 * Retrieved from http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.19.9400&rep=rep1&type=pdf
 *
 * Uses implementation from the Tapkee library.
 *
 * To use this converter with static interfaces please refer it by
 * sg('create_converter','laplacian_eigenmaps',k,width);
 *
 */
class LaplacianEigenmaps: public EmbeddingConverter
{
public:

	/** constructor */
	LaplacianEigenmaps();

	/** destructor */
	virtual ~LaplacianEigenmaps();

	/** apply to features
	 * @param features to embed
	 * @return embedded features
	 */
	virtual std::shared_ptr<Features> transform(std::shared_ptr<Features> features, bool inplace = true);

	/** embed distance
	 * @param distance to use for embedding
	 */
	virtual std::shared_ptr<DenseFeatures<float64_t>> embed_distance(std::shared_ptr<Distance> distance);

	/** setter for K parameter
	 * @param k k value
	 */
	void set_k(int32_t k);

	/** getter for K parameter
	 * @return k value
	 */
	int32_t get_k() const;

	/** setter for TAU parameter
	 * @param tau tau value
	 */
	void set_tau(float64_t tau);

	/** getter for TAU parameter
	 * @return tau value
	 */
	float64_t get_tau() const;

	/** get name */
	virtual const char* get_name() const;

protected:

	/** init */
	void init();

protected:

	/** number of neighbors */
	int32_t m_k;

	/** tau parameter of heat distribution */
	float64_t m_tau;

};
}

#endif /* LAPLACIANEIGENMAPS_H_ */


text:
'use strict'

const db = require('APP/db')
const User = db.model('users')

const { mustBeLoggedIn } = require('./auth.filters')

module.exports = require('express').Router()
  .get('/',
  // The forbidden middleware will fail *all* requests to list users.
  // Remove it if you want to allow anyone to list all users on the site.
  //
  // If you want to only let admins list all the users, then you'll
  // have to add a role column to the users table to support
  // the concept of admin users.
  // forbidden('listing users is not allowed'),
  (req, res, next) =>
    User.findAll()
      .then(users => res.json(users))
      .catch(next))

  .post('/',
  (req, res, next) =>
    User.create(req.body)
      .then(user => res.status(201).json(user))
      .catch(next))

  .get('/:id',
  mustBeLoggedIn,
  (req, res, next) =>
    User.findById(req.params.id)
      .then(user => res.json(user))
      .catch(next))


text:
<?xml version="1.0" encoding="UTF-8"?>
<project
  xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>

  <modelVersion>4.0.0</modelVersion>
  <packaging>jar</packaging>

  <artifactId>lichkin-springboot-starter-sc</artifactId>

  <parent>
    <groupId>com.lichkin</groupId>
    <artifactId>lichkin-springboot-parent</artifactId>
    <version>1.1.0-RELEASE</version>
    <relativePath>../../lichkin-springboot-parent</relativePath>
  </parent>

  <dependencies>
    <!-- lichkin framework -->
    <dependency>
      <groupId>com.lichkin</groupId>
      <artifactId>lichkin-springboot-starter-database</artifactId>
    </dependency>
    <dependency>
      <groupId>com.lichkin</groupId>
      <artifactId>lichkin-springboot-entities-sc</artifactId>
    </dependency>
  </dependencies>

</project>


text:
package com.itwheel.edigate.invrpt.processor;

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

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class PrepSqlParamInvrptRetailProc implements Processor {

	public void process(Exchange exchange) throws Exception {

		Date lastStartDte =
				(Date)exchange.getIn().getHeader("invrpt_last_start_dte");
		Date startDte =
				(Date)exchange.getIn().getHeader("invrpt_start_dte");
		List params = new ArrayList();
		params.add(lastStartDte);
		params.add(startDte);

		exchange.getOut().setHeaders(exchange.getIn().getHeaders());
		exchange.getOut().setBody(params);
	}

}


text:
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
  double val2;
  int val, decimal;
  char dot = '.';

  cout << "Welcome to the wondrous decimal-value rounding program!" << endl;
  cout << "Unfortunately though, due to the economy, you only get three chances to round." << endl;
  cout << "Enter in a decimal value to be rounded: ";
  cin >> val >> dot >> decimal; //scan for the integer, the dot in between, and the decimal

  if (dot == '.') //if the input was a decimal
  {
    val2 = (val >= 0) ? (val + (decimal * .1)) : (val - (decimal * .1)); //set val2 as the decimal value
                                                                         //where if val is positive,
                                                                         //val2 = val + the decimal (in
                                                                         //proper place); else, then
                                                                         //val2 = val - the decimal (in
                                                                         //its proper place)
    val = static_cast<int>(val2 >= 0 ? val2 + 0.5 : val2 - 0.5); //rounding done here
    cout << "Your input rounded is: " << val << endl; //output new, rounded value
  }
  else
  {
    cout << "Invalid input." << endl;
  }
  cout << "Two more tries..." << endl;

  cout << "Enter in a decimal value to be rounded: ";
  cin >> val >> dot >> decimal; //scan for the integer, the dot in between, and the decimal

  if (dot == '.') //if the input was a decimal
  {
    val2 = (val >= 0) ? (val + (decimal * .1)) : (val - (decimal * .1)); //set val2 as the decimal value
                                                                         //(same as first)
    val = static_cast<int>(val2 >= 0 ? val2 + 0.5 : val2 - 0.5); //rounding done here
    cout << "Your input rounded is: " << val << endl; //output new, rounded value
  }
  else
  {
    cout << "Invalid input." << endl;
  }
  cout << "One more try..." << endl;

  cout << "Enter in a decimal value to be rounded: ";
  cin >> val >> dot >> decimal; //scan for the integer, the dot in between, and the decimal

  if (dot == '.') //if the input was a decimal
  {
    val2 = (val >= 0) ? (val + (decimal * .1)) : (val - (decimal * .1)); //set val2 as the decimal value
                                                                         //(same as first)
    val = static_cast<int>(val2 >= 0 ? val2 + 0.5 : val2 - 0.5); //rounding done here
    cout << "Your input rounded is: " << val << endl; //output new, rounded value
  }
  else
  {
    cout << "Invalid input." << endl;
  }

  cout << "No more tries. Thanks for using this program!" << endl;

  //lazy way to do this

	return 0;
}


text:
using Aurora.Settings.Layers;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace Aurora.Controls {

    /// <summary>
    /// A control that is capable of rendering the preview of any layer that correctly implements <see cref="INotifyRender"/>.
    /// </summary>
    public partial class Control_LayerPreview : UserControl {

        private bool eventsAttached;

        public Control_LayerPreview() {
            InitializeComponent();
        }

        #region Target Layer Property
        public INotifyRender TargetLayer {
            get => (INotifyRender)GetValue(TargetLayerProperty);
            set => SetValue(TargetLayerProperty, value);
        }
        public static readonly DependencyProperty TargetLayerProperty =
            DependencyProperty.Register("TargetLayer", typeof(INotifyRender), typeof(Control_LayerPreview), new PropertyMetadata(null, TargetLayerChanged));

        private static void TargetLayerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
            var control = (Control_LayerPreview)d;
            // If the events are currently attached (I.E. a preview is currently running, then remove the handler from the old target and add to the new one)
            if (control.eventsAttached) {
                if (e.OldValue is INotifyRender old)
                    old.LayerRender -= control.RenderLayerPreview;
                if (e.NewValue is INotifyRender @new)
                    @new.LayerRender += control.RenderLayerPreview;
            }
        }
        #endregion

        // Start listening for when the particle layer is rendered so we can update the preview
        private void UserControl_Loaded(object sender, RoutedEventArgs e) {
            if (TargetLayer != null)
                TargetLayer.LayerRender += RenderLayerPreview;
            eventsAttached = true;
        }

        // Stop listenting for when the particle layer is rendered (since you can't see the image now anyways)
        private void UserControl_Unloaded(object sender, RoutedEventArgs e) {
            if (TargetLayer != null)
                TargetLayer.LayerRender -= RenderLayerPreview;
            eventsAttached = false;
        }

        // Take the bitmap from the layer and transform it into a format that can be used by WPF
        private void RenderLayerPreview(object sender, System.Drawing.Bitmap bitmap) =>
            Dispatcher.Invoke(delegate {
                using (var ms = new MemoryStream()) {
                    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    ms.Position = 0;
                    var bitmapImg = new BitmapImage();
                    bitmapImg.BeginInit();
                    bitmapImg.StreamSource = ms;
                    bitmapImg.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImg.EndInit();
                    imagePreview.Source = bitmapImg;
                }
            });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ASMIdeaPluginConfiguration">
    <asm skipDebug="false" skipFrames="false" skipCode="false" expandFrames="false" />
    <groovy codeStyle="LEGACY" />
  </component>
  <component name="ASMPluginConfiguration">
    <asm skipDebug="false" skipFrames="false" skipCode="false" expandFrames="false" />
    <groovy codeStyle="LEGACY" />
  </component>
  <component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="Sireum-dev" project-jdk-type="IDEA JDK">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
</project>


text:
<?php
/* @var $this MatriculaController */
/* @var $model Matricula */

$this->breadcrumbs=array(
	'Matriculas'=>array('index'),
	'Manage',
);

$this->menu=array(
	array('label'=>'List Matricula', 'url'=>array('index')),
	array('label'=>'Create Matricula', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$('#matricula-grid').yiiGridView('update', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

Manage Matriculas

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<?php $this->renderPartial('_search',array(
	'model'=>$model,
)); ?>

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'matricula-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'IDMATRICULA',
		'CODMATRICULA',
		'IDCURSO_PROG',
		'IDALUMNO',
		'FEC_MATRICULA',
		'FECHAREGISTRO',
		/*
		'ESTADO',
		*/
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>


text:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import time
import tqdm
import scrapy
from Global_function import get_localtime, print_new_number, save_messages

now_time = get_localtime(time.strftime("%Y-%m-%d", time.localtime()))
now_time = 20100101
end_time = 20170101

class NPU001_Spider(scrapy.Spider):
	name = 'NPU001'
	start_urls = ['http://jsj.nwpu.edu.cn/index/xueshu.htm']
	domain = 'http://jsj.nwpu.edu.cn/'
	counts = 0

	def parse(self, response):
		messages = response.xpath("//table[@class='winstyle54630']").xpath(".//tr[@height='26']")

		for i in xrange(len(messages)):
			report_name = messages[i].xpath(".//td")[0].xpath(".//a/text()").extract()[0]
			if u'学术报告' not in report_name:
				continue

			report_url = self.domain + messages[i].xpath(".//td")[0].xpath(".//a/@href").extract()[0][3:]
			report_time = get_localtime(messages[i].xpath(".//td")[1].xpath(".//span/text()").extract()[0].strip().replace('/', '-'))

			if report_time > end_time:
				continue
			if report_time < now_time:
				return

			yield scrapy.Request(report_url, callback=self.parse_pages, meta={'link': report_url, 'number': i + 1})
			# return

		now_number = int(response.xpath("//tr[@valign='middle']/td/text()").extract()[0].strip().split('/')[0][-1])
		last_number = int(response.xpath("//tr[@valign='middle']/td/text()").extract()[0].strip().split('/')[-1])
		# print now_number

		# if now_number >= last_number:
		# 	return
		#
		# next_url = 'http://jsj.nwpu.edu.cn/index/xueshu/{}.htm'.format(last_number - now_number + 1)
		# # print next_url
		# yield scrapy.Request(next_url, callback=self.parse)

	def parse_pages(self, response):
		messages = response.xpath("//div[@id='vsb_content']/p")

		sign = 1
		title, time, address, speaker, person_introduce, content = '', '', '', '', '', ''
		for message in messages:
			text = self.get_messages(message)
			if u'题目:' in text or u'题目:' in text:
				title = self.connect_message(text, ':') if  u'题目:' in text else self.connect_message(text, ':')
			elif u'主持人' in text:
				continue
			elif u'时间:' in text or u'时间:' in text:
				time = self.connect_message(text, ':') if  u'时间:' in text else self.connect_message(text, ':')
			elif u'地点:' in text or u'地点:' in text:
				address = self.connect_message(text, ':') if  u'地点:' in text else self.connect_message(text, ':')
			elif u'报告人:' in text or u'报告人:' in text:
				speaker = self.connect_message(text, ':') if  u'报告人:' in text else self.connect_message(text, ':')
			elif u'简介:' in text or u'简介:' in text:
				sign = 1
				person_introduce = self.connect_message(text, ':') if  u'题目:' in text else self.connect_message(text, ':')
			elif u'摘要:' in text or u'摘要:' in text:
				sign = 2
				content = self.connect_message(text, ':') if  u'题目:' in text else self.connect_message(text, ':')
			else:
				if sign == 1:
					person_introduce += text
				elif sign == 2:
					content += text

		if title != '':
			self.counts += 1
			print_new_number(self.counts, 'NPU', self.name)

		all_messages = save_messages('NPU', self.name, title, time, address, speaker, person_introduce,
		                             content, '', response.meta['link'], response.meta['number'], u'西北工业大学', u'计算机学院')

		return all_messages

	def get_messages(self, messages):
		all_text = messages.xpath(".//text()").extract()
		texts = ''
		for text in all_text:
			texts += text.strip()
		return texts

	def connect_message(self, message, sign):
		ans = ''
		message = message.split(sign)[1:]
		for i in range(len(message)):
			if i > 0:
				ans += ':'
			ans += message[i].strip()
		return ans


text:
import * as api from "./api";
export { connect } from "./connect";
import * as apiInterface from "./interfaces/api/api";
import * as contact from "./interfaces/api/contact";
import * as conversation from "./interfaces/api/conversation";
export declare type Api = api.Api;
export declare namespace Api {
    type NewMessage = apiInterface.NewMessage;
    type SendMessageResult = apiInterface.SendMessageResult;
}
export declare type Contact = contact.Contact;
export declare namespace Contact {
    type Phone = contact.Phone;
    type Location = contact.Location;
}
export declare type Conversation = conversation.Conversation;
export declare namespace Conversation {
    type ThreadProperties = conversation.ThreadProperties;
}


text:
NSString * const HOUR_OF_DAY_KEY		= @"hourOfDay";
NSString * const MINUTE_KEY				= @"minute";
NSString * const SCHEDULE_GROUP			= @"ScheduleSet1";
NSString * const INDEX_TAG				= @"indexTag";
NSString * const MONDAY					= @"MONDAY";
NSString * const TUESDAY				= @"TUESDAY";
NSString * const WEDNESDAY				= @"WEDNESDAY";
NSString * const THURSDAY				= @"THURSDAY";
NSString * const FRIDAY					= @"FRIDAY";
NSString * const SATURDAY				= @"SATURDAY";
NSString * const SUNDAY					= @"SUNDAY";

@interface ViewController () <SCLRTimeSelectorDelegate>

@property (nonatomic, readonly) SCLRSAManager *scheduleMgr;
@property (nonatomic, readonly) NSArray *schedules;

@property (nonatomic) NSArray* scheduleRows;

@property (nonatomic) BOOL initializing;

- (void)setupViews;
- (void)initializeViews;
- (void)loadDefaultValues;
- (void)initializeScheduleRowViews:(int)index withSchedule:(NSObject<SCLRScheduleState> *)schedule;
- (void)setFromAndToTime:(int)index withStartTime:(NSDate *)startTime andDuration:(int)duration;
- (void)setTextAndTagOnTimeView:(UIButton *)timeView usingTime:(NSDate *)time;
- (void)setScheduleRowEnabled:(int)index withState:(BOOL)enable;
- (void)setStateOnOrOff:(int)index forSchedule:(NSObject<SCLRScheduleState>*)schedState;
- (NSString *)getDayTag:(int)calendarDayOfWeek;

@end

@implementation ViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
	_scheduleMgr = [SCLRSAManager sharedInstance];
	[_scheduleMgr setCallback:self forceReplace:YES];

	self.initializing = YES;
	[self setupViews];
	[self initializeViews];
	self.initializing = NO;
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

// Implementation of the SAMCallback protocol
-(void)onScheduleStateChange:(NSMapTable *)changedSchedules appInBackground:(BOOL)backgroud {
	// If the app is running in the background, don't update the views
	if (backgroud) {
		return;
	}

	NSEnumerator *changedSchedulesEnum = [changedSchedules objectEnumerator];
	NSObject<SCLRScheduleState> *schedState = [changedSchedulesEnum nextObject];
	while (schedState != nil) {
		NSString * tag = [schedState getTag];
		if ([tag isEqualToString:MONDAY]) {
			[self setStateOnOrOff:0 forSchedule:schedState];
		} else if ([tag isEqualToString:TUESDAY]) {
			[self setStateOnOrOff:1 forSchedule:schedState];
		} else if ([tag isEqualToString:WEDNESDAY]) {
			[self setStateOnOrOff:2 forSchedule:schedState];
		} else if ([tag isEqualToString:THURSDAY]) {
			[self setStateOnOrOff:3 forSchedule:schedState];
		} else if ([tag isEqualToString:FRIDAY]) {
			[self setStateOnOrOff:4 forSchedule:schedState];
		} else if ([tag isEqualToString:SATURDAY]) {
			[self setStateOnOrOff:5 forSchedule:schedState];
		} else if ([tag isEqualToString:SUNDAY]) {
			[self setStateOnOrOff:6 forSchedule:schedState];
		}

		schedState = [changedSchedulesEnum nextObject];
	}

	// Next alarm details
	NSDate* nextAlarmTime = [_scheduleMgr getTimeForNextAlarm];
	if (nextAlarmTime != nil) {
		NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
		[formatter setDateStyle:NSDateFormatterShortStyle];
		[formatter setTimeStyle:NSDateFormatterShortStyle];

		self.nextAlarmLbl.text = [formatter stringFromDate:nextAlarmTime];
	} else {
		self.nextAlarmLbl.text = @"<None>";
	}
}

- (IBAction)schedStateChanged:(UISwitch *)sender forEvent:(UIEvent *)event {
	int index = [(NSNumber *)[sender.layer valueForKey:INDEX_TAG] intValue];
	[self setScheduleRowEnabled:index withState:sender.on];
}

- (IBAction)fromTimePressed:(UIButton *)sender {
	// Launch time selector to choose the time
	int hour = [(NSNumber *)[sender.layer valueForKey:HOUR_OF_DAY_KEY] intValue];
	int minute = [(NSNumber *)[sender.layer valueForKey:MINUTE_KEY] intValue];

	SCLRTimeSelector* timeSelector = [[SCLRTimeSelector alloc]
									  initWithSuperView:self.view
									  withDelegate:(NSObject<SCLRTimeSelectorDelegate> *)self
									  initialHour:hour
									  initialMinute:minute
									  andUserData:sender];

	[self.view addSubview:timeSelector];
}

- (IBAction)toTimePressed:(UIButton *)sender {
	// Launch time selector to choose the time
	int hour = [(NSNumber *)[sender.layer valueForKey:HOUR_OF_DAY_KEY] intValue];
	int minute = [(NSNumber *)[sender.layer valueForKey:MINUTE_KEY] intValue];

	SCLRTimeSelector* timeSelector = [[SCLRTimeSelector alloc]
									  initWithSuperView:self.view
									  withDelegate:(NSObject<SCLRTimeSelectorDelegate> *)self
									  initialHour:hour
									  initialMinute:minute
									  andUserData:sender];

	[self.view addSubview:timeSelector];
}

// Implementation of TimeChooserCallback delegate
- (void)timeSelected:(NSDate *)date withHours:(int)hours
		  andMinutes:(int) minutes forUserData:(id)userData {
	NSLog(@"timeSelected callback called with %d hours and %d minutes", hours, minutes);

	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateStyle:NSDateFormatterNoStyle];
	[formatter setTimeStyle:NSDateFormatterShortStyle];

	UIButton *button = (UIButton *)userData;
	[button setTitle:[formatter stringFromDate:date] forState:UIControlStateNormal];
	[button.layer setValue:[NSNumber numberWithInt:hours] forKey:HOUR_OF_DAY_KEY];
	[button.layer setValue:[NSNumber numberWithInt:minutes] forKey:MINUTE_KEY];

	// TODO: After the change is made, the next thing will be to recompute the schedule state

	int index = [((NSNumber *)[button.layer valueForKey:INDEX_TAG]) intValue];
	ScheduleRowViews * row = (ScheduleRowViews *)self.scheduleRows[index];

	NSCalendar *calendar = [NSCalendar currentCalendar];

	NSCalendarUnit currDayUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
	NSDateComponents *startTimeComponents = [calendar components:currDayUnits fromDate:[row.schedule getStartTime]];
	[startTimeComponents setHour:[((NSNumber *)[row.sch_from.layer valueForKey:HOUR_OF_DAY_KEY]) intValue]];
	[startTimeComponents setMinute:[((NSNumber *)[row.sch_from.layer valueForKey:MINUTE_KEY]) intValue]];
	NSDate *startTime = [calendar dateFromComponents:startTimeComponents];

	NSDateComponents *stopTimeComponents = [[NSDateComponents alloc] init];
	[stopTimeComponents setHour:[((NSNumber *)[row.sch_to.layer valueForKey:HOUR_OF_DAY_KEY]) intValue]];
	[stopTimeComponents setMinute:[((NSNumber *)[row.sch_to.layer valueForKey:MINUTE_KEY]) intValue]];
	[stopTimeComponents setYear:startTimeComponents.year];
	[stopTimeComponents setMonth:startTimeComponents.month];
	[stopTimeComponents setDay:startTimeComponents.day];
	NSDate *stopTime = [calendar dateFromComponents:stopTimeComponents];

	// We are passing in REPEAT_TYPE_DAILY in order to correctly calculate the duration on a
	// 24-hour period. Our schedules are actually weekly schedules.
	int duration = [_scheduleMgr getDuration:startTime stopTime:stopTime repeating:REPEAT_TYPE_DAILY];
	[_scheduleMgr updateSchedule:row.schedule newStartTime:startTime withDuration:duration];
}

- (void)setupViews {
	ScheduleRowViews* mondayRow = [[ScheduleRowViews alloc] init];
	mondayRow.sch_day = self.sch_day1;
	mondayRow.sch_from = self.sch_from1;
	mondayRow.sch_to = self.sch_to1;
	mondayRow.sch_enable = self.sch_enable1;
	mondayRow.sch_state = self.sch_state1;

	ScheduleRowViews* tuesdayRow = [[ScheduleRowViews alloc] init];
	tuesdayRow.sch_day = self.sch_day2;
	tuesdayRow.sch_from = self.sch_from2;
	tuesdayRow.sch_to = self.sch_to2;
	tuesdayRow.sch_enable = self.sch_enable2;
	tuesdayRow.sch_state = self.sch_state2;

	ScheduleRowViews* wednesdayRow = [[ScheduleRowViews alloc] init];
	wednesdayRow.sch_day = self.sch_day3;
	wednesdayRow.sch_from = self.sch_from3;
	wednesdayRow.sch_to = self.sch_to3;
	wednesdayRow.sch_enable = self.sch_enable3;
	wednesdayRow.sch_state = self.sch_state3;

	ScheduleRowViews* thursdayRow = [[ScheduleRowViews alloc] init];
	thursdayRow.sch_day = self.sch_day4;
	thursdayRow.sch_from = self.sch_from4;
	thursdayRow.sch_to = self.sch_to4;
	thursdayRow.sch_enable = self.sch_enable4;
	thursdayRow.sch_state = self.sch_state4;

	ScheduleRowViews* fridayRow = [[ScheduleRowViews alloc] init];
	fridayRow.sch_day = self.sch_day5;
	fridayRow.sch_from = self.sch_from5;
	fridayRow.sch_to = self.sch_to5;
	fridayRow.sch_enable = self.sch_enable5;
	fridayRow.sch_state = self.sch_state5;

	ScheduleRowViews* saturdayRow = [[ScheduleRowViews alloc] init];
	saturdayRow.sch_day = self.sch_day6;
	saturdayRow.sch_from = self.sch_from6;
	saturdayRow.sch_to = self.sch_to6;
	saturdayRow.sch_enable = self.sch_enable6;
	saturdayRow.sch_state = self.sch_state6;

	ScheduleRowViews* sundayRow = [[ScheduleRowViews alloc] init];
	sundayRow.sch_day = self.sch_day7;
	sundayRow.sch_from = self.sch_from7;
	sundayRow.sch_to = self.sch_to7;
	sundayRow.sch_enable = self.sch_enable7;
	sundayRow.sch_state = self.sch_state7;

	self.scheduleRows = @[mondayRow, tuesdayRow, wednesdayRow, thursdayRow,
						  fridayRow, saturdayRow, sundayRow];

}

- (void)initializeViews {
	NSSet * scheduleStates = [_scheduleMgr getScheduleStatesByGroupTag:SCHEDULE_GROUP];

	if ([scheduleStates count] < 7) {
		[self loadDefaultValues];
		scheduleStates = [_scheduleMgr getScheduleStatesByGroupTag:SCHEDULE_GROUP];
	}

	if ([scheduleStates count] >= 7) {
		for (int i = 0; i < 7; i++) {
			// Tag each view with its corresponding index
			NSNumber* nsIndex = [NSNumber numberWithInt:i];
			ScheduleRowViews* row = (ScheduleRowViews *)self.scheduleRows[i];
			[row.sch_day.layer setValue:nsIndex forKey:INDEX_TAG];
			[row.sch_from.layer setValue:nsIndex forKey:INDEX_TAG];
			[row.sch_to.layer setValue:nsIndex forKey:INDEX_TAG];
			[row.sch_enable.layer setValue:nsIndex forKey:INDEX_TAG];
			[row.sch_state.layer setValue:nsIndex forKey:INDEX_TAG];
		}

		for (NSObject<SCLRScheduleState>* schedState in scheduleStates) {
			NSString* tag = [schedState getTag];
			if ([tag isEqualToString:@"MONDAY"]) {
				[self initializeScheduleRowViews:0 withSchedule:schedState];
			} else if ([tag isEqualToString:@"TUESDAY"]) {
				[self initializeScheduleRowViews:1 withSchedule:schedState];
			} else if ([tag isEqualToString:@"WEDNESDAY"]) {
				[self initializeScheduleRowViews:2 withSchedule:schedState];
			} else if ([tag isEqualToString:@"THURSDAY"]) {
				[self initializeScheduleRowViews:3 withSchedule:schedState];
			} else if ([tag isEqualToString:@"FRIDAY"]) {
				[self initializeScheduleRowViews:4 withSchedule:schedState];
			} else if ([tag isEqualToString:@"SATURDAY"]) {
				[self initializeScheduleRowViews:5 withSchedule:schedState];
			} else if ([tag isEqualToString:@"SUNDAY"]) {
				[self initializeScheduleRowViews:6 withSchedule:schedState];
			}
		}
	}

	// Next alarm details
	NSDate* nextAlarmTime = [_scheduleMgr getTimeForNextAlarm];
	if (nextAlarmTime != nil) {
		NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
		[formatter setDateStyle:NSDateFormatterShortStyle];
		[formatter setTimeStyle:NSDateFormatterShortStyle];

		self.nextAlarmLbl.text = [formatter stringFromDate:nextAlarmTime];
	} else {
		self.nextAlarmLbl.text = @"<None>";
	}
}

- (void)initializeScheduleRowViews:(int)index withSchedule:(NSObject<SCLRScheduleState> *)schedule {

	//m_scheduleRowViewsArray[scheduleRowIndex].m_startTimeMillis = schedule.getStartTime().getTimeInMillis();
	ScheduleRowViews * row = (ScheduleRowViews *)self.scheduleRows[index];
	row.schedule = schedule;

	[self setFromAndToTime:index withStartTime:[schedule getStartTime] andDuration:[schedule getDuration]];
	[self setScheduleRowEnabled:index withState:![schedule isDisabled]];
	[self setStateOnOrOff:index forSchedule:schedule];
}

- (void)setFromAndToTime:(int)index withStartTime:(NSDate *)startTime andDuration:(int)duration {
	ScheduleRowViews * row = (ScheduleRowViews *)self.scheduleRows[index];
	[self setTextAndTagOnTimeView:row.sch_from usingTime:startTime];

	NSDate* stopTime = [startTime dateByAddingTimeInterval:duration * ALARMPROCESSINGUTIL_MINUTE_S];
	[self setTextAndTagOnTimeView:row.sch_to usingTime:stopTime];
}

- (void)setTextAndTagOnTimeView:(UIButton *)timeView usingTime:(NSDate *)time {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateStyle:NSDateFormatterNoStyle];
	[formatter setTimeStyle:NSDateFormatterShortStyle];

	// Get the hour of day and minute from the time.
	NSCalendar *calendar = [NSCalendar currentCalendar];
	NSCalendarUnit units = NSCalendarUnitHour | NSCalendarUnitMinute;
	NSDateComponents *components = [calendar components:units fromDate:time];

	// Set the timeView properties

	// DEBUG: Temp formatter
	NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
	// [outputFormatter setDateFormat:@"dd HH:mm"]; //24hr time format
	[outputFormatter setDateFormat:@"HH:mm"]; //24hr time format

	[timeView setTitle:[outputFormatter stringFromDate:time] forState:UIControlStateNormal];
	[timeView.layer setValue:[NSNumber numberWithLong:components.hour] forKey:HOUR_OF_DAY_KEY];
	[timeView.layer setValue:[NSNumber numberWithLong:components.minute] forKey:MINUTE_KEY];
}

- (void)setScheduleRowEnabled:(int)index withState:(BOOL)enable {
	ScheduleRowViews * row = (ScheduleRowViews *)self.scheduleRows[index];

	BOOL changeViews = YES;
	if (!self.initializing) {
		if (enable) {
			changeViews = [_scheduleMgr enableSchedule:row.schedule];
		} else {
			changeViews = [_scheduleMgr disableSchedule:row.schedule];
		}
	}

	if (changeViews) {
		row.sch_day.enabled = enable;
		row.sch_from.enabled = enable;
		row.sch_to.enabled = enable;

		if (enable && !row.sch_enable.on) {
			row.sch_enable.on = YES;
		} else if (!enable && row.sch_enable.on) {
			row.sch_enable.on = NO;
		}
	}
}

- (void)setStateOnOrOff:(int)index forSchedule:(NSObject<SCLRScheduleState>*)schedState {
	ScheduleRowViews * row = (ScheduleRowViews *)self.scheduleRows[index];

	if ([SCHEDULE_STATE_ON isEqualToString:[schedState getState]]) {
		row.sch_state.text = @"ON";
	} else {
		row.sch_state.text = @"OFF";
	}
}

- (void)loadDefaultValues {
	NSCalendar *calendar = [NSCalendar currentCalendar];
	NSDateComponents *oneDay = [[NSDateComponents alloc] init];
	[oneDay setDay:1];
	NSCalendarUnit currDayUnits = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
	NSDateComponents *startTimeComponents = [calendar components:currDayUnits fromDate:[[NSDate alloc] init]];
	[startTimeComponents setHour:9];
	[startTimeComponents setMinute:0];
	int duration = 8 * 60;  // 8 hours in minutes

	NSDate *startTime = [calendar dateFromComponents:startTimeComponents];

	[_scheduleMgr suspendCallbacks];
	for (int i = 0; i < 7; i++) {
		NSCalendarUnit units = NSCalendarUnitWeekday;
		NSDateComponents *weekDayComponent = [calendar components:units fromDate:startTime];

		[_scheduleMgr addSchedule:startTime
					 withDuration:duration
						repeating:REPEAT_TYPE_WEEKLY
						  withTag:[self getDayTag:(int)weekDayComponent.weekday]
					 withGroupTag:SCHEDULE_GROUP];
		startTime = [calendar dateByAddingComponents:oneDay toDate:startTime options:0];
	}
	[_scheduleMgr resumeCallbacks];
}

- (NSString *)getDayTag:(int)calendarDayOfWeek {

	switch (calendarDayOfWeek) {
		case 1:
			return SUNDAY;
		case 2:
			return MONDAY;
		case 3:
			return TUESDAY;
		case 4:
			return WEDNESDAY;
		case 5:
			return THURSDAY;
		case 6:
			return FRIDAY;
		case 7:
			return SATURDAY;
		default:
			return nil;
	}
}

@end


text:
.PHONY: all clean

include ../conf.mk

K=3
tree=tree.nw
index=index

all: output_wo_header.sam output.kraken
	for x in $^; do test -s $$x; done;

output_wo_header.sam: index.complete
	$(PROP) classify $(index) -f sam to_be_unclassified.fa | samtools view > $@

output.kraken: index.complete
	$(PROP) classify $(index) -f kraken to_be_unclassified.fa > $@

index.complete:
	$(PROP) index -k $(K) -A $(tree) $(index)
	touch $@

clean:
	rm -rf $(index)
	rm -f *.complete *.sam *.kraken


text:
import logging
import os
import shutil
import tempfile
import copy
import datetime

import numpy as np
from matplotlib.pyplot import imsave
import PIL.Image
import piexif

from imagecluster import calc as ic
from imagecluster import io as icio

# https://stackoverflow.com/a/39708493
logging.getLogger("tensorflow").setLevel(logging.CRITICAL)

pj = os.path.join

# TODO re-use ImagedirCtx where possible, we write files in each context,
# re-use ctxs which don't alter the files
class ImagedirCtx:
    def __init__(self, fmt='png'):
        assert fmt in ['jpg', 'png']
        date_time_base_dct = dict(year=2019,
                                  month=12,
                                  day=31,
                                  hour=23,
                                  minute=42)
        imagedir = tempfile.mkdtemp(prefix='imagecluster_')
        dbfn = pj(imagedir, icio.ic_base_dir, 'fingerprints.pk')
        arr = np.ones((500,600,3), dtype=np.uint8)
        white = np.ones_like(arr) * 255
        black = np.zeros_like(arr)
        red = np.ones_like(arr)
        red[...,0] *= 255
        images = dict(red=[red]*2,
                      white=[white]*3,
                      black=[black]*4)
        image_fns = []
        clusters = {}
        second = 0
        for color, arrs in images.items():
            nimg = len(arrs)
            clus = clusters.get(nimg, [])
            for idx, arr in enumerate(arrs):
                if fmt == 'png':
                    fn = pj(imagedir, f'image_{color}_{idx}.png')
                    imsave(fn, arr)
                elif fmt == 'jpg':
                    fn = pj(imagedir, f'image_{color}_{idx}.jpg')
                    img = PIL.Image.fromarray(arr, mode='RGB')
                    # just the DateTime field
                    date_time_dct = copy.deepcopy(date_time_base_dct)
                    date_time_dct.update(second=second)
                    exif_date_time_fmt = '{year}:{month}:{day} {hour}:{minute}:{second}'
                    exif_date_time_str = exif_date_time_fmt.format(**date_time_dct)
                    piexif_exif_dct = {'0th': {306: exif_date_time_str}}
                    img.save(fn, exif=piexif.dump(piexif_exif_dct))
                image_fns.append(fn)
                clus.append(fn)
                second += 1
            clusters[nimg] = [clus]
        self.imagedir = imagedir
        self.dbfn = dbfn
        self.image_fns = image_fns
        self.clusters = clusters
        self.date_time_base_dct = date_time_base_dct
        print(clusters)

    def __enter__(self):
        return self

    def __exit__(self, *args):
        shutil.rmtree(self.imagedir)

def test_api_get_image_data():
    with ImagedirCtx() as ctx:
        # run 1: create fingerprints database, run clustering
        images,fingerprints,timestamps = icio.get_image_data(ctx.imagedir)
        # run 2: only run clustering, should be much faster, this time use all
        # kwds (test API)
        images,fingerprints,timestamps = icio.get_image_data(
            ctx.imagedir,
            pca_kwds=dict(n_components=0.95),
            model_kwds=dict(layer='fc2'),
            img_kwds=dict(size=(224,224)),
            timestamps_kwds=dict(source='auto'))
        assert len(fingerprints.keys()) == len(ctx.image_fns)
        assert set(fingerprints.keys()) == set(ctx.image_fns)

def test_low_level_api_and_clustering():
    # use low level API (same as get_image_data) but call all funcs
    # test clustering
    with ImagedirCtx() as ctx:
        images = icio.read_images(ctx.imagedir, size=(224,224))
        model = ic.get_model()
        fingerprints = ic.fingerprints(images, model)
        for kk,vv in fingerprints.items():
            assert isinstance(vv, np.ndarray)
            assert len(vv) == 4096, len(vv)
        fingerprints = ic.pca(fingerprints, n_components=0.95)
        clusters = ic.cluster(fingerprints, sim=0.5)
        assert set(clusters.keys()) == set(ctx.clusters.keys())
        assert len(fingerprints.keys()) == len(ctx.image_fns)
        assert set(fingerprints.keys()) == set(ctx.image_fns)
        for nimg in ctx.clusters.keys():
            for val_clus, ref_clus in zip(clusters[nimg], ctx.clusters[nimg]):
                msg = f"ref_clus: {ref_clus}, val_clus: {val_clus}"
                assert set(ref_clus) == set(val_clus), msg

def test_png_rgba_io():
    fn = tempfile.mktemp(prefix='imagecluster_') + '.png'
    try:
        shape2d = (123,456)
        shape = shape2d + (3,)
        rgb = (np.random.rand(*shape) * 255).astype(np.uint8)
        alpha1 = np.ones(shape2d, dtype=np.uint8) * 255  # white
        alpha2 = np.zeros(shape2d, dtype=np.uint8)  # black
        alpha3 = (np.random.rand(*shape2d) * 255).astype(np.uint8)  # noise
        for alpha in [alpha1, alpha2, alpha3]:
            rgba = np.empty(shape2d + (4,), dtype=np.uint8)
            rgba[..., :3] = rgb
            rgba[..., 3] = alpha
            assert rgba.max() <= 255
            imsave(fn, rgba)
            img = PIL.Image.open(fn)
            assert img.mode == 'RGBA', img.mode
            assert img.format == 'PNG', img.format
            rgb2 = np.array(PIL.Image.open(fn).convert('RGB'))
            assert (rgb == rgb2).all()
            assert rgb.dtype == rgb2.dtype
    finally:
        if os.path.exists(fn):
            os.remove(fn)

def test_img_timestamp():
    with ImagedirCtx(fmt='jpg') as ctx:
        for second, fn in enumerate(ctx.image_fns):
            stamp = icio.exif_timestamp(fn)
            dct = copy.deepcopy(ctx.date_time_base_dct)
            dct.update(second=second)
            ref = datetime.datetime(**dct, tzinfo=datetime.timezone.utc).timestamp()
            assert stamp is not None
            assert stamp == ref, f"stamp={stamp} ref={ref}"
            # try EXIF first
            assert stamp == icio.timestamp(fn, source='auto')
            assert stamp == icio.timestamp(fn, source='exif')

    with ImagedirCtx(fmt='png') as ctx:
        fn = ctx.image_fns[0]
        assert icio.stat_timestamp(fn) is not None
        assert icio.timestamp(fn, source='auto') is not None
        assert icio.timestamp(fn, source='auto') == icio.stat_timestamp(fn)


text:
import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import gvldash
version = gvldash.__version__

setup(
    name='gvldash',
    version=version,
    author='',
    author_email='nuwan.goonasekera@unimelb.edu.au',
    packages=[
        'gvldash',
    ],
    include_package_data=True,
    install_requires=[
        'Django>=1.6.5',
    ],
    zip_safe=False,
    scripts=['gvldash/manage.py'],
)


text:
using System;
using System.Runtime.Serialization;
using Gallio.Common.Diagnostics;
using Gallio.Model;

namespace Gallio.Framework
{
    /// <summary>
    /// This exception type is used to signal that a test has not produced a conclusive
    /// pass or fail result.
    /// </summary>
    /// <remarks>
    /// <para>
    /// The exception message, if present, should explain the
    /// reason no conclusive result was obtained.
    /// </para>
    /// </remarks>
    [Serializable]
    public class TestInconclusiveException : TestException
    {
        /// <summary>
        /// Creates an exception.
        /// </summary>
        public TestInconclusiveException()
        {
        }

        /// <summary>
        /// Creates an exception.
        /// </summary>
        /// <param name="message">The message.</param>
        public TestInconclusiveException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Creates an exception.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="innerException">The inner exception.</param>
        public TestInconclusiveException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        /// <summary>
        /// Creates an exception from serialization info.
        /// </summary>
        /// <param name="info">The serialization info.</param>
        /// <param name="context">The streaming context.</param>
        protected TestInconclusiveException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// Returns <see cref="TestOutcome.Inconclusive" />.
        /// </summary>
        [SystemInternal]
        public sealed override TestOutcome Outcome
        {
            get { return TestOutcome.Inconclusive; }
        }
    }
}


text:
import Promise from 'promise-polyfill'
if (!window.Promise) {
  window.Promise = Promise
}

import Clipboard from 'clipboard'
import attributions from './attributions'
import * as list from './list'
import * as form from './form'
import * as grid from './grid'
import * as favorite from './favorite'
import * as tags from './tags'
import * as search from './search'

const init = () => {
  var clipboardText = new Clipboard('.clipboard-sel-text')
  var clipboardHTML = new Clipboard('.clipboard-sel-html', {
      text: () => {
        const htmlBlock = document.querySelector('.attribution')
        return htmlBlock.innerHTML
      }
  })
  attributions(clipboardText)
  attributions(clipboardHTML)
}

document.addEventListener('DOMContentLoaded', () => {
  init()
})

window.openledger = {}
window.openledger.list = list
window.openledger.form = form
window.openledger.grid = grid
window.openledger.favorite = favorite
window.openledger.tags = tags
window.openledger.search = search


text:
*DataKit* is a tool to orchestrate applications using a Git-like dataflow. It
revisits the UNIX pipeline concept, with a modern twist: streams of
tree-structured data instead of raw text. DataKit allows you to define
complex build pipelines over version-controlled data.

DataKit is currently used as the coordination
layer for [HyperKit](http://github.com/docker/hyperkit), the
hypervisor component of
[Docker for Mac and Windows](https://blog.docker.com/2016/03/docker-for-mac-windows-beta/), and
for the [DataKitCI][] continuous integration system.

---

[![Build Status (OSX, Linux)](https://travis-ci.org/moby/datakit.svg)](https://travis-ci.org/moby/datakit)
[![Build status (Windows)](https://ci.appveyor.com/api/projects/status/6qrdgiqbhi4sehmy/branch/master?svg=true)](https://ci.appveyor.com/project/moby/datakit/branch/master)
[![docs](https://img.shields.io/badge/doc-online-blue.svg)](https://docker.github.io/datakit/)

There are several components in this repository:

- `src` contains the main DataKit service. This is a Git-like database to which other services can connect.
- `ci` contains [DataKitCI][], a continuous integration system that uses DataKit to monitor repositories and store build results.
- `ci/self-ci` is the CI configuration for DataKitCI that tests DataKit itself.
- `bridge/github` is a service that monitors repositories on GitHub and syncs their metadata with a DataKit database.
  e.g. when a pull request is opened or updated, it will commit that information to DataKit. If you commit a status message to DataKit, the bridge will push it to GitHub.
- `bridge/local` is a drop-in replacement for `bridge/github` that just monitors a local Git repository. This is useful for local testing.

### Quick Start

The easiest way to use DataKit is to start both the server and the client in containers.

To expose a Git repository as a 9p endpoint on port 5640 on a private network, run:

```shell
$ docker network create datakit-net # create a private network
$ docker run -it --net datakit-net --name datakit -v <path/to/git/repo>:/data datakit/db
```

*Note*: The `--name datakit` option is mandatory.  It will allow the client
to connect to a known name on the private network.

You can then start a DataKit client, which will mount the 9p endpoint and
expose the database as a filesystem API:

```shell
# In an other terminal
$ docker run -it --privileged --net datakit-net datakit/client
$ ls /db
branch     remotes    snapshots  trees
```

*Note*: the `--privileged` option is needed because the container will have
to mount the 9p endpoint into its local filesystem.

Now you can explore, edit and script `/db`. See the
[Filesystem API][]
for more details.

### Building

The easiest way to build the DataKit project is to use [docker](https://docker.com),
(which is what the
[start-datakit.sh](https://github.com/moby/datakit/blob/master/scripts/start-datakit.sh) script
does under the hood):

```shell
docker build -t datakit/db -f Dockerfile .
docker run -p 5640:5640 -it --rm datakit/db --listen-9p=tcp://0.0.0.0:5640
```
These commands will expose the database's 9p endpoint on port 5640.

If you want to build the project from source without Docker, you will need to install
[ocaml](http://ocaml.org/) and [opam](http://opam.ocaml.org/). Then write:

```shell
$ make depends
$ make && make test
```

For information about command-line options:

```shell
$ datakit --help
```

## Prometheus metric reporting

Run with `--listen-prometheus 9090` to expose metrics at `http://*:9090/metrics`.

Note: there is no encryption and no access control. You are expected to run the
database in a container and to not export this port to the outside world. You
can either collect the metrics by running a Prometheus service in a container
on the same Docker network, or front the service with nginx or similar if you
want to collect metrics remotely.

## Language bindings

* **Go** bindings are in the `api/go` directory.
* **OCaml** bindings are in the `api/ocaml` directory. See `examples/ocaml-client` for an example.

## Licensing

DataKit is licensed under the Apache License, Version 2.0. See
[LICENSE](https://github.com/moby/datakit/blob/master/LICENSE.md) for the full
license text.

Contributions are welcome under the terms of this license. You may wish to browse
the [weekly reports](reports) to read about overall activity in the repository.

[DataKitCI]: https://github.com/moby/datakit/tree/master/ci
[Filesystem API]: https://github.com/moby/datakit/tree/master/9p.md


text:
package com.microsoft.bingads.v12.reporting;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Reserved for internal use.
 */
public class KeywordStatusReportFilterConverter {

    public static Collection<KeywordStatusReportFilter> convertToList(String enums) {
        String[] values = enums.split(" ");

        Collection<KeywordStatusReportFilter> result = new ArrayList<KeywordStatusReportFilter>();

        for (String value : values) {
            result.add(KeywordStatusReportFilter.fromValue(value));
        }

        return result;
    }

    public static String convertToString(Collection<KeywordStatusReportFilter> enums) {
        String result = "";

        for (KeywordStatusReportFilter entity : enums) {
            result += (entity.value() + " ");
        }

        result = result.substring(0, result.length() - 1);

        return result;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/card_margin"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingTop="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:orientation="vertical"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:paddingTop="14dp">

        <TextView
            android:id="@+id/row_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="12dp"
            android:singleLine="true"
            android:text="row_title" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <RelativeLayout
                android:id="@+id/pic_rl"
                android:layout_width="140dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical">

                <ImageView
                    android:id="@+id/row_iv"
                    android:layout_width="140dp"
                    android:layout_height="94dp"
                    android:src="@drawable/ic_class_icon" />

                <ImageView
                    android:id="@+id/row_red_dot_is_had_opened"
                    android:layout_width="14dp"
                    android:layout_height="14dp"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="1dp"
                    android:src="@drawable/ic_class" />
            </RelativeLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="left|center"
                android:orientation="vertical"
                android:paddingLeft="16dp"
                android:paddingRight="12dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="12dp">

                    <TextView
                        android:id="@+id/myclass_classmateprogress_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:text="myclass_classmateprogress_text" />

                    <TextView
                        android:id="@+id/students_progress"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:text="50.0%" />

                    <ProgressBar
                        android:id="@+id/pro_students"
                        style="?android:attr/progressBarStyleHorizontal"
                        android:layout_width="fill_parent"
                        android:layout_height="4dp"
                        android:layout_below="@+id/myclass_classmateprogress_text"
                        android:layout_marginTop="4dp"
                        android:progress="50" />
                </RelativeLayout>

                <RelativeLayout
                    android:id="@+id/myclass_myprogress"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">

                    <TextView
                        android:id="@+id/myclass_myprogress_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:text="myclass_myprogress_text" />

                    <TextView
                        android:id="@+id/my_progress"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:text="80.0%" />

                    <ProgressBar
                        android:id="@+id/pro_me"
                        style="?android:attr/progressBarStyleHorizontal"
                        android:layout_width="fill_parent"
                        android:layout_height="4dp"
                        android:layout_below="@+id/myclass_myprogress_text"
                        android:layout_marginTop="4dp"
                        android:progress="80" />
                </RelativeLayout>

                <TextView
                    android:id="@+id/credit"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:gravity="bottom"
                    android:includeFontPadding="false"
                    android:text="credit" />

                <LinearLayout
                    android:id="@+id/myclass_contunue_study"
                    android:layout_width="124dp"
                    android:layout_height="30dp"
                    android:background="@drawable/ic_dashboard"
                    android:clickable="true"
                    android:gravity="center"
                    android:visibility="gone">

                    <TextView
                        android:id="@+id/tx_start"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:drawablePadding="5dp"
                        android:drawableRight="@drawable/ic_dashboard"
                        android:singleLine="true"
                        android:text="dad" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>


text:
from django.shortcuts import render_to_response
from django.template.loader import render_to_string

from sentry.plugins import GroupActionProvider

class ServerUrlsPanel(GroupActionProvider):
    """Adds additional support for showing information about urls including:

    * A panel which shows all urls a message was seen on.
    * A sidebar module which shows the urls most actively seen on.
    """

    title = 'URLs'

    def panels(self, request, panel_list, group):
        panel_list.append((self.title, self.__class__.get_url(group.pk)))
        return panel_list

    def view(self, request, group):
        return render_to_response('sentry/plugins/sentry_urls/index.html', locals())

    def widget(self, request, group):
        return render_to_string('sentry/plugins/sentry_urls/widget.html', locals())


text:
/*
 * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
 * at the root of this project for more details.
 */
package io.github.nucleuspowered.nucleus.modules.nickname.listeners;

import com.google.inject.Inject;
import io.github.nucleuspowered.nucleus.modules.nickname.services.NicknameService;
import io.github.nucleuspowered.nucleus.core.scaffold.listener.ListenerBase;
import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection;
import net.kyori.adventure.text.Component;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.filter.Getter;
import org.spongepowered.api.event.network.ServerSideConnectionEvent;

import java.util.Optional;

public class NicknameListener implements ListenerBase {

    private final NicknameService nicknameService;

    @Inject
    public NicknameListener(final INucleusServiceCollection serviceCollection) {
        this.nicknameService = serviceCollection.getServiceUnchecked(NicknameService.class);
    }

    @Listener(order = Order.FIRST)
    public void onPlayerJoin(final ServerSideConnectionEvent.Join event, @Getter("player") final ServerPlayer player) {
        final Optional<Component> nickname = this.nicknameService.getNickname(player.uniqueId());
        this.nicknameService.markRead(player.uniqueId());
        if (nickname.isPresent()) {
            this.nicknameService.updateCache(player.uniqueId(), nickname.get());
            player.offer(Keys.CUSTOM_NAME, nickname.get());
        } else {
            player.remove(Keys.CUSTOM_NAME);
        }
    }

    @Listener(order = Order.LAST)
    public void onPlayerQuit(final ServerSideConnectionEvent.Disconnect event, @Getter("player") final ServerPlayer player) {
        this.nicknameService.removeFromCache(player.uniqueId());
    }

}


text:
package org.innovateuk.ifs.project.spendprofile.controller;

import org.innovateuk.ifs.commons.rest.LocalDateResource;
import org.innovateuk.ifs.commons.security.SecuredBySpring;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.controller.ValidationHandler;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.project.ProjectService;
import org.innovateuk.ifs.project.spendprofile.SpendProfileSummaryModel;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.project.spendprofile.form.TotalSpendProfileForm;
import org.innovateuk.ifs.project.spendprofile.resource.SpendProfileTableResource;
import org.innovateuk.ifs.project.spendprofile.SpendProfileTableCalculator;
import org.innovateuk.ifs.project.spendprofile.viewmodel.TotalProjectSpendProfileTableViewModel;
import org.innovateuk.ifs.project.spendprofile.viewmodel.TotalSpendProfileViewModel;
import org.innovateuk.ifs.spendprofile.SpendProfileService;
import org.innovateuk.ifs.util.PrioritySorting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static org.innovateuk.ifs.competition.publiccontent.resource.FundingType.LOAN;
import static org.innovateuk.ifs.util.CollectionFunctions.*;

/**
 * This controller will handle all requests that are related to the reviewing and sending of total project spend profiles.
 */
@Controller
@RequestMapping("/" + TotalProjectSpendProfileController.BASE_DIR + "/{projectId}/spend-profile/total")
@SecuredBySpring(value = "Controller", description = "TODO", securedType = TotalProjectSpendProfileController .class)
@PreAuthorize("hasAnyAuthority('project_finance', 'applicant', 'comp_admin')")
public class TotalProjectSpendProfileController {

    public static final String BASE_DIR = "project";
    private static final String FORM_ATTR_NAME = "form";
    private static final String SPEND_PROFILE_TOTALS_TEMPLATE = BASE_DIR + "/spend-profile-totals";

    @Autowired
    private ProjectService projectService;
    @Autowired
    private SpendProfileService spendProfileService;
    @Autowired
    private SpendProfileTableCalculator spendProfileTableCalculator;
    @Autowired
    private CompetitionRestService competitionRestService;

    @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_TOTAL_SPEND_PROFILE_SECTION')")
    @GetMapping
    public String totals(Model model, @PathVariable("projectId") final Long projectId) {
        model.addAttribute("model", buildTotalViewModel(projectId));
        model.addAttribute(FORM_ATTR_NAME, new TotalSpendProfileForm());
        return SPEND_PROFILE_TOTALS_TEMPLATE;
    }

    @GetMapping("confirmation")
    public String confirmation(@PathVariable("projectId") final Long projectId) {
        return BASE_DIR + "/spend-profile-total-confirmation";
    }

    @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'SUBMIT_SPEND_PROFILE_SECTION')")
    @PostMapping
    public String sendForReview(@PathVariable("projectId") final Long projectId,
                                @ModelAttribute(FORM_ATTR_NAME) TotalSpendProfileForm form,
                                @SuppressWarnings("unused") BindingResult bindingResult,
                                ValidationHandler validationHandler,
                                Model model) {
        return validationHandler.performActionOrBindErrorsToField("",
                () -> {
                    model.addAttribute("model", buildTotalViewModel(projectId));
                    model.addAttribute(FORM_ATTR_NAME, form);
                    return SPEND_PROFILE_TOTALS_TEMPLATE;
                },
                () -> "redirect:/project/" + projectId,
                () -> spendProfileService.completeSpendProfilesReview(projectId));

    }

    private TotalSpendProfileViewModel buildTotalViewModel(final Long projectId) {
        ProjectResource projectResource = projectService.getById(projectId);
        TotalProjectSpendProfileTableViewModel tableView = buildTableViewModel(projectId);

        CompetitionResource competition = competitionRestService.getCompetitionById(projectResource.getCompetition()).getSuccess();
        SpendProfileSummaryModel summary = null;
        if (!competition.getFundingType().equals(LOAN)) {
            summary = spendProfileTableCalculator.createSpendProfileSummary(projectResource, tableView.getMonthlyCostsPerOrganisationMap(), tableView.getMonths());
        }
        return new TotalSpendProfileViewModel(projectResource, tableView, summary, competition.isKtp());
    }

    private TotalProjectSpendProfileTableViewModel buildTableViewModel(final Long projectId) {
        final OrganisationResource leadOrganisation = projectService.getLeadOrganisation(projectId);
        List<OrganisationResource> organisations = new PrioritySorting<>(projectService.getPartnerOrganisationsForProject(projectId),
                leadOrganisation, OrganisationResource::getName).unwrap();

        Map<Long, SpendProfileTableResource> organisationSpendProfiles = simpleToLinkedMap(organisations, OrganisationResource::getId,
                organisation -> spendProfileService.getSpendProfileTable(projectId, organisation.getId()));

        Map<Long, List<BigDecimal>> monthlyCostsPerOrganisationMap = simpleLinkedMapValue(organisationSpendProfiles, spendTableResource ->
                spendProfileTableCalculator.calculateMonthlyTotals(spendTableResource.getMonthlyCostsPerCategoryMap(), spendTableResource.getMonths().size()));

        Map<Long, BigDecimal> eligibleCostPerOrganisationMap = simpleLinkedMapValue(organisationSpendProfiles, tableResource ->
                spendProfileTableCalculator.calculateTotalOfAllEligibleTotals(tableResource.getEligibleCostPerCategoryMap()));

        List<LocalDateResource> months = organisationSpendProfiles.values().iterator().next().getMonths();
        Map<Long, BigDecimal> organisationToActualTotal = spendProfileTableCalculator.calculateRowTotal(monthlyCostsPerOrganisationMap);
        List<BigDecimal> totalForEachMonth = spendProfileTableCalculator.calculateMonthlyTotals(monthlyCostsPerOrganisationMap, months.size());
        BigDecimal totalOfAllActualTotals = spendProfileTableCalculator.calculateTotalOfAllActualTotals(monthlyCostsPerOrganisationMap);
        BigDecimal totalOfAllEligibleTotals = spendProfileTableCalculator.calculateTotalOfAllEligibleTotals(eligibleCostPerOrganisationMap);

        return new TotalProjectSpendProfileTableViewModel(months, monthlyCostsPerOrganisationMap, eligibleCostPerOrganisationMap,
                organisationToActualTotal, totalForEachMonth, totalOfAllActualTotals, totalOfAllEligibleTotals,
                simpleToMap(organisations, OrganisationResource::getId, OrganisationResource::getName), leadOrganisation);

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>intersection</type>
  <formatted_address>North St, Montrose, Angus DD10, UK</formatted_address>
  <address_component>
   <long_name>North Street</long_name>
   <short_name>North St</short_name>
   <type>route</type>
  </address_component>
  <address_component>
   <long_name>Montrose</long_name>
   <short_name>Montrose</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Montrose</long_name>
   <short_name>Montrose</short_name>
   <type>postal_town</type>
  </address_component>
  <address_component>
   <long_name>Angus</long_name>
   <short_name>Angus</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>United Kingdom</long_name>
   <short_name>GB</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>DD10</long_name>
   <short_name>DD10</short_name>
   <type>postal_code</type>
   <type>postal_code_prefix</type>
  </address_component>
  <geometry>
   <location>
    <lat>56.7161134</lat>
    <lng>-2.4667605</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>56.7147644</lat>
     <lng>-2.4681095</lng>
    </southwest>
    <northeast>
     <lat>56.7174624</lat>
     <lng>-2.4654115</lng>
    </northeast>
   </viewport>
  </geometry>
  <partial_match>true</partial_match>
  <place_id>EiJOb3J0aCBTdCwgTW9udHJvc2UsIEFuZ3VzIEREMTAsIFVL</place_id>
 </result>
</GeocodeResponse>


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../paper-material/paper-material.html">
<link rel="import" href="../tf-dashboard-common/scrollbar-style.html">
<link rel="import" href="../tf-imports/d3.html">

<dom-module id="tf-text-loader">

  <template>

    <paper-material elevation="1" id="outer" class="container scrollbar">
      <template id="repeater" is="dom-repeat" items="[[_texts]]">
      <paper-material elevation="1" class="step-container">
        step [[_numfmt(item.step)]]
      </paper-material>
      <paper-material elevation="1" inner-h-t-m-l="[[item.text]]" class="text">
        </paper-material>
      </template>
    </paper-material>

  </template>

</dom-module>


text:
"use strict";
var commonUtils = require("../../core/utils/common"),
    isDefined = commonUtils.isDefined,
    round = Math.round;
module.exports = {
    translate: function(category, directionOffset) {
        var stickDelta, that = this,
            canvasOptions = that._canvasOptions,
            categoryIndex = that._categoriesToPoints[category.valueOf()],
            specialValue = that.translateSpecialCase(category),
            startPointIndex = canvasOptions.startPointIndex || 0,
            stickInterval = that._businessRange.stick ? 0 : .5;
        if (isDefined(specialValue)) {
            return specialValue
        }
        if (!categoryIndex && 0 !== categoryIndex) {
            return null
        }
        directionOffset = directionOffset || 0;
        stickDelta = categoryIndex + stickInterval - startPointIndex + .5 * directionOffset;
        return round(that._calculateProjection(canvasOptions.interval * stickDelta))
    },
    untranslate: function(pos, directionOffset, enableOutOfCanvas) {
        var that = this,
            canvasOptions = that._canvasOptions,
            startPoint = canvasOptions.startPoint,
            categories = that.visibleCategories || that._categories,
            categoriesLength = categories.length,
            result = 0,
            stickInterval = that._businessRange.stick ? .5 : 0;
        if (!enableOutOfCanvas && (pos < startPoint || pos > canvasOptions.endPoint)) {
            return null
        }
        directionOffset = directionOffset || 0;
        result = round((pos - startPoint) / canvasOptions.interval + stickInterval - .5 - .5 * directionOffset);
        if (categoriesLength === result) {
            result--
        }
        if (result === -1) {
            result = 0
        }
        if (canvasOptions.invert) {
            result = categoriesLength - result - 1
        }
        return categories[result]
    },
    getInterval: function() {
        return this._canvasOptions.interval
    },
    zoom: function(translate, scale) {
        var endCategoryIndex, newVisibleCategories, newInterval, that = this,
            canvasOptions = that._canvasOptions,
            stick = that._businessRange.stick,
            invert = canvasOptions.invert,
            interval = canvasOptions.interval * scale,
            translateCategories = translate / interval,
            startCategoryIndex = parseInt((canvasOptions.startPointIndex || 0) + translateCategories + .5),
            categoriesLength = parseInt(canvasOptions.canvasLength / interval + (stick ? 1 : 0)) || 1,
            categories = that._categories;
        if (invert) {
            startCategoryIndex = parseInt((canvasOptions.startPointIndex || 0) + (that.visibleCategories || []).length - translateCategories + .5) - categoriesLength
        }
        if (startCategoryIndex < 0) {
            startCategoryIndex = 0
        }
        endCategoryIndex = startCategoryIndex + categoriesLength;
        if (endCategoryIndex > categories.length) {
            endCategoryIndex = categories.length;
            startCategoryIndex = endCategoryIndex - categoriesLength;
            if (startCategoryIndex < 0) {
                startCategoryIndex = 0
            }
        }
        newVisibleCategories = categories.slice(parseInt(startCategoryIndex), parseInt(endCategoryIndex));
        newInterval = that._getDiscreteInterval(newVisibleCategories.length, canvasOptions);
        scale = newInterval / canvasOptions.interval;
        translate = that.translate(!invert ? newVisibleCategories[0] : newVisibleCategories[newVisibleCategories.length - 1]) * scale - (canvasOptions.startPoint + (stick ? 0 : newInterval / 2));
        return {
            min: newVisibleCategories[0],
            max: newVisibleCategories[newVisibleCategories.length - 1],
            translate: translate,
            scale: scale
        }
    },
    getMinScale: function(zoom) {
        var that = this,
            canvasOptions = that._canvasOptions,
            categoriesLength = (that.visibleCategories || that._categories).length;
        categoriesLength += (parseInt(.1 * categoriesLength) || 1) * (zoom ? -2 : 2);
        return canvasOptions.canvasLength / (Math.max(categoriesLength, 1) * canvasOptions.interval)
    },
    getScale: function(min, max) {
        var that = this,
            canvasOptions = that._canvasOptions,
            visibleArea = that.getCanvasVisibleArea(),
            stickOffset = !that._businessRange.stick && 1,
            minPoint = isDefined(min) ? that.translate(min, -stickOffset) : null,
            maxPoint = isDefined(max) ? that.translate(max, +stickOffset) : null;
        if (null === minPoint) {
            minPoint = canvasOptions.invert ? visibleArea.max : visibleArea.min
        }
        if (null === maxPoint) {
            maxPoint = canvasOptions.invert ? visibleArea.min : visibleArea.max
        }
        return that.canvasLength / Math.abs(maxPoint - minPoint)
    },
    isValid: function(value) {
        return isDefined(value) ? this._categoriesToPoints[value.valueOf()] >= 0 : false
    },
    parse: function(value) {
        return value
    },
    to: function(value, direction) {
        var canvasOptions = this._canvasOptions,
            businessRange = this._businessRange,
            categoryIndex = this._categoriesToPoints[value.valueOf()],
            startPointIndex = canvasOptions.startPointIndex || 0,
            stickInterval = businessRange.stick ? 0 : .5,
            stickDelta = categoryIndex + stickInterval - startPointIndex + (businessRange.invert ? -1 : 1) * direction * .5;
        return round(this._calculateProjection(canvasOptions.interval * stickDelta))
    },
    from: function(position, direction) {
        var canvasOptions = this._canvasOptions,
            businessRange = this._businessRange,
            startPoint = canvasOptions.startPoint,
            categories = this._categories,
            categoriesLength = categories.length,
            stickInterval = businessRange.stick ? .5 : 0,
            result = round((position - startPoint) / canvasOptions.interval + stickInterval - .5 - .5 * direction);
        if (categoriesLength === result) {
            result--
        }
        if (result === -1) {
            result = 0
        }
        if (canvasOptions.invert) {
            result = categoriesLength - result - 1
        }
        return categories[result]
    },
    _add: function() {
        return NaN
    },
    isValueProlonged: true
};


text:
select * from
(
	select sod.SalesPersonID pracId,round(subtotal,2) KwotaSprzedazy,YEAR(sod.orderdate) rok from sales.SalesOrderHeader sod
) as p
pivot (sum(KwotaSprzedazy) for rok in ([2011],[2012],[2013],[2014])) pvt


text:
package com.github.dcoric.demonico.service;

import java.util.List;

import com.github.dcoric.demonico.model.User;

public interface UserService {

	public void persistUser(User user);

	public User findUserById(Integer id);

	public User findUserUsernamePassword(String username, String password);

	public List<User> findAll();

	public List<User> findUserByName(String firstName, String lastName);

	public void updateUser(User user);

	public void deleteUser(User user);

	public User findUserByUsername(String username);
}