text:
published: true
layout: page
---
Games Programming using KODU

![Alt textl]({{ site.baseurl }}/04kodu/Kodu1.jpg "Eample of Kodu Programming")

## Games Programming using KODU

1. Lesson 01 [Introduction to KODU]({{ site.baseurl }}/04kodu/lesson_01.ppt "Download this and follow the instructions in the Powerpoint to get started in KODU")
2. Lesson 02 [KODU gaming and world editing]({{ site.baseurl }}/04kodu/lesson_02.ppt "Download this and follow the instructions in the Powerpoint to edit your worlds and add interaction with your world")
3. Lesson 03 [Multiplayer and high scores]({{ site.baseurl }}/04kodu/lesson_03.ppt "Download this and follow the instructions in the Powerpoint to create a multi player game and gain high score awards")
4. Your [KODU game presentation]({{ site.baseurl }}/04kodu/lesson_final.pptx "Download this and complete the slides to showcase your KODU game which will be used for assessment")

### Useful Resources
1. Manual [Kodu Training Manual]({{ site.baseurl }}/04kodu/Designing Games with Kodu Game Lab Trainer Manual v2.pdf  "Kodu Training Manual ")
2. Tips [Some less than obvious tricks]({{ site.baseurl }}/04kodu/Designing Games with Kodu Game Lab Trainer Manual v2.pdf  "Kodu Top Tricks ")

### Teacher Resources

1. Starter [General programming concepts]({{ site.baseurl }}/04kodu/l1 going out.doc "Download this and move the text boxes to the correct Flowchart Location ")
2. Starter [Guess the Blue Icons - Lesson 2]({{ site.baseurl }}/04kodu/l02 starter guess the icons blue.pptx "Class wide via OHP")
3. Starter [Guess the Action Icons - Lesson 3]({{ site.baseurl }}/04kodu/l03 starter guess the icons actions.pptx "Class wide via OHP")
4. Plenary [What will happen next - Lesson 3]({{ site.baseurl }}/04kodu/l03 plenary what next v01 v01, by rita.Kodu "Download and load into KODU and then Class Wide via OHP what happens next")
5. Starter Answers [General programming concepts - item 1]({{ site.baseurl }}/04kodu/l1 going out answers.doc "Answers for Going Out ")
4. [KODU game presentation Levels]({{ site.baseurl }}/04kodu/lesson_final levels.pptx "definition of levels for KODU to be used for assessment")


text:
import os
import sys

def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "contactmvc.settings")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)

redpajama_set_name: RedPajamaGithub


text:
import { assert } from "ember-data/debug";
import { PromiseManyArray } from "ember-data/system/promise-proxies";
import Relationship from "ember-data/system/relationships/state/relationship";
import OrderedSet from "ember-data/system/ordered-set";
import ManyArray from "ember-data/system/many-array";

import { assertPolymorphicType } from "ember-data/utils";

export default function ManyRelationship(store, record, inverseKey, relationshipMeta) {
  this._super$constructor(store, record, inverseKey, relationshipMeta);
  this.belongsToType = relationshipMeta.type;
  this.canonicalState = [];
  this.manyArray = ManyArray.create({
    canonicalState: this.canonicalState,
    store: this.store,
    relationship: this,
    type: this.store.modelFor(this.belongsToType),
    record: record
  });
  this.isPolymorphic = relationshipMeta.options.polymorphic;
  this.manyArray.isPolymorphic = this.isPolymorphic;
}

ManyRelationship.prototype = Object.create(Relationship.prototype);
ManyRelationship.prototype.constructor = ManyRelationship;
ManyRelationship.prototype._super$constructor = Relationship;

ManyRelationship.prototype.destroy = function() {
  this.manyArray.destroy();
};

ManyRelationship.prototype._super$updateMeta = Relationship.prototype.updateMeta;
ManyRelationship.prototype.updateMeta = function(meta) {
  this._super$updateMeta(meta);
  this.manyArray.set('meta', meta);
};

ManyRelationship.prototype._super$addCanonicalRecord = Relationship.prototype.addCanonicalRecord;
ManyRelationship.prototype.addCanonicalRecord = function(record, idx) {
  if (this.canonicalMembers.has(record)) {
    return;
  }
  if (idx !== undefined) {
    this.canonicalState.splice(idx, 0, record);
  } else {
    this.canonicalState.push(record);
  }
  this._super$addCanonicalRecord(record, idx);
};

ManyRelationship.prototype._super$addRecord = Relationship.prototype.addRecord;
ManyRelationship.prototype.addRecord = function(record, idx) {
  if (this.members.has(record)) {
    return;
  }
  this._super$addRecord(record, idx);
  this.manyArray.internalAddRecords([record], idx);
};

ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = Relationship.prototype.removeCanonicalRecordFromOwn;
ManyRelationship.prototype.removeCanonicalRecordFromOwn = function(record, idx) {
  var i = idx;
  if (!this.canonicalMembers.has(record)) {
    return;
  }
  if (i === undefined) {
    i = this.canonicalState.indexOf(record);
  }
  if (i > -1) {
    this.canonicalState.splice(i, 1);
  }
  this._super$removeCanonicalRecordFromOwn(record, idx);
};

ManyRelationship.prototype._super$flushCanonical = Relationship.prototype.flushCanonical;
ManyRelationship.prototype.flushCanonical = function() {
  this.manyArray.flushCanonical();
  this._super$flushCanonical();
};

ManyRelationship.prototype._super$removeRecordFromOwn = Relationship.prototype.removeRecordFromOwn;
ManyRelationship.prototype.removeRecordFromOwn = function(record, idx) {
  if (!this.members.has(record)) {
    return;
  }
  this._super$removeRecordFromOwn(record, idx);
  if (idx !== undefined) {
    //TODO(Igor) not used currently, fix
    this.manyArray.currentState.removeAt(idx);
  } else {
    this.manyArray.internalRemoveRecords([record]);
  }
};

ManyRelationship.prototype.notifyRecordRelationshipAdded = function(record, idx) {
  assertPolymorphicType(this.record, this.relationshipMeta, record);

  this.record.notifyHasManyAdded(this.key, record, idx);
};

ManyRelationship.prototype.reload = function() {
  var self = this;
  var manyArrayLoadedState = this.manyArray.get('isLoaded');

  if (this._loadingPromise) {
    if (this._loadingPromise.get('isPending')) {
      return this._loadingPromise;
    }
    if (this._loadingPromise.get('isRejected')) {
      this.manyArray.set('isLoaded', manyArrayLoadedState);
    }
  }

  if (this.link) {
    return this.fetchLink();
  } else {
    return this.store.scheduleFetchMany(this.manyArray.toArray()).then(function() {
      //Goes away after the manyArray refactor
      self.manyArray.set('isLoaded', true);
      return self.manyArray;
    });
  }
};

ManyRelationship.prototype.computeChanges = function(records) {
  var members = this.canonicalMembers;
  var recordsToRemove = [];
  var length;
  var record;
  var i;

  records = setForArray(records);

  members.forEach(function(member) {
    if (records.has(member)) { return; }

    recordsToRemove.push(member);
  });

  this.removeCanonicalRecords(recordsToRemove);

  // Using records.toArray() since currently using
  // removeRecord can modify length, messing stuff up
  // forEach since it directly looks at "length" each
  // iteration
  records = records.toArray();
  length = records.length;
  for (i = 0; i < length; i++) {
    record = records[i];
    this.removeCanonicalRecord(record);
    this.addCanonicalRecord(record, i);
  }
};

ManyRelationship.prototype.fetchLink = function() {
  return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then((records) => {
    if (records.hasOwnProperty('meta')) {
      this.updateMeta(records.meta);
    }
    this.store._backburner.join(() => {
      this.updateRecordsFromAdapter(records);
      this.manyArray.set('isLoaded', true);
    });
    return this.manyArray;
  });
};

ManyRelationship.prototype.findRecords = function() {
  //TODO CLEANUP
  return this.store.findMany(this.manyArray.toArray().map((rec) => rec._internalModel)).
    then(() => {
      if (!this.manyArray.get('isDestroyed')) {
        //Goes away after the manyArray refactor
        this.manyArray.set('isLoaded', true);
      }
      return this.manyArray;
    });
};
ManyRelationship.prototype.notifyHasManyChanged = function() {
  this.record.notifyHasManyAdded(this.key);
};

ManyRelationship.prototype.getRecords = function() {
  //TODO(Igor) sync server here, once our syncing is not stupid
  if (this.isAsync) {
    var promise;
    if (this.link) {
      if (this.hasLoaded) {
        promise = this.findRecords();
      } else {
        promise = this.findLink().then(() => this.findRecords());
      }
    } else {
      promise = this.findRecords();
    }
    this._loadingPromise = PromiseManyArray.create({
      content: this.manyArray,
      promise: promise
    });
    return this._loadingPromise;
  } else {
    assert("You looked up the '" + this.key + "' relationship on a '" + this.record.type.modelName + "' with id " + this.record.id +  " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", this.manyArray.isEvery('isEmpty', false));

    //TODO(Igor) WTF DO I DO HERE?
    if (!this.manyArray.get('isDestroyed')) {
      this.manyArray.set('isLoaded', true);
    }
    return this.manyArray;
  }
};

function setForArray(array) {
  var set = new OrderedSet();

  if (array) {
    for (var i=0, l=array.length; i<l; i++) {
      set.add(array[i]);
    }
  }

  return set;
}


text:
  <form>
    <mat-form-field id="address-input">
      <input #addressInput matInput placeholder="Address" [value]="address" type="text">
    </mat-form-field>
  </form>

    <button mat-icon-button
            disableRipple
            class="active"
            matTooltip="go to address"
            (click)="goto(addressInput.value)">
      <mat-icon>near_me</mat-icon>
    </button>
    <button mat-icon-button
            disableRipple
            [class.inactive]="!markersOn"
            [class.active]="markersOn"
            matTooltip="toggle on/off marker editing"
            (click)="toggleMarkers(!markersOn)">
      <mat-icon>pin_drop</mat-icon>
    </button>
    <button mat-icon-button
            disableRipple
            [class.inactive]="!airportsOn"
            [class.active]="airportsOn"
            matTooltip="togglee on/off vector tile layer"
            (click)="toggleAirports(!airportsOn)">
      <mat-icon>flight</mat-icon>
    </button>


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

//go:build ignore
// +build ignore

/*
Input to cgo -godefs.  See README.md
*/

package unix

/*
#include <net/if.h>
#include <sys/sockio.h>
#include <sys/stropts.h>

// Many illumos distributions ship a 3rd party tun/tap driver
// from https://github.com/kaizawa/tuntap
// It supports a pair of IOCTLs defined at
// https://github.com/kaizawa/tuntap/blob/master/if_tun.h#L91-L93
#define TUNNEWPPA	(('T'<<16) | 0x0001)
#define TUNSETPPA	(('T'<<16) | 0x0002)
*/
import "C"

const (
	TUNNEWPPA = C.TUNNEWPPA
	TUNSETPPA = C.TUNSETPPA

	// sys/stropts.h:
	I_STR     = C.I_STR
	I_POP     = C.I_POP
	I_PUSH    = C.I_PUSH
	I_LINK    = C.I_LINK
	I_UNLINK  = C.I_UNLINK
	I_PLINK   = C.I_PLINK
	I_PUNLINK = C.I_PUNLINK

	// sys/sockio.h:
	IF_UNITSEL = C.IF_UNITSEL
)

type strbuf C.struct_strbuf

type Strioctl C.struct_strioctl

type Lifreq C.struct_lifreq


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file    HTBP_Inside_Squid_Filter.h
 *
 *  @author Phil Mesnier
 */
//=============================================================================

#ifndef ACE_HTBP_INSIDE_SQUID_FILTER_H
#define ACE_HTBP_INSIDE_SQUID_FILTER_H
#include /**/ "ace/pre.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "HTBP_Export.h"
#include "HTBP_Filter.h"

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

namespace ACE
{
  namespace HTBP
  {

    /**
     * @class Inside_Squid_Filter
     *
     * @brief Defines the methods in the <Filter> abstraction.
     *
     * A filter is responsible for wrapping / unwrapping messages
     * depending on direction of flow on each stream. There will be 4
     * filters participating in a session, inside-send, inside-recv,
     * outside-send, ouside-recv. It is anticipated that specialized
     * filters will be implemented that tune the filter behavior based
     * on proxy particulars. That, or there will be a matrix
     * configuration parameters that may be tweeked to match the
     * configuration.  It remains to be seen which is easier to
     * manage.
     */
    class HTBP_Export Inside_Squid_Filter : public Filter
    {
    public:
      /// Destructor.
      virtual ~Inside_Squid_Filter (void);

      /// Inside and outside Send filters need to supply a data header
      /// that sets the stage before sending the data body, and then
      /// (maybe) send a data trailer that closes the message. The
      /// data header may be formatted differently on the first
      /// message, to send optional context information.
      virtual ssize_t send_data_header (ssize_t data_len, Channel *);
      virtual ssize_t send_data_trailer (Channel *);

      /// Upon receiving data, the Channel is obliged to send an
      /// ack. This is either an empty document if this is the
      /// in-to-out stream, or a new long-duration document request if
      /// this is the out-to-in stream.
      virtual int send_ack (Channel *);
      virtual int recv_ack (Channel *);

      /// receiving data must compliment sending. In the case of an
      /// in-to-out stream. It is possible that the stream identity is
      /// not known until the first request is received. In this case
      /// the filter will have to look lookup the received session ID
      /// and either create a new instance or reassign itself to an
      /// existing sesion. In that case, the associated stream will
      /// have to be reassigned as well.
      ///
      virtual ssize_t recv_data_header (Channel *);
      virtual ssize_t recv_data_trailer(Channel *);
    private:
      int make_request_header (Channel *, const char *, char *, size_t );

    };
  }
}

ACE_END_VERSIONED_NAMESPACE_DECL

#if defined (__ACE_INLINE__)
#include "HTBP_Inside_Squid_Filter.inl"
#endif

#include /**/ "ace/post.h"
#endif /* ACE_HTBP_FILTER_H */


text:
package org.jboss.weld.tests.extensions.lifecycle;

import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.BeforeShutdown;
import javax.enterprise.inject.spi.Extension;

/**
 * @author Aaron Anderson
 * @author Ales Justin
 */
public class BeforeShutdownExt implements Extension {
    public void beforeShutdown(@Observes BeforeShutdown bfs, BeanManager bm) {
        System.out.format("BeforeShutdown \n");
    }
}


text:
<?php

namespace CallFire\Api\Rest\Client;

use CallFire\Api\Rest\AbstractClient;
use CallFire\Api\Rest\Request as Request;

class Broadcast extends AbstractClient
{

    public $basePath = 'https://www.callfire.com/api/1.1/rest';

    /**
     * Creates a new Broadcast
     *
     * This operation creates a Broadcast campaign and returns a broadcastId. To see
     * the status of this campaign call GetBroadcast with the returned broadcastId.
     * There are 3 types of Broadcast: TEXT, IVR, or VOICE. Select the appropriate
     * config to match the broadcast type, TextBroadcastConfig, IvrBroadcastConfig, or
     * VoiceBroadcastConfig. Prefer the Text Service operations (ex: SendText) and Call
     * Service operations (ex: SendCall) over this operation when managing simple text
     * and call campaigns since those operations are simpler and more concise.
     *
     * @api
     * @param Request\CreateBroadcast $CreateBroadcast = null
     */
    public function CreateBroadcast(Request\CreateBroadcast $CreateBroadcast = null)
    {
        $uri = $this->getUri('/broadcast', array());

        return $this->post($uri, $CreateBroadcast);
    }

    /**
     * Lists existing Broadcasts
     *
     * Use this operation to see the status of Broadcasts in account. Filter by type of
     * campaign whether currently running. Returns a list of Broadcast info such as
     * campaign name, type, status, ect...
     *
     * @api
     * @param Request\QueryBroadcasts $QueryBroadcasts = null
     */
    public function QueryBroadcasts(Request\QueryBroadcasts $QueryBroadcasts = null)
    {
        $uri = $this->getUri('/broadcast', array());

        return $this->get($uri, $QueryBroadcasts);
    }

    /**
     * Gets a single Broadcast by ID
     *
     * Use ID returned from CreateBroadcast or from QueryBroadcast to retreive
     * information on indivual Broadcast. Include info such as campaign name, type,
     * status, ect...
     *
     * @api
     * @param int $Id Unique ID of resource
     */
    public function GetBroadcast($Id)
    {
        $uri = $this->getUri('/broadcast/%s', array($Id));

        return $this->get($uri);
    }

    /**
     * Gets performance and result statistics for a Broadcast
     *
     * Get broadcast stats by broadcastId or by interval range. Stats include
     * information like billed amount, billed duration, actions count, attempt count,
     * etc...
     *
     * @api
     * @param int                       $Id                Unique ID of resource
     * @param Request\GetBroadcastStats $GetBroadcastStats
     */
    public function GetBroadcastStats($Id, Request\GetBroadcastStats $GetBroadcastStats)
    {
        $uri = $this->getUri('/broadcast/%s/stats', array($Id));

        return $this->get($uri, $GetBroadcastStats);
    }

    /**
     * Starts, Stops or Archives a Broadcast
     *
     * Apply command START, STOP, or ARCHIVE to Broadcast. Also can change the max
     * active count of Broadcast.
     *
     * @api
     * @param int                      $Id               Unique ID of resource
     * @param Request\ControlBroadcast $ControlBroadcast
     */
    public function ControlBroadcast($Id, Request\ControlBroadcast $ControlBroadcast)
    {
        $uri = $this->getUri('/broadcast/%s/control', array($Id));

        return $this->put($uri, $ControlBroadcast);
    }

    /**
     * Creates a new ContactBatch
     *
     * Contact Batch is a list of contacts to associate with a broadcast. Use this
     * operation to attach a list of contacts to an existing Campaign. A list of
     * ToNumbers or an existing Contact List ID is required to create and attach the
     * Contact List. Returned is the unique contactListId that can be used in
     * ControlContactBatch to enable or disable this batch.
     *
     * @api
     * @param int                        $BroadcastId        Id of Broadcast
     * @param Request\CreateContactBatch $CreateContactBatch
     */
    public function CreateContactBatch($BroadcastId, Request\CreateContactBatch $CreateContactBatch)
    {
        $uri = $this->getUri('/broadcast/%s/batch', array($BroadcastId));

        return $this->post($uri, $CreateContactBatch);
    }

    /**
     * Lists a Broadcast's ContactBatch
     *
     * Return list of Contact Batches associated with this Broadcast. The
     * contactBatchIds returned from this campaign can then be used to enable, disable,
     * or delete the individual Batches.
     *
     * @api
     * @param int                         $BroadcastId         Unique ID of Broadcast
     * @param Request\QueryContactBatches $QueryContactBatches
     */
    public function QueryContactBatches($BroadcastId, Request\QueryContactBatches $QueryContactBatches)
    {
        $uri = $this->getUri('/broadcast/%s/batch', array($BroadcastId));

        return $this->get($uri, $QueryContactBatches);
    }

    /**
     * Gets a ContactBatch by ID
     *
     * Retrieve info on individual Contact Batch using contactId returned from
     * CreateContactBatch
     *
     * @api
     * @param int $Id Unique ID of resource
     */
    public function GetContactBatch($Id)
    {
        $uri = $this->getUri('/broadcast/batch/%s', array($Id));

        return $this->get($uri);
    }

    /**
     * Enables or Disables a Broadcast's ContactBatch
     *
     * This operation provides the ability to enable or disable on a Broadcast the list
     * of contacts associated with a ContactBatch.
     *
     * @api
     * @param int                         $Id                  Unique ID of resource
     * @param Request\ControlContactBatch $ControlContactBatch
     */
    public function ControlContactBatch($Id, Request\ControlContactBatch $ControlContactBatch)
    {
        $uri = $this->getUri('/broadcast/batch/%s/control', array($Id));

        return $this->put($uri, $ControlContactBatch);
    }

    /**
     * Creates a new Schedule for a Broadcast
     *
     * Broadcast can be set to run at scheduled times a prescribed by
     * BroadcastSchedule. Can pick start time, stop time, begin date, and day of week.
     * Returns broadcastScheduleId that can be used in GetBroadcastSchedule and
     * DeleteBroadcastSchedule
     *
     * @api
     * @param int                             $BroadcastId
     * @param Request\CreateBroadcastSchedule $CreateBroadcastSchedule
     */
    public function CreateBroadcastSchedule($BroadcastId, Request\CreateBroadcastSchedule $CreateBroadcastSchedule)
    {
        $uri = $this->getUri('/broadcast/%s/schedule', array($BroadcastId));

        return $this->post($uri, $CreateBroadcastSchedule);
    }

    /**
     * Lists existing BroadcastSchedules
     *
     * List information about Broadcast Schedules attached to a Broadcast.
     *
     * @api
     * @param int                            $BroadcastId            Unique ID of Broadcast
     * @param Request\QueryBroadcastSchedule $QueryBroadcastSchedule
     */
    public function QueryBroadcastSchedule($BroadcastId, Request\QueryBroadcastSchedule $QueryBroadcastSchedule)
    {
        $uri = $this->getUri('/broadcast/%s/schedule', array($BroadcastId));

        return $this->get($uri, $QueryBroadcastSchedule);
    }

    /**
     * Gets a BroadcastSchedule by ID
     *
     * List information about individual Broadcast Schedule attached to a Broadcast.
     *
     * @api
     * @param int $Id Unique ID of resource
     */
    public function GetBroadcastSchedule($Id)
    {
        $uri = $this->getUri('/broadcast/schedule/%s', array($Id));

        return $this->get($uri);
    }

    /**
     * Deletes a BroadcastSchedule by ID
     *
     * Delete BroadcastSchedule associated with a Broadcast.
     *
     * @api
     * @param int $Id Unique ID of resource
     */
    public function DeleteBroadcastSchedule($Id)
    {
        $uri = $this->getUri('/broadcast/schedule/%s', array($Id));

        return $this->delete($uri);
    }

    /**
     * Updates an existing Broadcast's configuration
     *
     * Update existing broadcast's configuration such as time zone restrictions or
     * retry logic. Currently all fields from config are updated so the 'Message' field
     * needs to be populated just like in CreateBroadcast operation.  Use unique ID to
     * specify broadcast. Need to provide dummy 'Name' field Broadcast even though the
     * field will not be overwritten.  Testing this method using swagger doc REST
     * interface (Try Me! button) does not work correctly. Please use curl or other
     * rest client to test api call.
     *
     * @api
     * @param Request\UpdateBroadcast $UpdateBroadcast = null
     * @param int                     $id
     */
    public function UpdateBroadcast($id, Request\UpdateBroadcast $UpdateBroadcast = null)
    {
        $uri = $this->getUri('/broadcast/%s', array($id));

        return $this->put($uri, $UpdateBroadcast);
    }

}


text:
package org.elasticsearch.xpack.core.ilm;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateObserver;
import org.elasticsearch.cluster.metadata.IndexMetadata;

/**
 * Invokes a open step on a single index.
 */

final class OpenIndexStep extends AsyncActionStep {

    static final String NAME = "open-index";

    OpenIndexStep(StepKey key, StepKey nextStepKey, Client client) {
        super(key, nextStepKey, client);
    }

    @Override
    public void performAction(IndexMetadata indexMetadata, ClusterState currentClusterState,
                              ClusterStateObserver observer, ActionListener<Boolean> listener) {
        if (indexMetadata.getState() == IndexMetadata.State.CLOSE) {
            OpenIndexRequest request = new OpenIndexRequest(indexMetadata.getIndex().getName());
            getClient().admin().indices()
                .open(request,
                    ActionListener.wrap(openIndexResponse -> {
                        if (openIndexResponse.isAcknowledged() == false) {
                            throw new ElasticsearchException("open index request failed to be acknowledged");
                        }
                        listener.onResponse(true);
                    }, listener::onFailure));

        } else {
            listener.onResponse(true);
        }
    }

    @Override
    public boolean isRetryable() {
        return true;
    }
}


text:
package io.undertow.server.protocol.http;

import io.undertow.UndertowOptions;
import io.undertow.testutils.category.UnitTest;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import io.undertow.util.Protocols;
import io.undertow.util.BadRequestException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.xnio.OptionMap;

import java.nio.ByteBuffer;

/**
 * Tests that the parser can resume when it is given partial input
 *
 * @author Stuart Douglas
 */
@Category(UnitTest.class)
public class ParserResumeTestCase {

    public static final String DATA = "GET http://www.somehost.net/apath+with+spaces%20and%20I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%C3%A0li%C5%BE%C3%A6ti%C3%B8n?key1=value1&key2=I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%C3%A0li%C5%BE%C3%A6ti%C3%B8n HTTP/1.1\r\nHost:   www.somehost.net\r\nOtherHeader: some\r\n    value\r\nHostee:another\r\nAccept-garbage:   a\r\n\r\ntttt";
    public static final HttpRequestParser PARSER = HttpRequestParser.instance(OptionMap.create(UndertowOptions.ALLOW_ENCODED_SLASH, true));

    final ParseState context = new ParseState(10);
    @Test
    public void testMethodSplit() {
        byte[] in = DATA.getBytes();
        for (int i = 0; i < in.length - 4; ++i) {
            try {
                testResume(i, in);
            } catch (Throwable e) {
                throw new RuntimeException("Test failed at split " + i, e);
            }
        }
    }

    @Test
    public void testOneCharacterAtATime() throws BadRequestException {
        context.reset();
        byte[] in = DATA.getBytes();
        HttpServerExchange result = new HttpServerExchange(null);
        ByteBuffer buffer = ByteBuffer.wrap(in);
        int oldLimit = buffer.limit();
        buffer.limit(1);
        while (context.state != ParseState.PARSE_COMPLETE) {
            PARSER.handle(buffer, context, result);
            if(context.state != ParseState.PARSE_COMPLETE) {
                buffer.limit(buffer.limit() + 1);
            }
        }
        Assert.assertEquals(oldLimit, buffer.limit() + 4);
        runAssertions(result);
    }

    private void testResume(final int split, byte[] in) throws BadRequestException {
        context.reset();
        HttpServerExchange result = new HttpServerExchange(null);
        ByteBuffer buffer = ByteBuffer.wrap(in);
        buffer.limit(split);
        PARSER.handle(buffer, context, result);
        buffer.limit(buffer.capacity());
        PARSER.handle(buffer, context, result);
        runAssertions(result);
        Assert.assertEquals(4, buffer.remaining());
    }

    private void runAssertions(final HttpServerExchange result) {
        Assert.assertSame(Methods.GET, result.getRequestMethod());
        Assert.assertEquals("/apath with spaces and Iñtërnâtiônàližætiøn", result.getRelativePath());
        Assert.assertEquals("http://www.somehost.net/apath+with+spaces%20and%20I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%C3%A0li%C5%BE%C3%A6ti%C3%B8n", result.getRequestURI());
        Assert.assertSame(Protocols.HTTP_1_1, result.getProtocol());

        Assert.assertEquals("www.somehost.net", result.getRequestHeaders().getFirst(new HttpString("Host")));
        Assert.assertEquals("some value", result.getRequestHeaders().getFirst(new HttpString("OtherHeader")));
        Assert.assertEquals("another", result.getRequestHeaders().getFirst(new HttpString("Hostee")));
        Assert.assertEquals("a", result.getRequestHeaders().getFirst(new HttpString("Accept-garbage")));
        Assert.assertEquals(4, result.getRequestHeaders().getHeaderNames().size());

        Assert.assertEquals(ParseState.PARSE_COMPLETE, context.state);
        Assert.assertEquals("key1=value1&key2=I%C3%B1t%C3%ABrn%C3%A2ti%C3%B4n%C3%A0li%C5%BE%C3%A6ti%C3%B8n", result.getQueryString());
        Assert.assertEquals("value1", result.getQueryParameters().get("key1").getFirst());
        Assert.assertEquals("Iñtërnâtiônàližætiøn", result.getQueryParameters().get("key2").getFirst());
    }

}


text:
package compressionservice.handlers.models;

import java.util.UUID;

import compressionservice.runner.state.TaskState;
import compressionservice.runner.state.TaskStateModel;

public class TaskStateExtendedModel
{
    public final UUID requestId;
    public final TaskState state;
    public final String message;
    public final String opLog;

    public TaskStateExtendedModel(TaskStateModel taskStateModel, String opLog) {
        this.requestId = taskStateModel.requestId;
        this.state = taskStateModel.state;
        this.message = taskStateModel.message;
        this.opLog = opLog;
    }
}


text:
<resources>
    <string name="app_name">Parking Spaces</string>
    <string name="error">Error loading parking spaces</string>
</resources>


text:
Meteor.startup(function() {
	RocketChat.roomTypes.setPublish('c', function(identifier) {
		const options = {
			fields: {
				name: 1,
				t: 1,
				cl: 1,
				u: 1,
				usernames: 1,
				topic: 1,
				announcement: 1,
				muted: 1,
				archived: 1,
				ro: 1,
				reactWhenReadOnly: 1,
				jitsiTimeout: 1,
				description: 1,
				sysMes: 1,
				joinCodeRequired: 1
			}
		};

		if (RocketChat.authz.hasPermission(this.userId, 'view-c-room')) {
			return RocketChat.models.Rooms.findByTypeAndName('c', identifier, options);
		} else if (RocketChat.authz.hasPermission(this.userId, 'view-joined-room')) {
			const roomId = RocketChat.models.Subscriptions.findByTypeNameAndUserId('c', identifier, this.userId).fetch();
			if (roomId.length > 0) {
				return RocketChat.models.Rooms.findById(roomId[0].rid, options);
			}
		}

		return this.ready();
	});

	RocketChat.roomTypes.setPublish('p', function(identifier) {
		const options = {
			fields: {
				name: 1,
				t: 1,
				cl: 1,
				u: 1,
				usernames: 1,
				topic: 1,
				announcement: 1,
				muted: 1,
				archived: 1,
				ro: 1,
				reactWhenReadOnly: 1,
				jitsiTimeout: 1,
				description: 1,
				sysMes: 1,
				tokenpass: 1
			}
		};

		const user = RocketChat.models.Users.findOneById(this.userId, {
			fields: {
				username: 1
			}
		});

		return RocketChat.models.Rooms.findByTypeAndNameContainingUsername('p', identifier, user.username, options);
	});

	return RocketChat.roomTypes.setPublish('d', function(identifier) {
		const options = {
			fields: {
				name: 1,
				t: 1,
				cl: 1,
				u: 1,
				usernames: 1,
				topic: 1,
				jitsiTimeout: 1
			}
		};

		const user = RocketChat.models.Users.findOneById(this.userId, {
			fields: {
				username: 1
			}
		});

		if (RocketChat.authz.hasAtLeastOnePermission(this.userId, ['view-d-room', 'view-joined-room'])) {
			return RocketChat.models.Rooms.findByTypeContainingUsernames('d', [user.username, identifier], options);
		}

		return this.ready();
	});
});


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE Test SYSTEM "test.dtd">
<Test
	ID="ObjectTest002"
	date-of-creation="2005-10-01"
	timeout="1"
	>

		<Copyright value="apache"/>
		<Author value="Aleksander Budniy"/>
		<Description>
            This tests case exercises the JDWP agent under ObjectIDs stressing. First
			test runs VirtualMachine.AllThreads command, creates separate
			thread and run it vast number of time, runs
			VirtualMachine.AllThreads command again, checks number of
			running threads. Then it runs VirtualMachine.DisposeObjects
			and disposes some number of ThreadIDs. For each thread test checks
			ReferenceType, Name, and Status, and expects proper number of
			INVALID_OBJECTID errors.
   		</Description>

		<Keyword name="stress"/>
		<Keyword name="jpda"/>
		<Source name="ObjectTest002.java"/>
		<Source name="ObjectDebuggee002.java"/>
		<Modification date="2005-10-01" author="Aleksander Bydniy"/>

		<Runner ID="Runtime">
			<Option name="-Djpda.settings.timeout=300000"/>
			<Param name="toRun" value="org.apache.harmony.test.stress.jpda.jdwp.scenario.OBJECT002.ObjectTest002">
			</Param>
		</Runner>
</Test>


text:
package htmlutil

import (
	"strings"

	"golang.org/x/net/html/atom"
)

type AtomSet map[atom.Atom]struct{}

func NewAtomSet(atoms []atom.Atom) AtomSet {
	s := AtomSet{}
	for _, t := range atoms {
		s[t] = struct{}{}
	}
	return s
}

func NewAtomSetFromString(s string) AtomSet {
	atoms := []atom.Atom{}
	for _, token := range strings.Fields(s) {
		a := atom.Lookup([]byte(token))
		if a > 0 {
			atoms = append(atoms, a)
		}
	}
	return NewAtomSet(atoms)
}

func (s AtomSet) Has(a atom.Atom) bool {
	if s == nil {
		return false
	}
	_, ok := s[a]
	return ok
}

func (s AtomSet) HasName(name []byte) bool {
	a := atom.Lookup(name)
	if a == 0 {
		return false
	}
	return s.Has(a)
}

var (
	Codes      = NewAtomSetFromString("style script link")
	Blocks     = NewAtomSetFromString("address article aside audio blockquote canvas dd div dl fieldset figcaption figure figcaption footer form h1 h2 h3 h4 h5 h6 header hgroup hr noscript ol output p pre section table tfoot ul video")
	Containers = NewAtomSetFromString("article aside div footer header hgroup section")
	Headers    = NewAtomSetFromString("h1 h2 h3 h4 h5 h6 h7")
	Voids      = NewAtomSetFromString("area base br col embed hr img input keygen link meta param source track wbr")
)


text:
#import "ABI10_0_0RCTImageLoader.h"

@interface ABI10_0_0RCTGIFImageDecoder : NSObject <ABI10_0_0RCTImageDataDecoder>

@end


text:
// Problem 2: Write a script that compares two char arrays lexicographically (letter by letter).

var firstCharArray = ['n','m','o'];
var secondCharArray = ['n', 'm', 'i'];
var isEqual = true;

if (firstCharArray.length === secondCharArray.length) {
    for (var i = 0; i < firstCharArray.length; i++) {
        if (firstCharArray[i] !== secondCharArray[i]) {
            isEqual = false;
            break;
        }
    }
} else {
    isEqual = false;
}

console.log('Char arrays are equal? --> ' + isEqual);


text: export { default } from '@cardstack/tools/components/cs-editor-switch';


text:
return {
  {
    name = "2015-08-21_init_response-rate-limiting",
    up = [[
      CREATE TABLE IF NOT EXISTS response_ratelimiting_metrics(
        api_id uuid,
        identifier text,
        period text,
        period_date timestamp,
        value counter,
        PRIMARY KEY ((api_id, identifier, period_date, period))
      );
    ]],
    down = [[
      DROP TABLE response_ratelimiting_metrics;
    ]]
  },
  {
    name = "2016-08-04-321512_response-rate-limiting_policies",
    up = function(_, _, dao)
      local rows, err = dao.plugins:find_all {name = "response-ratelimiting"}
      if err then return err end

      for i = 1, #rows do
        local response_rate_limiting = rows[i]

        -- Delete the old one to avoid conflicts when inserting the new one
        local _, err = dao.plugins:delete(response_rate_limiting)
        if err then return err end

        local _, err = dao.plugins:insert {
          name = "response-ratelimiting",
          api_id = response_rate_limiting.api_id,
          consumer_id = response_rate_limiting.consumer_id,
          enabled = response_rate_limiting.enabled,
          config = {
            second = response_rate_limiting.config.second,
            minute = response_rate_limiting.config.minute,
            hour = response_rate_limiting.config.hour,
            day = response_rate_limiting.config.day,
            month = response_rate_limiting.config.month,
            year = response_rate_limiting.config.year,
            block_on_first_violation = response_rate_limiting.config.block_on_first_violation,
            limit_by = "consumer",
            policy = "cluster",
            fault_tolerant = response_rate_limiting.config.continue_on_error
          }
        }
        if err then return err end
      end
    end
  }
}


text:
require 'nimbu-api/utils/json'

module Nimbu
  # Raised when Nimbu returns any of the HTTP status codes
  module Error
    class ServiceError < NimbuError
      include ::Nimbu::Utils::Json

      attr_reader :http_headers
      attr_reader :http_body

      attr_reader :status

      def initialize(response)
        @http_headers = response[:response_headers]
        @status = response[:status]

        message = parse_response(response)
        super(message)
      end

      def parse_response(response)
        body = parse_body(response[:body])
        "#{response[:method].to_s.upcase} #{response[:url].to_s}: #{response[:status]} #{body}"
      end

      def decode_body(body)
        if body.respond_to?(:to_str) && body.length >= 2
           decode body, :symbolize_keys => true
        else
          body
        end
      end

      def parse_body(body)
        body = decode_body(body)

        return '' if body.nil? || body.empty?

        if body[:error]
          body[:error]
        elsif body[:errors]
          error = Array(body[:errors]).first
          if error.kind_of?(Hash)
            error[:message]
          else
            error
          end
        elsif body[:message]
          body[:message]
        else
          ''
        end
      end

      def self.http_status_code(code)
        define_method(:http_status_code) { code }
      end

      def self.errors
        @errors ||= Hash[
          descendants.map { |klass| [klass.new({}).http_status_code, klass] }
        ]
      end

    end
  end # Error
end # Nimbu


text:
  <alerts fixed="true" channels="status/general" types="SUCCESS, INFO, ERROR, WARNING" view="views/customAlert.html" exclusive></alerts>

    Status
    Service Name
    Notes

      {{service.name}}

          {{note.noteType | replaceUnderscore}} {{note.title}}

<button class="btn btn-primary" ng-if="showShortList" ng-click="showHideShortList()">Show All Services</button>
<button class="btn btn-primary" ng-if="!showShortList" ng-click="showHideShortList()">Collapse</button>

Notes

      Note

          <note note="note" link="true"></note>


text:
'use strict';

/**
 * Requirements
 */
let Entity = require(SOURCE_ROOT + '/model/entity/Entity.js').Entity;
let MissingArgumentError = require(SOURCE_ROOT + '/error/MissingArgumentError.js').MissingArgumentError;
let compact = require(FIXTURES_ROOT + '/Entities/Compact.js');
let baseValueObjectSpec = require('../BaseValueObjectShared.js').spec;
let co = require('co');

/**
 * Spec
 */
describe(Entity.className, function()
{
    baseValueObjectSpec(Entity, 'model.entity/Entity', function(parameters)
    {
        parameters.unshift(fixtures.entityIdGallery);
        return parameters;
    });

    beforeEach(function()
    {
        fixtures = compact.createFixture();
    });

    describe('#constructor()', function()
    {
        it('should throw a exception when created without a id', function()
        {
            expect(function() { new Entity(); }).to.throw(MissingArgumentError);
        });

        it('should throw a exception when created without a proper id type', function()
        {
            expect(function() { new Entity('Category'); }).to.throw(TypeError);
        });
    });

    describe('#update', function()
    {
        it('should allow to update id', function()
        {
            let promise = co(function *()
            {
                let data = new Entity(fixtures.entityIdGallery);
                let testee = new Entity(fixtures.entityIdButton);
                yield testee.update(data);
                expect(testee.id).to.be.equal(data.id);
            });
            return promise;
        });
    });
});


text:
package madgik.exareme.utils.embedded.db;

import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author herald
 */
public class SQLite {

  private static Logger log = Logger.getLogger(SQLite.class);

  private SQLite() {
  }

  public static Connection createConnection(String database) throws SQLException {
    try {
      Class.forName("org.sqlite.JDBC");
    } catch (Exception e) {
      throw new SQLException("SQLite driver not found", e);
    }
    Connection conn = DriverManager.getConnection("jdbc:sqlite:" + database);
    return conn;
  }
}


text: ![overview](overview.svg)


text:
// Copyright(c) 2016 Guus Waals (guus_waals@live.nl)
// Licensed under the MIT License(MIT)
// See "LICENSE.txt" for more information

using OpenTK.Graphics;

namespace FX2.Game
{
    public static class ColorExtensions
    {
        public static Color4 WithAlpha(this Color4 color, float alpha)
        {
            return new Color4(color.R, color.G, color.B, alpha);
        }
        public static Color4 Scale(this Color4 color, float mult)
        {
            return new Color4(color.R * mult, color.G * mult, color.B * mult, color.A);
        }
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>Ssl  · Shiraaz Moollatjie</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1">

<meta name="description" content="" />

<meta name="keywords" content="">

<meta property="og:title" content="Ssl  · Shiraaz Moollatjie ">
<meta property="og:site_name" content="Shiraaz Moollatjie"/>
<meta property="og:url" content="http://shiraazmoollatjie.github.io/tags/ssl/" />
<meta property="og:locale" content="en-us">

<meta property="og:type" content="website" />

<link href="http://shiraazmoollatjie.github.io/tags/ssl/index.xml" rel="alternate" type="application/rss+xml" title="Ssl" />

<link rel="canonical" href="http://shiraazmoollatjie.github.io/tags/ssl/" />

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://shiraazmoollatjie.github.io/touch-icon-144-precomposed.png">
<link href="http://shiraazmoollatjie.github.io/favicon.png" rel="icon">

<meta name="generator" content="Hugo 0.45" />

<link href='https://fonts.googleapis.com/css?family=Merriweather:300%7CRaleway%7COpen+Sans' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/css/highlight/monokai.css">

  Shiraaz Moollatjie

  Satisfying my curiosity of technology by writing and sharing.

About

Posts

Tags

  github

  linkedin

Ssl

How to configure Spring Boot with SSL

  back to top

  © 2018 Shiraaz Moollatjie.


text:
package com.missionhub.activity;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.missionhub.application.Application;

public class LicensesActivity extends BaseActivity {

    private WebView mWebView;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mWebView = new WebView(this);
        mWebView.setBackgroundColor(0xFFEEEEEE);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
                view.loadUrl(url);
                return true;
            }
        });
        mWebView.loadUrl("file:///android_asset/licenses.html");

        setContentView(mWebView);
    }

    @Override
    public void onStart() {
        super.onStart();

        Application.trackView("Licenses");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
'use strict';

(function() {
	// Projects Controller Spec
	describe('ProjectsController', function() {
		// Initialize global variables
		var ProjectsController,
			scope,
			$httpBackend,
			$stateParams,
			$location;

		// The $resource service augments the response object with methods for updating and deleting the resource.
		// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
		// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
		// When the toEqualData matcher compares two objects, it takes only object properties into
		// account and ignores methods.
		beforeEach(function() {
			jasmine.addMatchers({
				toEqualData: function(util, customEqualityTesters) {
					return {
						compare: function(actual, expected) {
							return {
								pass: angular.equals(actual, expected)
							};
						}
					};
				}
			});
		});

		// Then we can start by loading the main application module
		beforeEach(module(ApplicationConfiguration.applicationModuleName));

		// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
		// This allows us to inject a service but then attach it to a variable
		// with the same name as the service.
		beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
			// Set a new global scope
			scope = $rootScope.$new();

			// Point global variables to injected services
			$stateParams = _$stateParams_;
			$httpBackend = _$httpBackend_;
			$location = _$location_;

			// Initialize the Projects controller.
			ProjectsController = $controller('ProjectsController', {
				$scope: scope
			});
		}));

		it('$scope.init() should create an array with at least one project object fetched from XHR', inject(function(Projects) {
			// Create sample project using the Projects service
			var sampleProject = new Projects({
				projectCode: 'ABC',
				description: 'MEAN rocks!',
				due: '2014-10-30'
			});

			// Create a sample projects array that includes the new project
			var sampleProjects = [sampleProject];

			// Account for the Customers query
			$httpBackend.expectGET('customers').respond();

			// Account for the Organisms query
			$httpBackend.expectGET('organisms').respond();

			// Set GET response
			$httpBackend.expectGET('projects').respond(sampleProjects);

			// Run controller functionality
			scope.init();
			$httpBackend.flush();

			// Test scope value
			expect(scope.projects).toEqualData(sampleProjects);
		}));

		it('$scope.findOne() should create an array with one project object fetched from XHR using a projectId URL parameter', inject(function(Projects) {
			// Define a sample project object
			var sampleProject = new Projects({
				projectCode: 'ABC',
				description: 'MEAN rocks!',
                plates: []
			});

			// Set the URL parameter
			$stateParams.projectId = '525a8422f6d0f87f0e407a33';

			// Account for the Customer query
			$httpBackend.expectGET('customers').respond();

			// Account for the Organisms query
			$httpBackend.expectGET('organisms').respond();

			// Set GET response
			$httpBackend.expectGET(/projects\/([0-9a-fA-F]{24})$/).respond(sampleProject);

			// Run controller functionality
			scope.findOne();
			$httpBackend.flush();

			// Test scope value
			expect(scope.project).toEqualData(sampleProject);
		}));

		it('$scope.numSamples() should return the total number of samples in a project', inject(function(Projects) {
			// Create a sample project with a couple plates with samples inside
			scope.project = new Projects({
        plates: [{
        	samples: ['sample0', 'sample1']
        }, {
        	samples: ['sample2', 'sample3', 'sample4']
        }]
			});

			expect(scope.numSamples()).toBe(5);
		}));

		it('$scope.numSamples() should return 0 when $scope.project is undefined', inject(function() {
			delete scope.project;

			expect(scope.numSamples()).toBe(0);
		}));

		it('$scope.numSamples() should return 0 when $scope.project.plates is undefined', inject(function(Projects) {
			scope.project = new Projects({});

			expect(scope.numSamples()).toBe(0);
		}));

		it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Projects, Customers, Organisms) {
			// Create a sample customer object
			var sampleCustomer = new Customers({
			  _id: '525cf20451979dea2c000002',
			  name: 'University of Florida',
			  id: 37,
			  code: 'UFL'
			});

			// Create a sample organism object
			var sampleOrganism = new Organisms({
			  _id: '525cf20451979dea2c000003',
			  id: 1,
			  name: 'Burrito'
			});

			// Create a sample project object
			var sampleProjectPostData = new Projects({
			  projectCode: 'ABC',
			  description: 'MEAN rocks!',
			  customer: sampleCustomer._id,
			  organism: sampleOrganism._id
			});

			// Create a sample project response
			var sampleProjectResponse = new Projects({
			  _id: '525cf20451979dea2c000001',
			  projectCode: 'ABC',
			  description: 'MEAN rocks!'
			});

			// Create organism and customer responses
			var customerResponse = [sampleCustomer];
			var organismResponse = [sampleOrganism];
			scope.customer.selected = sampleCustomer;
			scope.organism.selected = sampleOrganism;

			// Fixture mock form input values
			scope.projectCode = function() { return 'ABC';};
			scope.description = 'MEAN rocks!';

			// Account for customers query
			$httpBackend.expectGET('customers').respond(customerResponse);

			// Account for organisms query
			$httpBackend.expectGET('organisms').respond(organismResponse);

			// Set POST response
			$httpBackend.expectPOST('projects', sampleProjectPostData).respond(sampleProjectResponse);

			// Run controller functionality
			scope.create();
			$httpBackend.flush();

			// Test form inputs are reset
			expect(scope.projectCode).toEqual('');
			expect(scope.description).toEqual('');

			// Test URL redirection after the project was created
			expect($location.path()).toBe('/projects/' + sampleProjectResponse._id);
		}));

		it('$scope.create() should throw an error if a customer or organism hasn\'t been selected' , inject(function(Projects, Customers, Organisms) {
			scope.create();
			expect(scope.error).toBe('Customer and Organism must be selected');
		}));

		it('$scope.update() should update a valid project', inject(function(Projects, Customers, Organisms) {
			// Create a sample customer object
			var sampleCustomer = new Customers({
			  _id: '525cf20451979dea2c000002',
			  name: 'University of Florida',
			  id: 37,
			  code: 'UFL'
			});

			// Create a sample organism object
			var sampleOrganism = new Organisms({
			  _id: '525cf20451979dea2c000003',
			  id: 1,
			  name: 'Burrito'
			});

			// Define a sample project put data
			var sampleProjectPutData = new Projects({
				_id: '525cf20451979dea2c000001',
				projectcode: 'ABC',
				description: 'MEAN Rocks!'
			});

			// Mock project in scope
			scope.project = sampleProjectPutData;
			scope.selectedCustomer = {selected: sampleCustomer};
			scope.selectedOrganism = {selected: sampleCustomer};

			// Account for the Customer query
			$httpBackend.expectGET('customers').respond();

			// Account for the Organisms query
			$httpBackend.expectGET('organisms').respond();

			// Set PUT response
			$httpBackend.expectPUT(/projects\/([0-9a-fA-F]{24})$/).respond();

			// Run controller functionality
			scope.update();
			$httpBackend.flush();

			// Test URL location to new object
			expect($location.path()).toBe('/projects/' + sampleProjectPutData._id);
		}));

		it('$scope.remove() should send a DELETE request with a valid projectId and remove the project from the scope', inject(function(Projects) {
			// Create new project object
			var sampleProject = new Projects({
				_id: '525a8422f6d0f87f0e407a33'
			});

			// Create new projects array and include the project
			scope.projects = [sampleProject];

			// Account for the Customer query
			$httpBackend.expectGET('customers').respond();

			// Account for the Organisms query
			$httpBackend.expectGET('organisms').respond();

			// Set expected DELETE response
			$httpBackend.expectDELETE(/projects\/([0-9a-fA-F]{24})$/).respond(204);

			// Run controller functionality
			scope.remove(sampleProject);
			$httpBackend.flush();

			// Test array after successful delete
			expect(scope.projects.length).toBe(0);
		}));

		it('$scope.addPlates(selectedPlates) should add the selectedPlates to the user\'s workList and trigger reload', inject(function() {
			var selectedPlates = [{isAssigned: false}, {isAssigned: false}];

			// Account for the Customer query
			$httpBackend.expectGET('customers').respond();

			// Account for the Organisms query
			$httpBackend.expectGET('organisms').respond();

			$httpBackend.expectPOST('/plates/assignPlate').respond(200);
			$httpBackend.expectPOST('/plates/assignPlate').respond(200);

			spyOn(scope, 'findOne');
			scope.addPlates(selectedPlates);
			$httpBackend.flush();
			expect(scope.findOne).toHaveBeenCalled();
		}));

		it('$scope.initReactGrid() should set gridReady equal to true when done', inject(function(Projects) {
			scope.initReactGrid();
			expect(scope.gridReady).toBeTruthy();
		}));

		it('$scope.initReactGrid() should set $scope.grid.data equal to scope.projects modified', inject(function(Projects) {
			var sampleProject = new Projects({
				_id: '525a8422f6d0f87f0e407a33',
				due: '2014-10-30'
			});

			// Create new projects array and include the project
			scope.projects = [sampleProject];

			scope.initReactGrid();

			// Modify sampleProject
			sampleProject.projectStatus = 'In Progress';

			expect(scope.grid.data).toEqualData([sampleProject]);
		}));

		it('$scope.initReactGrid() should convert the due date to yyyy-mm-dd', inject(function(Projects) {
			var sampleProject = new Projects({
				_id: '525a8422f6d0f87f0e407a33',
				due: '2014-10-30T04:00:00.000Z'
			});

			// Create new projects array and include the project
			scope.projects = [sampleProject];

			scope.initReactGrid();

			expect(scope.grid.data[0].due).toEqual('2014-10-30');
		}));

		it('$scope.initReactGrid() should correctly set projectStatus', inject(function(Projects) {
			var sampleProject = new Projects({
				_id: '525a8422f6d0f87f0e407a33',
				due: '2014-10-30T04:00:00.000Z',
				projectStatus: false
			});

			var sampleProject2 = new Projects({
				_id: '525a8422f6d0f87f0e407a33',
				due: '2014-10-30T04:00:00.000Z',
				projectStatus: true
			});

			// Create new projects array and include the project
			scope.projects = [sampleProject, sampleProject2];

			scope.initReactGrid();

			expect(scope.grid.data[0].projectStatus).toEqual('In Progress');
			expect(scope.grid.data[1].projectStatus).toEqual('Completed');
		}));

		it('$scope.projectCode() should return a unique projectCode', inject(function(Projects) {

			// Create a sample project object
			var sampleProject = new Projects({
			  projectCode: 'ABC_012345',
			  description: 'MEAN rocks!',
				due: '2014-10-30T04:00:00.000Z'
			});
			// Create a sample projects array that includes the new project
			var sampleProjects = [sampleProject];

			// Account for the Customers query
			$httpBackend.expectGET('customers').respond();

			// Account for the Organisms query
			$httpBackend.expectGET('organisms').respond();

			// Set GET response
			$httpBackend.expectGET('projects').respond(sampleProjects);

			// Run controller functionality
			scope.init();
			$httpBackend.flush();

			scope.organism = {selected: {id: 1}};
			scope.customer = {selected: {id: 23, code: 'ABC'}};

			expect(scope.projectCode()).toBe('ABC_012346');
		}));

		it('$scope.projectCode() should return the current project code if organism and customer haven\'t been changed in edit mode', inject(function(Projects) {

			// Create a sample project object
			var sampleProject = new Projects({
			  projectCode: 'ABC_012345',
			  description: 'MEAN rocks!',
				due: '2014-10-30T04:00:00.000Z',
				customer: {
					_id: '12345'
				},
				organism: {
					_id: '54321'
				}
			});
			// Create a sample projects array that includes the new project
			var sampleProjects = [sampleProject];

			// Account for the Customers query
			$httpBackend.expectGET('customers').respond();

			// Account for the Organisms query
			$httpBackend.expectGET('organisms').respond();

			// Set GET response
			$httpBackend.expectGET('projects').respond(sampleProjects);

			// Run controller functionality
			scope.editing();
			scope.init();
			$httpBackend.flush();

			scope.project = sampleProject;
			scope.organism = {selected: {id: 1, _id: '54321'}};
			scope.customer = {selected: {id: 23, _id: '12345', code: 'ABC'}};

			expect(scope.projectCode()).toBe('ABC_012345');
		}));

		it('$scope.projectCode() should use wildcards when an organism or customer hasn\'t been selected yet', inject(function(Projects) {

			// Create a sample project object
			var sampleProject = new Projects({
			  projectCode: 'ABC_012345',
			  description: 'MEAN rocks!',
				due: '2014-10-30T04:00:00.000Z'
			});
			// Create a sample projects array that includes the new project
			var sampleProjects = [sampleProject];

			// Account for the Customers query
			$httpBackend.expectGET('customers').respond();

			// Account for the Organisms query
			$httpBackend.expectGET('organisms').respond();

			// Set GET response
			$httpBackend.expectGET('projects').respond(sampleProjects);

			// Run controller functionality
			scope.init();
			$httpBackend.flush();

			scope.customer = {selected: {id: 23, code: 'ABC'}};

			expect(scope.projectCode()).toBe('ABC_XX23XX');
		}));

		describe('Retrieving projects by status', function(){

			beforeEach(inject(function(Projects){
				var sampleProject1 = new Projects({
					projectCode: 'ABC_012345',
					description: 'MEAN rocks!',
					due: '2014-10-30T04:00:00.100Z',
					projectStatus: true
				});

				var sampleProject2 = new Projects({
					projectCode: 'ABC_012346',
					description: 'MEAN is mean!',
					due: '2014-10-30T04:00:00.020Z',
					projectStatus: false
				});

				var sampleProject3 = new Projects({
					projectCode: 'ABC_012347',
					description: 'NEAM is MEAN spelled backwards!',
					due: '2014-10-30T04:00:00.300Z',
					projectStatus: true
				});

				var sampleProject4 = new Projects({
					projectCode: 'ABC_012348',
					description: 'MEAN, you mean nice!',
					due: '2014-10-30T04:00:00.400Z',
					projectStatus: false
				});

				scope.openProjects = [sampleProject2, sampleProject4];
				scope.closedProjects = [sampleProject1, sampleProject3];
			}));

			it('should retrieve open projects', inject(function(){

				$httpBackend.expectGET('customers').respond();
				$httpBackend.expectGET('organisms').respond();
				$httpBackend.expectGET('http://localhost:3000/projectsByStatus/false').respond(scope.openProjects);
				scope.showProjectsByStatus(false, true, false);
				$httpBackend.flush();

				expect(scope.openProjectsActive).toBeTruthy();
				expect(scope.closedProjectsActive).toBeFalsy();
				expect(scope.projects).toEqualData(scope.openProjects);

			}));

			it('should retrieve closed projects', inject(function(){

				$httpBackend.expectGET('customers').respond();
				$httpBackend.expectGET('organisms').respond();
				$httpBackend.expectGET('http://localhost:3000/projectsByStatus/true').respond(scope.closedProjects);
				scope.showProjectsByStatus(true, false, true);
				$httpBackend.flush();

				expect(scope.openProjectsActive).toBeFalsy();
				expect(scope.closedProjectsActive).toBeTruthy();
				expect(scope.projects).toEqualData(scope.closedProjects);

			}));
		});

	});
}());


text:
var Chain = function () {
    this.stack = [];
    this.index = 0;
};

Chain.prototype.origin = function () {
    this.stack.forEach(function (chainItem) {
        chainItem.animate.origin(chainItem.actualEl());
    });
};

Chain.prototype.next = function () {
    if (!this.stack[this.index]) {
        //reset
        this.index = 0;
        return;
    }
    var self = this;
    var chainItem = this.stack[this.index];
    chainItem.animate.complete(function () {
        self.index++;
        self.next();
    });
    chainItem.animate.start(chainItem.actualEl(), this.index, this.stack.length);
};

Chain.prototype.add = function (chainItem) {
    this.stack.push(chainItem);
};

var ChainItem = function (el, animate, type) {
    this.el = el;
    this.animate = animate;
    this.type = type;
};

ChainItem.prototype.actualEl = function () {
    var img = this.el.find(".so-img");
    return this.type == "img" && img.size() ? img : this.el;
};

exports.Chain = Chain;
exports.ChainItem = ChainItem;


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">

First TODO App - Ajinkya

Tasks remaining {{remaining()}} out of {{items.length}}. [Archive]

<input type="checkbox" ng-model="item.done">{{item.text}} || {{item.done}}

            <form action="" name="taskform">
                <input type="text" ng-model="newItem.text" ng-maxlength="12" name="tasktext">
                Error! Message too long.
                <button type="submit" ng-click="add(newItem)" ng-disabled="!newItem.text">Add Item</button>
            </form>


text:
static juce_wchar getDefaultPasswordChar() noexcept
{
   #if JUCE_LINUX
    return 0x2022;
   #else
    return 0x25cf;
   #endif
}

//==============================================================================
AlertWindow::AlertWindow (const String& title,
                          const String& message,
                          AlertIconType iconType,
                          Component* comp)
   : TopLevelWindow (title, true),
     alertIconType (iconType),
     associatedComponent (comp),
     escapeKeyCancels (true)
{
    setAlwaysOnTop (juce_areThereAnyAlwaysOnTopWindows());

    if (message.isEmpty())
        text = " "; // to force an update if the message is empty

    setMessage (message);

    AlertWindow::lookAndFeelChanged();
    constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
}

AlertWindow::~AlertWindow()
{
    removeAllChildren();
}

void AlertWindow::userTriedToCloseWindow()
{
    if (escapeKeyCancels || buttons.size() > 0)
        exitModalState (0);
}

//==============================================================================
void AlertWindow::setMessage (const String& message)
{
    const String newMessage (message.substring (0, 2048));

    if (text != newMessage)
    {
        text = newMessage;
        updateLayout (true);
        repaint();
    }
}

//==============================================================================
void AlertWindow::buttonClicked (Button* button)
{
    if (Component* parent = button->getParentComponent())
        parent->exitModalState (button->getCommandID());
}

//==============================================================================
void AlertWindow::addButton (const String& name,
                             const int returnValue,
                             const KeyPress& shortcutKey1,
                             const KeyPress& shortcutKey2)
{
    TextButton* const b = new TextButton (name, String::empty);
    buttons.add (b);

    b->setWantsKeyboardFocus (true);
    b->setMouseClickGrabsKeyboardFocus (false);
    b->setCommandToTrigger (0, returnValue, false);
    b->addShortcut (shortcutKey1);
    b->addShortcut (shortcutKey2);
    b->addListener (this);
    b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());

    addAndMakeVisible (b, 0);

    updateLayout (false);
}

int AlertWindow::getNumButtons() const
{
    return buttons.size();
}

void AlertWindow::triggerButtonClick (const String& buttonName)
{
    for (int i = buttons.size(); --i >= 0;)
    {
        TextButton* const b = buttons.getUnchecked(i);

        if (buttonName == b->getName())
        {
            b->triggerClick();
            break;
        }
    }
}

void AlertWindow::setEscapeKeyCancels (bool shouldEscapeKeyCancel)
{
    escapeKeyCancels = shouldEscapeKeyCancel;
}

//==============================================================================
void AlertWindow::addTextEditor (const String& name,
                                 const String& initialContents,
                                 const String& onScreenLabel,
                                 const bool isPasswordBox)
{
    TextEditor* ed = new TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0);
    ed->setSelectAllWhenFocused (true);
    ed->setEscapeAndReturnKeysConsumed (false);
    textBoxes.add (ed);
    allComps.add (ed);

    ed->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
    ed->setFont (getLookAndFeel().getAlertWindowMessageFont());
    ed->setText (initialContents);
    ed->setCaretPosition (initialContents.length());
    addAndMakeVisible (ed);
    textboxNames.add (onScreenLabel);

    updateLayout (false);
}

TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
{
    for (int i = textBoxes.size(); --i >= 0;)
        if (textBoxes.getUnchecked(i)->getName() == nameOfTextEditor)
            return textBoxes.getUnchecked(i);

    return nullptr;
}

String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
{
    if (TextEditor* const t = getTextEditor (nameOfTextEditor))
        return t->getText();

    return String::empty;
}

//==============================================================================
void AlertWindow::addComboBox (const String& name,
                               const StringArray& items,
                               const String& onScreenLabel)
{
    ComboBox* const cb = new ComboBox (name);
    comboBoxes.add (cb);
    allComps.add (cb);

    cb->addItemList (items, 1);

    addAndMakeVisible (cb);
    cb->setSelectedItemIndex (0);

    comboBoxNames.add (onScreenLabel);
    updateLayout (false);
}

ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
{
    for (int i = comboBoxes.size(); --i >= 0;)
        if (comboBoxes.getUnchecked(i)->getName() == nameOfList)
            return comboBoxes.getUnchecked(i);

    return nullptr;
}

//==============================================================================
class AlertTextComp : public TextEditor
{
public:
    AlertTextComp (const String& message,
                   const Font& font)
    {
        setReadOnly (true);
        setMultiLine (true, true);
        setCaretVisible (false);
        setScrollbarsShown (true);
        lookAndFeelChanged();
        setWantsKeyboardFocus (false);

        setFont (font);
        setText (message, false);

        bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));

        setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
        setColour (TextEditor::outlineColourId, Colours::transparentBlack);
        setColour (TextEditor::shadowColourId, Colours::transparentBlack);
    }

    int getPreferredWidth() const noexcept   { return bestWidth; }

    void updateLayout (const int width)
    {
        AttributedString s;
        s.setJustification (Justification::topLeft);
        s.append (getText(), getFont());

        TextLayout text;
        text.createLayoutWithBalancedLineLengths (s, width - 8.0f);
        setSize (width, jmin (width, (int) (text.getHeight() + getFont().getHeight())));
    }

private:
    int bestWidth;

    JUCE_DECLARE_NON_COPYABLE (AlertTextComp)
};

void AlertWindow::addTextBlock (const String& textBlock)
{
    AlertTextComp* const c = new AlertTextComp (textBlock, getLookAndFeel().getAlertWindowMessageFont());
    textBlocks.add (c);
    allComps.add (c);

    addAndMakeVisible (c);

    updateLayout (false);
}

//==============================================================================
void AlertWindow::addProgressBarComponent (double& progressValue)
{
    ProgressBar* const pb = new ProgressBar (progressValue);
    progressBars.add (pb);
    allComps.add (pb);

    addAndMakeVisible (pb);

    updateLayout (false);
}

//==============================================================================
void AlertWindow::addCustomComponent (Component* const component)
{
    customComps.add (component);
    allComps.add (component);

    addAndMakeVisible (component);

    updateLayout (false);
}

int AlertWindow::getNumCustomComponents() const
{
    return customComps.size();
}

Component* AlertWindow::getCustomComponent (const int index) const
{
    return customComps [index];
}

Component* AlertWindow::removeCustomComponent (const int index)
{
    Component* const c = getCustomComponent (index);

    if (c != nullptr)
    {
        customComps.removeFirstMatchingValue (c);
        allComps.removeFirstMatchingValue (c);
        removeChildComponent (c);

        updateLayout (false);
    }

    return c;
}

//==============================================================================
void AlertWindow::paint (Graphics& g)
{
    getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);

    g.setColour (findColour (textColourId));
    g.setFont (getLookAndFeel().getAlertWindowFont());

    for (int i = textBoxes.size(); --i >= 0;)
    {
        const TextEditor* const te = textBoxes.getUnchecked(i);

        g.drawFittedText (textboxNames[i],
                          te->getX(), te->getY() - 14,
                          te->getWidth(), 14,
                          Justification::centredLeft, 1);
    }

    for (int i = comboBoxNames.size(); --i >= 0;)
    {
        const ComboBox* const cb = comboBoxes.getUnchecked(i);

        g.drawFittedText (comboBoxNames[i],
                          cb->getX(), cb->getY() - 14,
                          cb->getWidth(), 14,
                          Justification::centredLeft, 1);
    }

    for (int i = customComps.size(); --i >= 0;)
    {
        const Component* const c = customComps.getUnchecked(i);

        g.drawFittedText (c->getName(),
                          c->getX(), c->getY() - 14,
                          c->getWidth(), 14,
                          Justification::centredLeft, 1);
    }
}

void AlertWindow::updateLayout (const bool onlyIncreaseSize)
{
    const int titleH = 24;
    const int iconWidth = 80;

    LookAndFeel& lf = getLookAndFeel();

    const Font messageFont (lf.getAlertWindowMessageFont());

    const int wid = jmax (messageFont.getStringWidth (text),
                          messageFont.getStringWidth (getName()));

    const int sw = (int) std::sqrt (messageFont.getHeight() * wid);
    int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
    const int edgeGap = 10;
    const int labelHeight = 18;
    int iconSpace = 0;

    AttributedString attributedText;
    attributedText.append (getName(), lf.getAlertWindowTitleFont());

    if (text.isNotEmpty())
        attributedText.append ("\n\n" + text, messageFont);

    attributedText.setColour (findColour (textColourId));

    if (alertIconType == NoIcon)
    {
        attributedText.setJustification (Justification::centredTop);
        textLayout.createLayoutWithBalancedLineLengths (attributedText, (float) w);
    }
    else
    {
        attributedText.setJustification (Justification::topLeft);
        textLayout.createLayoutWithBalancedLineLengths (attributedText, (float) w);
        iconSpace = iconWidth;
    }

    w = jmax (350, (int) textLayout.getWidth() + iconSpace + edgeGap * 4);
    w = jmin (w, (int) (getParentWidth() * 0.7f));

    const int textLayoutH = (int) textLayout.getHeight();
    const int textBottom = 16 + titleH + textLayoutH;
    int h = textBottom;

    int buttonW = 40;
    for (int i = 0; i < buttons.size(); ++i)
        buttonW += 16 + buttons.getUnchecked (i)->getWidth();

    w = jmax (buttonW, w);

    h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;

    if (buttons.size() > 0)
        h += 20 + buttons.getUnchecked (0)->getHeight();

    for (int i = customComps.size(); --i >= 0;)
    {
        Component* c = customComps.getUnchecked (i);
        w = jmax (w, (c->getWidth() * 100) / 80);
        h += 10 + c->getHeight();

        if (c->getName().isNotEmpty())
            h += labelHeight;
    }

    for (int i = textBlocks.size(); --i >= 0;)
    {
        const AlertTextComp* const ac = static_cast<const AlertTextComp*> (textBlocks.getUnchecked(i));
        w = jmax (w, ac->getPreferredWidth());
    }

    w = jmin (w, (int) (getParentWidth() * 0.7f));

    for (int i = textBlocks.size(); --i >= 0;)
    {
        AlertTextComp* const ac = static_cast<AlertTextComp*> (textBlocks.getUnchecked(i));
        ac->updateLayout ((int) (w * 0.8f));
        h += ac->getHeight() + 10;
    }

    h = jmin (getParentHeight() - 50, h);

    if (onlyIncreaseSize)
    {
        w = jmax (w, getWidth());
        h = jmax (h, getHeight());
    }

    if (! isVisible())
    {
        centreAroundComponent (associatedComponent, w, h);
    }
    else
    {
        const int cx = getX() + getWidth() / 2;
        const int cy = getY() + getHeight() / 2;

        setBounds (cx - w / 2,
                   cy - h / 2,
                   w, h);
    }

    textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);

    const int spacer = 16;
    int totalWidth = -spacer;

    for (int i = buttons.size(); --i >= 0;)
        totalWidth += buttons.getUnchecked(i)->getWidth() + spacer;

    int x = (w - totalWidth) / 2;
    int y = (int) (getHeight() * 0.95f);

    for (int i = 0; i < buttons.size(); ++i)
    {
        TextButton* const c = buttons.getUnchecked(i);
        int ny = proportionOfHeight (0.95f) - c->getHeight();
        c->setTopLeftPosition (x, ny);
        if (ny < y)
            y = ny;

        x += c->getWidth() + spacer;

        c->toFront (false);
    }

    y = textBottom;

    for (int i = 0; i < allComps.size(); ++i)
    {
        Component* const c = allComps.getUnchecked(i);
        h = 22;

        const int comboIndex = comboBoxes.indexOf (dynamic_cast<ComboBox*> (c));
        if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
            y += labelHeight;

        const int tbIndex = textBoxes.indexOf (dynamic_cast<TextEditor*> (c));
        if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
            y += labelHeight;

        if (customComps.contains (c))
        {
            if (c->getName().isNotEmpty())
                y += labelHeight;

            c->setTopLeftPosition (proportionOfWidth (0.1f), y);
            h = c->getHeight();
        }
        else if (textBlocks.contains (c))
        {
            c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
            h = c->getHeight();
        }
        else
        {
            c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
        }

        y += h + 10;
    }

    setWantsKeyboardFocus (getNumChildComponents() == 0);
}

bool AlertWindow::containsAnyExtraComponents() const
{
    return allComps.size() > 0;
}

//==============================================================================
void AlertWindow::mouseDown (const MouseEvent& e)
{
    dragger.startDraggingComponent (this, e);
}

void AlertWindow::mouseDrag (const MouseEvent& e)
{
    dragger.dragComponent (this, e, &constrainer);
}

bool AlertWindow::keyPressed (const KeyPress& key)
{
    for (int i = buttons.size(); --i >= 0;)
    {
        TextButton* const b = buttons.getUnchecked(i);

        if (b->isRegisteredForShortcut (key))
        {
            b->triggerClick();
            return true;
        }
    }

    if (key.isKeyCode (KeyPress::escapeKey) && escapeKeyCancels && buttons.size() == 0)
    {
        exitModalState (0);
        return true;
    }

    if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
    {
        buttons.getUnchecked(0)->triggerClick();
        return true;
    }

    return false;
}

void AlertWindow::lookAndFeelChanged()
{
    const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();

    setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
    setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
    updateLayout (false);
}

int AlertWindow::getDesktopWindowStyleFlags() const
{
    return getLookAndFeel().getAlertBoxWindowFlags();
}

//==============================================================================
class AlertWindowInfo
{
public:
    AlertWindowInfo (const String& t, const String& m, Component* component,
                     AlertWindow::AlertIconType icon, int numButts,
                     ModalComponentManager::Callback* cb, bool runModally)
        : title (t), message (m), iconType (icon), numButtons (numButts),
          returnValue (0), associatedComponent (component),
          callback (cb), modal (runModally)
    {
    }

    String title, message, button1, button2, button3;

    int invoke() const
    {
        MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
        return returnValue;
    }

private:
    AlertWindow::AlertIconType iconType;
    int numButtons, returnValue;
    WeakReference<Component> associatedComponent;
    ModalComponentManager::Callback* callback;
    bool modal;

    void show()
    {
        LookAndFeel& lf = associatedComponent != nullptr ? associatedComponent->getLookAndFeel()
                                                         : LookAndFeel::getDefaultLookAndFeel();

        ScopedPointer<Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
                                                                 iconType, numButtons, associatedComponent));

        jassert (alertBox != nullptr); // you have to return one of these!

       #if JUCE_MODAL_LOOPS_PERMITTED
        if (modal)
        {
            returnValue = alertBox->runModalLoop();
        }
        else
       #endif
        {
            (void) modal; // (to avoid an unused variable warning)

            alertBox->enterModalState (true, callback, true);
            alertBox.release();
        }
    }

    static void* showCallback (void* userData)
    {
        static_cast<AlertWindowInfo*> (userData)->show();
        return nullptr;
    }
};

#if JUCE_MODAL_LOOPS_PERMITTED
void AlertWindow::showMessageBox (AlertIconType iconType,
                                  const String& title,
                                  const String& message,
                                  const String& buttonText,
                                  Component* associatedComponent)
{
    if (LookAndFeel::getDefaultLookAndFeel().isUsingNativeAlertWindows())
    {
        NativeMessageBox::showMessageBox (iconType, title, message, associatedComponent);
    }
    else
    {
        AlertWindowInfo info (title, message, associatedComponent, iconType, 1, nullptr, true);
        info.button1 = buttonText.isEmpty() ? TRANS("OK") : buttonText;

        info.invoke();
    }
}
#endif

void AlertWindow::showMessageBoxAsync (AlertIconType iconType,
                                       const String& title,
                                       const String& message,
                                       const String& buttonText,
                                       Component* associatedComponent,
                                       ModalComponentManager::Callback* callback)
{
    if (LookAndFeel::getDefaultLookAndFeel().isUsingNativeAlertWindows())
    {
        NativeMessageBox::showMessageBoxAsync (iconType, title, message, associatedComponent, callback);
    }
    else
    {
        AlertWindowInfo info (title, message, associatedComponent, iconType, 1, callback, false);
        info.button1 = buttonText.isEmpty() ? TRANS("OK") : buttonText;

        info.invoke();
    }
}

bool AlertWindow::showOkCancelBox (AlertIconType iconType,
                                   const String& title,
                                   const String& message,
                                   const String& button1Text,
                                   const String& button2Text,
                                   Component* associatedComponent,
                                   ModalComponentManager::Callback* callback)
{
    if (LookAndFeel::getDefaultLookAndFeel().isUsingNativeAlertWindows())
        return NativeMessageBox::showOkCancelBox (iconType, title, message, associatedComponent, callback);

    AlertWindowInfo info (title, message, associatedComponent, iconType, 2, callback, callback == nullptr);
    info.button1 = button1Text.isEmpty() ? TRANS("OK")     : button1Text;
    info.button2 = button2Text.isEmpty() ? TRANS("Cancel") : button2Text;

    return info.invoke() != 0;
}

int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
                                     const String& title,
                                     const String& message,
                                     const String& button1Text,
                                     const String& button2Text,
                                     const String& button3Text,
                                     Component* associatedComponent,
                                     ModalComponentManager::Callback* callback)
{
    if (LookAndFeel::getDefaultLookAndFeel().isUsingNativeAlertWindows())
        return NativeMessageBox::showYesNoCancelBox (iconType, title, message, associatedComponent, callback);

    AlertWindowInfo info (title, message, associatedComponent, iconType, 3, callback, callback == nullptr);
    info.button1 = button1Text.isEmpty() ? TRANS("Yes")     : button1Text;
    info.button2 = button2Text.isEmpty() ? TRANS("No")      : button2Text;
    info.button3 = button3Text.isEmpty() ? TRANS("Cancel")  : button3Text;

    return info.invoke();
}

#if JUCE_MODAL_LOOPS_PERMITTED
bool AlertWindow::showNativeDialogBox (const String& title,
                                       const String& bodyText,
                                       bool isOkCancel)
{
    if (isOkCancel)
        return NativeMessageBox::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);

    NativeMessageBox::showMessageBox (AlertWindow::NoIcon, title, bodyText);
    return true;
}
#endif


text:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

// http ://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once

#include "Magic_TargetTypes.generated.h"

UENUM(BlueprintType)
enum class EMagic_TargetTypes : uint8
{
	TT_Player UMETA(DisplayName = "Player"),
	TT_Enemy UMETA(DisplayName = "Enemy"),
};


text:
from sut import MockAgent
import mozdevice
import unittest
import hashlib
import tempfile
import os

class PullTest(unittest.TestCase):

    def test_pull_success(self):
        for count in [ 1, 4, 1024, 2048 ]:
            cheeseburgers = ""
            for i in range(count):
                cheeseburgers += "cheeseburgers"

            # pull file is kind of gross, make sure we can still execute commands after it's done
            remoteName = "/mnt/sdcard/cheeseburgers"
            mozdevice.DroidSUT.debug = 4
            a = MockAgent(self, commands = [("pull %s" % remoteName,
                                             "%s,%s\n%s" % (remoteName,
                                                            len(cheeseburgers),
                                                            cheeseburgers)),
                                            ("isdir /mnt/sdcard", "TRUE")])

            d = mozdevice.DroidSUT("127.0.0.1", port=a.port)
            pulledData = d.pullFile("/mnt/sdcard/cheeseburgers")
            self.assertEqual(pulledData, cheeseburgers)
            d.dirExists('/mnt/sdcard')

    def test_pull_failure(self):

        # this test simulates only receiving a few bytes of what we expect
        # to be larger file
        remoteName = "/mnt/sdcard/cheeseburgers"
        a = MockAgent(self, commands = [("pull %s" % remoteName,
                                         "%s,15\n%s" % (remoteName,
                                                        "cheeseburgh"))])
        d = mozdevice.DroidSUT("127.0.0.1", port=a.port)
        exceptionThrown = False
        try:
            d.pullFile("/mnt/sdcard/cheeseburgers")
        except mozdevice.DMError:
            exceptionThrown = True
        self.assertTrue(exceptionThrown)

if __name__ == '__main__':
    unittest.main()


text:
<?php

/**
 * Tagged products controller
 *
 * @category   Mage
 * @package    Mage_Tag
 * @author      Magento Core Team <core@magentocommerce.com>
 */

class Mage_Tag_ProductController extends Mage_Core_Controller_Front_Action
{
    public function listAction()
    {
        $tagId = $this->getRequest()->getParam('tagId');
        $tag = Mage::getModel('tag/tag')->load($tagId);

        if(!$tag->getId() || !$tag->isAvailableInStore()) {
            $this->_forward('404');
            return;
        }
        Mage::register('current_tag', $tag);

        $this->loadLayout();
        $this->_initLayoutMessages('checkout/session');
        $this->_initLayoutMessages('tag/session');
        $this->renderLayout();
    }
}


text:
using System;
using System.IO;
using System.Net;
using SignalR.Client._20.Infrastructure;

namespace SignalR.Client._20.Http
{
    public class HttpWebResponseWrapper : IResponse
    {
        private readonly HttpWebResponse m_response;

        public HttpWebResponseWrapper(HttpWebResponse response)
        {
            m_response = response;
        }

        public string ReadAsString()
        {
            return HttpHelper.ReadAsString(m_response);
        }

        public Stream GetResponseStream()
        {
            return m_response.GetResponseStream();
        }

        public void Close()
        {
            ((IDisposable)m_response).Dispose();
        }

    	public bool IsFaulted { get; set; }

    	public Exception Exception { get; set; }
    }
}


text:
<?php

// No direct access
defined('_HZEXEC_') or die();

$this->css()
     ->css('icons', 'com_projects')
	 ->css('emocons', 'com_projects');

$this->js();
$li = '';

if (count($this->activities) > 0 )
{
	$projects = array();
	$i = 1;

	?>

		<?php
		// Loop through activities
		foreach ($this->activities as $activity)
		{
			$a = $activity['activity'];
			if (!isset($projects[$a->projectid]))
			{
				$projects[$a->projectid] = \Components\Projects\Models\Project::getInstance($a->projectid);
			}

			// Show activity
			$this->view('_activity')
		     ->set('model', $projects[$a->projectid])
			 ->set('activity', $activity)
			 ->set('uid', $this->uid)
			 ->set('edit', false)
			 ->set('showProject', true)
		     ->display();

			?>
		<?php
			$li = 'li_' . $a->id;
			$i++;
		} // end foreach
		?>

<?php } else { ?>

<?php echo Lang::txt('PLG_PROJECTS_BLOG_NO_ACTIVITIES'); ?>

<?php } ?>

<?php
if ($this->total > $this->filters['limit']) {
	$limit = $this->filters['limit'] + $this->limit; ?>

<a href="<?php echo Route::url('index.php?option=com_members&id=' . $this->uid . '&active=projects') . '?action=updates&limit=' . $limit . '&prev=' . $this->filters['limit'] . '#' . $li;  ?>"><?php echo Lang::txt('PLG_PROJECTS_BLOG_VIEW_OLDER_ENTRIES'); ?>

<?php } else if ($this->filters['limit'] != $this->limit) { ?>

<?php echo Lang::txt('PLG_PROJECTS_BLOG_VIEW_OLDER_ENTRIES_NO_MORE'); ?>

<?php } ?>


text:
SET(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
SET(CMAKE_DEPENDS_CHECK_CXX
  "/home/iaa/gnuradio/gr-greene/build/swig/_greene_swig_swig_tag.cpp" "/home/iaa/gnuradio/gr-greene/build/swig/CMakeFiles/_greene_swig_swig_tag.dir/_greene_swig_swig_tag.cpp.o"
  )
SET(CMAKE_CXX_COMPILER_ID "GNU")

# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
  )


text:
class MultiplesController < ApplicationController
  image_deletable
  # GET /multiples
  # GET /multiples.xml
  def index
    @multiples = Multiple.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @multiples }
    end
  end

  # GET /multiples/1
  # GET /multiples/1.xml
  def show
    @multiple = Multiple.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @multiple }
    end
  end

  # GET /multiples/new
  # GET /multiples/new.xml
  def new
    @multiple = Multiple.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @multiple }
    end
  end

  # GET /multiples/1/edit
  def edit
    @multiple = Multiple.find(params[:id])
  end

  # POST /multiples
  # POST /multiples.xml
  def create
    @multiple = Multiple.new(params[:multiple])

    respond_to do |format|
      if @multiple.save
        format.html { redirect_to(multiple_path(@multiple), :notice => 'Multiple was successfully created.') }
        format.xml  { render :xml => @multiple, :status => :created, :location => @multiple }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @multiple.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /multiples/1
  # PUT /multiples/1.xml
  def update
    @multiple = Multiple.find(params[:id])

    respond_to do |format|
      if @multiple.update_attributes(params[:multiple])
        format.html { redirect_to(multiple_path(@multiple), :notice => 'Multiple was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @multiple.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /multiples/1
  # DELETE /multiples/1.xml
  def destroy
    @multiple = Multiple.find(params[:id])
    @multiple.destroy

    respond_to do |format|
      format.html { redirect_to(multiples_url) }
      format.xml  { head :ok }
    end
  end

end


text:
'use strict';

const context = require('../helpers/context');

describe('ctx.set(name, val)', () => {
  it('should set a field value', () => {
    const ctx = context();
    ctx.set('x-foo', 'bar');
    ctx.response.header['x-foo'].should.equal('bar');
  });

  it('should coerce to a string', () => {
    const ctx = context();
    ctx.set('x-foo', 5);
    ctx.response.header['x-foo'].should.equal('5');
  });

  it('should set a field value of array', () => {
    const ctx = context();
    ctx.set('x-foo', ['foo', 'bar']);
    ctx.response.header['x-foo'].should.eql([ 'foo', 'bar' ]);
  });
});

describe('ctx.set(object)', () => {
  it('should set multiple fields', () => {
    const ctx = context();

    ctx.set({
      foo: '1',
      bar: '2'
    });

    ctx.response.header.foo.should.equal('1');
    ctx.response.header.bar.should.equal('2');
  });
});


text:
"use strict";
var mongoose = require('mongoose');
var cache = null;

var schemaOptions = {
    toObject: {
        virtuals: true
    },
    toJSON: {
        virtuals: true
    }
};

var collegeSchema = new mongoose.Schema({
    _id: {type: String, required: true, unique: true}, //unique college id
    name: {type: String, required: true, index: true},
    city: {type: String},
    state: {type: String}, //2 letter
    zip: String,
    loc: {
        type: {type: String},
        coordinates: [Number] //offic. convention is lon, lat
    },
    _distance: Number //internal param for use in geonear
}, schemaOptions);
collegeSchema.index({loc: '2dsphere'});

//display name of college
collegeSchema.virtual('display').get(function () {
    return this.name + " - " + this.state;
});

/**
 * add a single college entry
 * @param unitid
 * @param name
 * @param city
 * @param state
 * @param zip
 * @param lon
 * @param lat
 * @param callback
 */
collegeSchema.statics.add = function (unitid, name, city, state, zip, lon, lat, callback) {
    var college = new this({
        _id: unitid,
        name: name,
        city: city,
        state: state,
        zip: zip,
        loc: {
            type: "Point",
            coordinates: [parseFloat(lon), parseFloat(lat)]
        }
    });

    this.findOne({_id: unitid}, function (err, res) {
        if (res === null) {
            //entry does not exist
            college.save(function (err) {
                callback(err, college);
            });
        }
    });
};

/**
 * get all College entries, limiting by fields
 * @param callback
 * @todo limit field selection
 */
collegeSchema.statics.getAll = function (callback) {
        if (cache == null) {
            this.find({}, function (err, res) {
                if (err) {
                    callback(err);
                }
                res = res.map(function (x) {
                    return {
                        id: x._id,
                        name: x.display
                    }
                });
                cache = res;
                callback(null, res);
            });
        }
    else callback(null, cache);
};

collegeSchema.statics.exists = function (unitid, callback) {
    this.findOne({_id: unitid}, function (err, res) {
        if (err) callback(err);
        if (res === null) {
            //entry does not exist
            callback(null, false);
        }
        return callback(null, true);
    })
};

module.exports = mongoose.model("College", collegeSchema);


text:
package me.chris.HotLogger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.logging.Level;

import org.bukkit.block.Block;
import org.bukkit.entity.Player;

public class QueryThread_Block implements Runnable
{
	ArrayList<String> lines = new ArrayList<String>();
	Player p;
	Block b;

	public QueryThread_Block(Player p, Block b)
	{
		this.p = p;
		this.b = b;
	}

	@Override
	public void run()
	{
		Connection conn;
		try
		{
			conn = Vars.getConnection();
		}
		catch(MyException e)
		{
			Vars.log.log(Level.SEVERE, "[HotLogger] Error establishing connection with SQL server.");
			Vars.log.log(Level.SEVERE, "[HotLogger] " + e.getString());
			return;
		}

		try
		{
			PreparedStatement st = conn.prepareStatement("SELECT action, timestamp, player, data FROM blockPlace WHERE x=? and y=? and z = ? "
					+ "UNION "
					+ "SELECT action, timestamp, player, data FROM blockBreak WHERE x=? and y=? and z = ? "
					+ "UNION "
					+ "SELECT action, timestamp, player, data FROM chestAccess WHERE x=? and y=? and z = ? "
					+ "ORDER BY timestamp");

			st.setDouble(1, b.getX());
			st.setDouble(2, b.getY());
			st.setDouble(3, b.getZ());

			st.setDouble(4, b.getX());
			st.setDouble(5, b.getY());
			st.setDouble(6, b.getZ());

			st.setDouble(7, b.getX());
			st.setDouble(8, b.getY());
			st.setDouble(9, b.getZ());

			ResultSet rs = st.executeQuery();

			while (rs.next()) {
				String action = rs.getString("action");
				Timestamp t = rs.getTimestamp("timestamp");
				String playerUUID = rs.getString("player");
				String data = rs.getString("data");
				String playerName = "Unknown";

				PreparedStatement name = conn.prepareStatement("SELECT playerName FROM playerList WHERE playerUUID=?");
				name.setString(1, playerUUID);

				ResultSet nameQuery = name.executeQuery();
				if(nameQuery.next())
					playerName = nameQuery.getString("playerName");

				if(action.equalsIgnoreCase("blockPlace"))
				{
					lines.add("§7" + t + " §8§l: §c" + playerName + " placed " + data.toLowerCase() + " here.");
				}
				else if(action.equalsIgnoreCase("blockBreak"))
				{
					lines.add("§7" + t + " §8§l: §c" + playerName + " broke " + data.toLowerCase() + " here.");
				}
				else if(action.equalsIgnoreCase("chestAccess"))
				{
					lines.add("§7" + t + " §8§l: §c" + playerName + " accessed a chest here.");
				}
			}
		}
		catch (SQLException e)
		{
			Vars.log.log(Level.SEVERE, "" + e);
			p.sendMessage("§a[HotLogger] §cThere was an internal error");
		}

		if(lines.isEmpty())
		{
			p.sendMessage("§a[HotLogger] §cNo records found for this block");
			return;
		}

		if(lines.size() > 10)
		{
			p.sendMessage("§5======§c [ HotLogger ] §5==================================");
			for(int index = 0; index < 10; index++)
			{
				p.sendMessage(lines.get(index));
			}
			p.sendMessage(" §e" + lines.size() + " records found. Paginate with §c/hl page [num]");
			p.sendMessage("§5==============================================§7 Page 1");
		}
		else
		{
			p.sendMessage("§5====§c [ HotLogger ] §5===============================");
			for(String l : lines)
			{
				p.sendMessage(l);
			}
			p.sendMessage("§5=====================================================");
		}

		Vars.lines.put(p, lines);
	}

}


text:
var JQ = jQuery.noConflict();
JQ('document').ready(function(){
/**
 * Enable DateTime Picker
 */
JQ('.datetime').datetimepicker({
	dateFormat:"yy-mm-dd",
	formatTime:"HH:mm:ss",
	showSecond: true
});

/**
 * Enable DateTime Picker
 */
JQ('.timestamp').datetimepicker({
	dateFormat:"yy-mm-dd",
	formatTime:"HH:mm:ss",
	showSecond: true
});

});