text:
package org.bdgenomics.quinine.metrics.targeted

import org.bdgenomics.adam.util.ADAMFunSuite
import org.bdgenomics.formats.avro.{ AlignmentRecord, Contig }
import scala.math.abs

class ReadStatsSuite extends ADAMFunSuite {

  val qualThreshold = 20

  val contig1 = Contig.newBuilder()
    .setContigName("ctg1")
    .build()

  def qualString(qual: Int, length: Int): String = {
    // toChar.toString reads funny, but .toString on Int returns the int as a string literal
    // e.g.,
    // 'a'.toString = "a"
    // 'a'.toInt = 97
    // 'a'.toInt.toString = "97"
    // 'a'.toInt.toChar.toString = "a"
    (33 + qual).toChar.toString * length
  }

  // my, the perfect read is free of defects!
  val perfectRead = AlignmentRecord.newBuilder()
    .setSequence("A" * 10)
    .setQual(qualString(65, 10))
    .setDuplicateRead(false)
    .setFailedVendorQualityChecks(false)
    .setReadMapped(true)
    .setStart(1L)
    .setEnd(11L)
    .setContig(contig1)
    .setReadPaired(true)
    .setMateMapped(true)
    .setReadInFragment(0)
    .setMateContig(contig1)
    .setMateAlignmentStart(100L)
    .setMateAlignmentEnd(110L)
    .setMapq(65)
    .build()

  // similar to the perfect read, but has no qual
  val noQualRead = AlignmentRecord.newBuilder(perfectRead)
    .setQual(null)
    .build()

  // similar to the perfect read, but failed the vendor quality checks
  val failedVendorChecksRead = AlignmentRecord.newBuilder(perfectRead)
    .setFailedVendorQualityChecks(true)
    .build()

  // similar to the perfect read, but marked as a duplicate
  val duplicateRead = AlignmentRecord.newBuilder(perfectRead)
    .setDuplicateRead(true)
    .build()

  // similar to the perfect read, but all bases are low quality
  val lowBaseQualityRead = AlignmentRecord.newBuilder(perfectRead)
    .setQual(qualString(19, 10))
    .build()

  // similar to the perfect read, but the start and end bases are low quality
  val lowBaseQualityEndsRead = AlignmentRecord.newBuilder(perfectRead)
    .setQual(qualString(19, 1) + qualString(20, 8) + qualString(19, 1))
    .build()

  // similar to the perfect read, but with zero mapq
  val mapQZeroRead = AlignmentRecord.newBuilder(perfectRead)
    .setMapq(0)
    .build()

  // similar to the perfect read, but with mapq = 19
  val poorlyMappedRead = AlignmentRecord.newBuilder(perfectRead)
    .setMapq(19)
    .build()

  // similar to the perfect read, but overlaps its mate
  val overlappingFirstOfPairRead = AlignmentRecord.newBuilder(perfectRead)
    .setMateAlignmentStart(5L)
    .setMateAlignmentEnd(15L)
    .build()

  // similar to the overlapping first-of-pair read, but the second read in the template
  val overlappingSecondOfPairRead = AlignmentRecord.newBuilder(overlappingFirstOfPairRead)
    .setReadInFragment(1)
    .build()

  // similar to the perfect read, but without a pair
  val unpairedRead = AlignmentRecord.newBuilder(perfectRead)
    .setReadInFragment(null)
    .setReadPaired(false)
    .setMateContig(null)
    .setMateAlignmentStart(null)
    .setMateAlignmentEnd(null)
    .build()

  def stat(read: AlignmentRecord) = ReadStats(read, qualThreshold, qualThreshold)

  def genericAsserts(rs: ReadStats,
                     dupe: Boolean = false,
                     mapQZero: Boolean = false,
                     poorlyMapped: Boolean = false,
                     lowQualBases: Long = 0L,
                     overlapping: Boolean = false,
                     failedChecks: Boolean = false) {
    assert(rs.reads === 1L)
    assert(rs.bases === 10L)

    if (!failedChecks) {
      assert(rs.readsPassingVendorQualityFilter === 1L)
    } else {
      assert(rs.readsPassingVendorQualityFilter === 0L)
    }

    if (!dupe) {
      assert(rs.uniqueReads === 1L)
      assert(rs.duplicateBases === 0L)
    } else {
      assert(rs.uniqueReads === 0L)
      assert(rs.duplicateBases === 10L)
    }

    // dupe reads are not counted
    if (!mapQZero && !dupe) {
      assert(rs.nonZeroMapQReads === 1L)
      assert(rs.nonZeroMapQBases === 10L)
    } else {
      assert(rs.nonZeroMapQReads === 0L)
      assert(rs.nonZeroMapQBases === 0L)
    }

    if (!overlapping) {
      assert(rs.overlapBases === 0L)
    }

    if (!poorlyMapped && !mapQZero) {
      assert(rs.lowMapQBases === 0L)
    } else {
      assert(rs.lowMapQBases === 10L)
    }

    assert(rs.lowQualityBases === lowQualBases)
  }

  test("perfect read") {
    val rs = stat(perfectRead)

    genericAsserts(rs)
  }

  test("noQualRead should be equivalent to the perfect read, and should not NPE") {
    val rs = stat(noQualRead)

    genericAsserts(rs)
  }

  test("read failed vendor qc") {
    val rs = stat(failedVendorChecksRead)

    genericAsserts(rs, failedChecks = true)
  }

  test("read is a dupe") {
    val rs = stat(duplicateRead)

    genericAsserts(rs, dupe = true)
  }

  test("all of the bases in a read are low quality") {
    val rs = stat(lowBaseQualityRead)

    genericAsserts(rs, lowQualBases = 10L)
  }

  test("the start/end of the read have low quality scores") {
    val rs = stat(lowBaseQualityEndsRead)

    genericAsserts(rs, lowQualBases = 2L)
  }

  test("read's mapping quality is zero") {
    val rs = stat(mapQZeroRead)

    genericAsserts(rs, mapQZero = true)
  }

  test("read is mapped with low, but non-zero mapping quality") {
    val rs = stat(poorlyMappedRead)

    genericAsserts(rs, poorlyMapped = true)
  }

  test("first-of-pair read overlaps mate") {
    val rs = stat(overlappingFirstOfPairRead)

    genericAsserts(rs)
  }

  test("second-of-pair read overlaps mate") {
    val rs = stat(overlappingSecondOfPairRead)

    genericAsserts(rs, overlapping = true)
  }

  test("unpaired, but otherwise perfect read") {
    val rs = stat(unpairedRead)

    genericAsserts(rs)
  }

  test("merge two read stats instances") {
    val rs1 = ReadStats(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L)
    val rs2 = ReadStats(11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L)

    val mergedRs = rs1 ++ rs2

    assert(mergedRs.reads === 12L)
    assert(mergedRs.bases === 14L)
    assert(mergedRs.readsPassingVendorQualityFilter === 16L)
    assert(mergedRs.uniqueReads === 18L)
    assert(mergedRs.nonZeroMapQReads === 20L)
    assert(mergedRs.nonZeroMapQBases === 22L)
    assert(mergedRs.lowQualityBases === 24L)
    assert(mergedRs.duplicateBases === 26L)
    assert(mergedRs.lowMapQBases === 28L)
    assert(mergedRs.overlapBases === 30L)
  }

  sparkTest("run an aggregate across all reads") {
    val reads = Seq(perfectRead,
      failedVendorChecksRead,
      duplicateRead,
      lowBaseQualityRead,
      lowBaseQualityEndsRead,
      mapQZeroRead,
      poorlyMappedRead,
      overlappingFirstOfPairRead,
      overlappingSecondOfPairRead,
      unpairedRead)

    val rs = ReadStats(sc.parallelize(reads), qualThreshold, qualThreshold)

    assert(rs.reads === 10L)
    assert(rs.bases === 100L)
    assert(rs.readsPassingVendorQualityFilter === 9L)
    assert(rs.uniqueReads === 9L)
    assert(rs.nonZeroMapQReads === 8L)
    assert(rs.nonZeroMapQBases === 80L)
    assert(rs.lowQualityBases === 12L)
    assert(rs.duplicateBases === 10L)
    assert(rs.lowMapQBases === 20L)
    assert(rs.overlapBases === 10L)
    assert(fpCompare(rs.percentPassingChecks, 90.0))
    assert(fpCompare(rs.percentUniqueHighQualityReads, 80.0))
    assert(fpCompare(rs.percentLowQualityBases, 12.0))
    assert(fpCompare(rs.percentDuplicateBases, 10.0))
    assert(fpCompare(rs.percentLowMapQBases, 20.0))
    assert(fpCompare(rs.percentOverlapBases, 10.0))
  }

  def fpCompare(a: Double, b: Double, absTol: Double = 1e-3): Boolean = {
    abs(a - b) <= absTol
  }
}


text:
`MicroFrameworkBundle` can be installed in new applications as well as existing
ones.

We're going to review first the Empty Edition, then the Standard Edition and
we'll see what we need to consider for existing applications.

## Empty Edition

[Symfony](http://symfony.com) applications can be created using distributions,
for example the [Empty Edition](http://github.com/gnugat/symfony-empty-edition):

```
composer create-project gnugat/symfony-empty-edition
cd symfony-empty-edition
```

Then we need to replace `FrameworkBundle` by `MicroFrameworkBundle`, first in the
composer dependencies:

```
composer require 'gnugat/micro-framework-bundle'
composer remove --update-with-dependencies 'symfony/framework-bundle'
```

Then in the `app/AppKernel.php` file by replacing `Symfony\Bundle\FrameworkBundle\FrameworkBundle`
with `Gnugat\MicroFrameworkBundle\GnugatMicroFrameworkBundle`.

Next, the `framework` configuration key needs to be removed from `app/config/config.yml`.

Finally, in the `bin/console` file
replace `Symfony\Bundle\FrameworkBundle\Console\Application`
with `Gnugat\MicroFrameworkBundle\Service\KernelApplication as Application`.

## Standard Edition

There's an official distribution: [Standard Edition](https://github.com/symfony/symfony-standard).
It provides pre-installed libraries, but it can be installed in the same manner:

```
composer create-project symfony/framework-standard-edition
cd framework-standard-edition
composer require 'gnugat/micro-framework-bundle'
```

Then we need to clean `app/AppKernel.php` file by removing the following bundles:

* `Symfony\Bundle\FrameworkBundle\FrameworkBundle`
* `Doctrine\Bundle\DoctrineBundle\DoctrineBundle` (depends on FrameworkBundle specific console Application)
* `Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle` (depends on annotations)
* `Symfony\Bundle\TwigBundle\TwigBundle` (depends on assets)
* `Symfony\Bundle\WebProfilerBundle\WebProfilerBundle` (depends on data collectors)

Don't forget to add `Gnugat\MicroFrameworkBundle\GnugatMicroFrameworkBundle`.

Next remove configuration for the following keys in `app/config/config*.yml`:

* `framework`
* `doctrine` (as well as `database_*` parameters)
* `web_profiler`
* `twig`

Extra steps are required for routing:

1. create a `app/config/routings` directory
2. move `app/config/routing.yml` to `app/config/routings/app.yml`
3. switch from annotation to YAML routing configuration in `app/config/routings/app.yml`:
   ```
   homepage:
    path: /
    defaults:
        _controller: app.default_controller:indexAction
    methods:
        - GET
   ```
4. configure `AppBundle\Controller\DefaultController` as a service in `app/config/services.yml`:
    ```
    services:
        app.default_controller:
            class: AppBundle\Controller\DefaultController
    ```
5. remove `FrameworkBundle` classes from `src/AppBundle/Controller/DefaultController.php`:
    ```php
    <?php

    namespace AppBundle\Controller;

    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;

    class DefaultController
    {
        public function indexAction(Request $request)
        {
            return new Response('Hello world');
        }
    }
    ```
6. remove `app/config/routing_dev.yml`

Finally, in the `bin/console` file
replace `Symfony\Bundle\FrameworkBundle\Console\Application`
with `Gnugat\MicroFrameworkBundle\Console\KernelApplication as Application`.

> **Note**: Since `symfony/symfony` is specified as a requirement in `composer.json`,
> `FrameworkBundle` and the removed bundles are still present in the vendors.
> To get rid of them, specificy instead the actual list of component and bundles.

## Existing Applications

Replacing `FrameworkBundle` with `MicroFrameworkBundle` might be tricky. Here's
a small guide on how to do so.

The first step is to make sure everything is saved, in case we might need to rollback.
With git we can commit everything or statsh them.

Then we need to install the bundle:

```
composer require 'gnugat/micro-framework-bundle'
```

And register it in `app/AppKernel.php` by replacing `FrameworkBundle`.

The next steps are iterations of "try and debug":

1. remove the cache `rm -rf var/cache`
2. try to run the console: `bin/console`
3. try to browse pages
4. run your tests

If any step fails, then:

* check if there's any configuration to remove
* check if it's a bundle issue and if so if we can remove it

redpajama_set_name: RedPajamaGithub


text:
class ActivePeriod < ActiveRecord::Base
  belongs_to :activatable
end


text:
 //
// nvGLWidgets.h - User Interface library
//
//
// Author: Ignacio Castano, Samuel Gateau, Evan Hart
// Email: sdkfeedback@nvidia.com
//
// Copyright (c) NVIDIA Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#ifndef NV_GL_WIDGETS_H
#define NV_GL_WIDGETS_H

#include "nvWidgets.h"

namespace nv {

    //*************************************************************************
    // GLUIPainter
    class GLUIPainter : public UIPainter
    {
    public:

        NVSDKENTRY GLUIPainter();

        NVSDKENTRY virtual void begin( const Rect& window );
        NVSDKENTRY virtual void end();

        // These methods should be called between begin/end
        NVSDKENTRY virtual void drawFrame(const Rect & r, int margin, int style);

        NVSDKENTRY virtual Rect getLabelRect(const Rect & r, const char * text, Rect & rt, int& nbLines) const;
        NVSDKENTRY virtual void drawLabel(const Rect & r, const char * text, const Rect & rt, const int& nbLines, bool isHover, int style);

        NVSDKENTRY virtual Rect getButtonRect(const Rect & r, const char * text, Rect & rt) const;
        NVSDKENTRY virtual void drawButton(const Rect & r, const char * text, const Rect & rt, bool isDown, bool isHover, bool isFocus, int style);

        NVSDKENTRY virtual Rect getCheckRect(const Rect & r, const char * text, Rect & rt, Rect & rc) const;
        NVSDKENTRY virtual void drawCheckButton(const Rect & r, const char * text, const Rect & rt, const Rect & rr, bool isChecked, bool isHover, bool isFocus, int style);

        NVSDKENTRY virtual Rect getRadioRect(const Rect & r, const char * text, Rect & rt, Rect & rr) const;
        NVSDKENTRY virtual void drawRadioButton(const Rect & r, const char * text, const Rect & rt, const Rect & rr, bool isOn, bool isHover, bool isFocus, int style);

        NVSDKENTRY virtual Rect getHorizontalSliderRect(const Rect & r, Rect& rs, float v, Rect& rc) const;
        NVSDKENTRY virtual void drawHorizontalSlider(const Rect & r, Rect& rs, float v, Rect& rc, bool isHover, int style);

        NVSDKENTRY virtual Rect getItemRect(const Rect & r, const char * text, Rect & rt) const;
        NVSDKENTRY virtual Rect getListRect(const Rect & r, int numOptions, const char * options[], Rect& ri, Rect & rt) const;
        NVSDKENTRY virtual void drawListItem(const Rect & r, const char * text, const Rect & rt, bool isSelected, bool isHover, int style);
        NVSDKENTRY virtual void drawListBox(const Rect & r, int numOptions, const char * options[], const Rect& ri, const Rect & rt, int selected, int hovered, int style);

        NVSDKENTRY virtual Rect getComboRect(const Rect & r, int numOptions, const char * options[], int selected, Rect& rt, Rect& ra) const;
        NVSDKENTRY virtual Rect getComboOptionsRect(const Rect & rCombo, int numOptions, const char * options[], Rect& ri, Rect & rit) const;
        NVSDKENTRY virtual void drawComboBox(const Rect & rect, int numOptions, const char * options[], const Rect & rt, const Rect& rd, int selected, bool isHover, bool isFocus, int style);
        NVSDKENTRY virtual void drawComboOptions(const Rect & rect, int numOptions, const char * options[], const Rect& ri, const Rect & rit, int selected, int hovered, bool isHover, bool isFocus, int style);

        NVSDKENTRY virtual Rect getLineEditRect(const Rect & r, const char * text, Rect & rt) const;
        NVSDKENTRY virtual void drawLineEdit(const Rect & r, const char * text, const Rect & rt, int caretPos, bool isSelected, bool isHover, int style);

        NVSDKENTRY virtual Rect getPanelRect(const Rect & r, const char * text, Rect& rt, Rect& ra) const;
        NVSDKENTRY virtual void drawPanel(const Rect & rect, const char * text, const Rect & rt, const Rect & ra, bool isUnfold, bool isHover, bool isFocus, int style);

        NVSDKENTRY virtual Rect getTextureViewRect(const Rect & rect, Rect& rt) const;
        NVSDKENTRY virtual void drawTextureView(const Rect & rect, const void* texID, const Rect& rt, const Rect & rz, int mipLevel, int style);

        // Eval widget dimensions
        NVSDKENTRY virtual int getCanvasMargin() const;
        NVSDKENTRY virtual int getCanvasSpace() const;
        NVSDKENTRY virtual int getFontHeight() const;
        NVSDKENTRY virtual int getTextLineWidth(const char * text) const;
        NVSDKENTRY virtual int getTextSize(const char * text, int& nbLines) const;
        NVSDKENTRY virtual int getTextLineWidthAt(const char * text, int charNb) const;
        NVSDKENTRY virtual int getPickedCharNb(const char * text, const Point& at) const;

        NVSDKENTRY virtual void drawDebugRect(const Rect & r);

    protected:

        // Draw primitive shapes
        NVSDKENTRY void drawText( const Rect& r , const char * text, int nbLines = 1, int caretPos = -1, bool isHover = false, bool isOn = false, bool isFocus = false );
        NVSDKENTRY void drawFrame( const Rect& rect, const Point& corner, bool isHover = false, bool isOn = false, bool isFocus = false ) const;
        NVSDKENTRY void drawBoolFrame( const Rect& rect, const Point& corner, bool isHover = false, bool isOn = false, bool isFocus = false ) const;

        NVSDKENTRY void drawString( int x, int y, const char * text, int nbLines );
        NVSDKENTRY void drawRect( const Rect& rect, int fillColorId, int borderColorId ) const;
        NVSDKENTRY void drawRoundedRect( const Rect& rect, const Point& corner, int fillColorId, int borderColorId ) const;
        NVSDKENTRY void drawRoundedRectOutline( const Rect& rect, const Point& corner, int borderColorId ) const;
        NVSDKENTRY void drawCircle( const Rect& rect, int fillColorId, int borderColorId ) const;
        NVSDKENTRY void drawMinus( const Rect& rect, int width, int fillColorId, int borderColorId ) const;
        NVSDKENTRY void drawPlus( const Rect& rect, int width, int fillColorId, int borderColorId ) const;
        NVSDKENTRY void drawDownArrow( const Rect& rect, int width, int fillColorId, int borderColorId ) const;
        NVSDKENTRY void drawUpArrow( const Rect& rect, int width, int fillColorId, int borderColorId ) const;

        NVSDKENTRY void init();

        enum Color
        {
            cBase = 0,
            cBool = 8,
            cOutline = 16,
            cFont = 20,
            cFontBack = 24,
            cTranslucent = 32,
            cNbColors = 33,
        };

    private:

        GLuint m_setupStateDL;
        GLuint m_restoreStateDL;
		GLuint m_textListBase;
        GLuint m_foregroundDL;

        GLuint m_widgetProgram;
        GLuint m_originUniform;
        GLuint m_sizeUniform;
        GLuint m_fillColorUniform;
        GLuint m_borderColorUniform;
        GLuint m_zonesUniform;

        vec4f m_colors[cNbColors];
    };
};

#endif


text:
<!DOCTYPE html>
<html class="no-js">
  {% include head.html %}
  <body>
    {% include header.html %}
    {% include nav.html %}
    <div class="content">
      {{ content }}
    </div>
    {% include footer.html %}
  </body>
</html>


text:
videoResolution vResolution;

u32 curr_fb = 0;

u32 display_width;
u32 display_height;

u32 depth_pitch;
u32 depth_offset;
u32 *depth_buffer;

u32 color_pitch;
u32 color_offset[FRAME_BUFFER_COUNT];
u32 *color_buffer[FRAME_BUFFER_COUNT];

f32 aspect_ratio;

u32 fbOnDisplay = 0;
u32 fbFlipped = 0;
bool fbOnFlip = false;
sys_event_queue_t flipEventQueue;
sys_event_port_t flipEventPort;

gcmSurface surface;

static u32 sLabelVal = 1;

static u32 sResolutionIds[] = {
    VIDEO_RESOLUTION_1600x1080,
    VIDEO_RESOLUTION_1440x1080,
    VIDEO_RESOLUTION_1280x1080,
    VIDEO_RESOLUTION_960x1080,
    VIDEO_RESOLUTION_720,
    VIDEO_RESOLUTION_480,
    VIDEO_RESOLUTION_576
};
static size_t RESOLUTION_ID_COUNT = sizeof(sResolutionIds)/sizeof(u32);

extern "C" {
static void flipHandler(const u32 head)
{
    (void)head;
    u32 v = fbFlipped;

    for (u32 i = fbOnDisplay; i != v; i=(i + 1)%FRAME_BUFFER_COUNT) {
        *((vu32*) gcmGetLabelAddress(GCM_BUFFER_STATUS_INDEX + i)) = BUFFER_IDLE;
    }
    fbOnDisplay = v;
    fbOnFlip = false;

    sysEventPortSend(flipEventPort, 0, 0, 0);
}

static void vblankHandler(const u32 head)
{
    (void)head;
    u32 data;
    u32 bufferToFlip;
    u32 indexToFlip;

    data = *((vu32*) gcmGetLabelAddress(GCM_PREPARED_BUFFER_INDEX));
    bufferToFlip = (data >> 8);
    indexToFlip = (data & 0x07);

    if (!fbOnFlip) {
        if (bufferToFlip != fbOnDisplay) {
            s32 ret = gcmSetFlipImmediate(indexToFlip);
            if (ret != 0) {
                printf("flip immediate failed\n");
                return;
            }
            fbFlipped = bufferToFlip;
            fbOnFlip = true;
        }
    }
}
}

static void syncPPUGPU()
{
    vu32 *label = (vu32*) gcmGetLabelAddress(GCM_PREPARED_BUFFER_INDEX);
    while(((curr_fb + FRAME_BUFFER_COUNT - ((*label)>>8))%FRAME_BUFFER_COUNT) > MAX_BUFFER_QUEUE_SIZE) {
        sys_event_t event;

        sysEventQueueReceive(flipEventQueue, &event, 0);
        sysEventQueueDrain(flipEventQueue);
    }
}

static void waitRSXFinish()
{
	rsxSetWriteBackendLabel(gGcmContext,GCM_WAIT_LABEL_INDEX,sLabelVal);

	rsxFlushBuffer(gGcmContext);

	while(*(vu32*)gcmGetLabelAddress(GCM_WAIT_LABEL_INDEX)!=sLabelVal)
		usleep(30);

	++sLabelVal;
}

static void waitRSXIdle()
{
	rsxSetWriteBackendLabel(gGcmContext,GCM_WAIT_LABEL_INDEX,sLabelVal);
	rsxSetWaitLabel(gGcmContext,GCM_WAIT_LABEL_INDEX,sLabelVal);

	++sLabelVal;

	waitRSXFinish();
}

void initVideoConfiguration()
{
    s32 rval = 0;
    s32 resId = 0;

    for (size_t i=0;i < RESOLUTION_ID_COUNT;i++) {
        rval = videoGetResolutionAvailability(VIDEO_PRIMARY, sResolutionIds[i], VIDEO_ASPECT_AUTO, 0);
        if (rval != 1) continue;

        resId = sResolutionIds[i];
        rval = videoGetResolution(resId, &vResolution);
        if(!rval) break;
    }

    if(rval) {
        printf("Error: videoGetResolutionAvailability failed. No usable resolution.\n");
        exit(1);
    }

    videoConfiguration config = {
        (u8)resId,
        VIDEO_BUFFER_FORMAT_XRGB,
        VIDEO_ASPECT_AUTO,
        {0,0,0,0,0,0,0,0,0},
        (u32)vResolution.width*4
    };

    rval = videoConfigure(VIDEO_PRIMARY, &config, NULL, 0);
    if(rval) {
        printf("Error: videoConfigure failed.\n");
        exit(1);
    }

    videoState state;

    rval = videoGetState(VIDEO_PRIMARY, 0, &state);
    switch(state.displayMode.aspect) {
        case VIDEO_ASPECT_4_3:
            aspect_ratio = 4.0f/3.0f;
            break;
        case VIDEO_ASPECT_16_9:
            aspect_ratio = 16.0f/9.0f;
            break;
        default:
            printf("unknown aspect ratio %x\n", state.displayMode.aspect);
            aspect_ratio = 16.0f/9.0f;
            break;
    }

    display_height = vResolution.height;
    display_width = vResolution.width;
}

void initFlipEvent()
{
    sys_event_queue_attr_t queueAttr = { SYS_EVENT_QUEUE_PRIO, SYS_EVENT_QUEUE_PPU, "\0" };

    sysEventQueueCreate(&flipEventQueue, &queueAttr, SYS_EVENT_QUEUE_KEY_LOCAL, 32);
    sysEventPortCreate(&flipEventPort, SYS_EVENT_PORT_LOCAL, SYS_EVENT_PORT_NO_NAME);
    sysEventPortConnectLocal(flipEventPort, flipEventQueue);

    gcmSetFlipHandler(flipHandler);
    gcmSetVBlankHandler(vblankHandler);
}

void initRenderTarget()
{
    memset(&surface, 0, sizeof(gcmSurface));

	surface.colorFormat		= GCM_SURFACE_X8R8G8B8;
	surface.colorTarget		= GCM_SURFACE_TARGET_0;
	surface.colorLocation[0]	= GCM_LOCATION_RSX;
	surface.colorOffset[0]	= color_offset[curr_fb];
	surface.colorPitch[0]	= color_pitch;

    for(u32 i=1; i< GCM_MAX_MRT_COUNT;i++) {
        surface.colorLocation[i]	= GCM_LOCATION_RSX;
        surface.colorOffset[i]		= color_offset[curr_fb];
        surface.colorPitch[i]		= 64;
    }

	surface.depthFormat		= GCM_SURFACE_ZETA_Z16;
	surface.depthLocation	= GCM_LOCATION_RSX;
	surface.depthOffset		= depth_offset;
	surface.depthPitch		= depth_pitch;

	surface.type				= GCM_SURFACE_TYPE_LINEAR;
	surface.antiAlias		= GCM_SURFACE_CENTER_1;

	surface.width			= display_width;
	surface.height			= display_height;
	surface.x				= 0;
	surface.y				= 0;

}

void setRenderTarget(u32 index)
{
	surface.colorOffset[0]	= color_offset[index];
	rsxSetSurface(gGcmContext,&surface);
}

void initScreen()
{
    u32 zs_depth = 4;
    u32 color_depth = 4;
    u32 bufferSize = rsxAlign(HOST_ADDR_ALIGNMENT, (DEFAULT_CB_SIZE + HOST_SIZE));

    gcmInitDefaultFifoMode(GCM_DEFAULT_FIFO_MODE_CONDITIONAL);

    void *hostAddr = memalign(HOST_ADDR_ALIGNMENT, bufferSize);
    rsxInit(nullptr, DEFAULT_CB_SIZE, bufferSize, hostAddr);

    initVideoConfiguration();

	color_pitch = display_width*color_depth;
    depth_pitch = display_width*zs_depth;

    waitRSXIdle();

    gcmSetFlipMode(GCM_FLIP_HSYNC);

    void *buffer;
    for (u32 i=0;i < FRAME_BUFFER_COUNT;i++) {
        buffer = rsxMemalign(64,(display_height*color_pitch));
        rsxAddressToOffset(buffer,&color_offset[i]);
        printf("fb[%d]: %p (%08x) [%dx%d] %d\n", i, buffer, color_offset[i], display_width, display_height, color_pitch);
        gcmSetDisplayBuffer(i,color_offset[i],color_pitch,display_width,display_height);
    }

    buffer = rsxMemalign(64,(display_height*depth_pitch)*2);
    rsxAddressToOffset(buffer, &depth_offset);

    for (u32 i=0;i < FRAME_BUFFER_COUNT;i++) {
        *((vu32*) gcmGetLabelAddress(GCM_BUFFER_STATUS_INDEX + i)) = BUFFER_IDLE;
    }
    *((vu32*) gcmGetLabelAddress(GCM_PREPARED_BUFFER_INDEX)) = (fbOnDisplay << 8);
    *((vu32*) gcmGetLabelAddress(GCM_BUFFER_STATUS_INDEX + fbOnDisplay)) = BUFFER_BUSY;

    curr_fb = (fbOnDisplay + 1)%FRAME_BUFFER_COUNT;

    initFlipEvent();
    initRenderTarget();

    rsxSetWriteCommandLabel(gGcmContext, GCM_BUFFER_STATUS_INDEX + curr_fb, BUFFER_BUSY);
}

void flip()
{
    s32 qid = gcmSetPrepareFlip(gGcmContext, curr_fb);
    while (qid < 0) {
        usleep(100);
        qid = gcmSetPrepareFlip(gGcmContext, curr_fb);
    }

    rsxSetWriteBackendLabel(gGcmContext, GCM_PREPARED_BUFFER_INDEX, ((curr_fb << 8) | qid));
    rsxFlushBuffer(gGcmContext);

    syncPPUGPU();

    curr_fb = (curr_fb + 1)%FRAME_BUFFER_COUNT;

    rsxSetWaitLabel(gGcmContext, GCM_BUFFER_STATUS_INDEX + curr_fb, BUFFER_IDLE);
    rsxSetWriteCommandLabel(gGcmContext, GCM_BUFFER_STATUS_INDEX + curr_fb, BUFFER_BUSY);

    setRenderTarget(curr_fb);
}

void finish()
{
	rsxFinish(gGcmContext,1);

    u32 data = *((vu32*) gcmGetLabelAddress(GCM_PREPARED_BUFFER_INDEX));
    u32 lastBuffer = (data >> 8);
    while (lastBuffer != fbOnDisplay)
        usleep(100);
}


text:
package alma.acs.gui.loglevel.tree;

/**
 * The list of items in the tree.
 *
 * The tree contains clients, components and containers.
 * They all appear as lefs but having a different parent nodes.
 *
 * This class offers methods supporting the management of such items.
 *
 * @author acaproni
 *
 */
public class ItemsList {

}


text:
create table foo ( a integer, b varchar(10), c datetime ) reuse_oid;

insert into foo values ( 1, 'AAA',sys_datetime);
insert into foo values ( 2, 'AAA',sys_datetime);
insert into foo values ( 3, 'AAA',sys_datetime);
insert into foo values ( 4, 'AAA',sys_datetime);
insert into foo values ( 5, 'AAA',sys_datetime);

select a from foo where a in ( select a from foo where b = 'AAA' order by b, c limit 0, 10 );

select a from foo where a in ( select a from foo where b = 'AAA' limit 0, 10 ) order by 1;

select b from foo where a in ( select a from foo where b = 'AAA' order by a limit 0, 3 );

select a from foo where b in ( select b from foo where a < 4 order by b limit 0, 10) order by 1;

drop table foo;


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>themelock.com - Chain Responsive Bootstrap3 Admin</title>

        <link href="css/style.default.css" rel="stylesheet">
        <link href="css/morris.css" rel="stylesheet">
        <link href="css/select2.css" rel="stylesheet" />

Elen Adarna

                    username@domain.com

                <form id="unlock" method="post" action="index.html">

                        <input type="password" class="form-control" placeholder="Enter Password">

                    <button class="btn btn-success btn-block">Unlock</button>
                </form>

                        <form class="form form-search" action="search-results.html">
                            <input type="search" class="form-control" placeholder="Search" />
                        </form>

                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

                              5
                            </button>

Notification

                                          Nusja Nawancali likes a photo of you
                                           15 minutes ago

                                          Weno Carasbong shared a photo of you in your Mobile Uploads album.
                                           July 04, 2014

                                          Venro Leonga likes a photo of you
                                           July 03, 2014

                                          Nanterey Reslaba shared a photo of you in your Mobile Uploads album.
                                           July 03, 2014

                                          Nusja Nawancali shared a photo of you in your Mobile Uploads album.
                                           July 02, 2014

                                    See All Notifications

                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

                                2
                            </button>

New Messages

                                        New

                                          Nusja Nawancali

Hi! How are you?...

                                           15 minutes ago

                                        New

                                          Weno Carasbong

Lorem ipsum dolor sit amet...

                                           July 04, 2014

                                          Venro Leonga

Do you have the time to listen to me...

                                           July 03, 2014

                                          Nanterey Reslaba

It might seem crazy what I'm about to say...

                                           July 03, 2014

                                          Nusja Nawancali

Hey I just met you and this is crazy...

                                           July 02, 2014

                                    See All Messages

                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

                            </button>

 My Profile

 Activity Log

 Account Settings

 Help

Sign Out

Elen Adarna

                            Beach Lover

Navigation

 Dashboard

5 Messages

 UI Elements

Alerts & Notifications

Buttons

Extras

Graphs & Charts

Icons

Modals

Panels & Widgets

Sliders

Tabs & Accordions

Typography

 Forms

Code Editor

General Forms

Layouts

Text Editor

Validation

Wizards

 Tables

Basic Tables

Data Tables

 Maps

 Pages

404 Page

Blank Page

Calendar

Invoice

Locked Screen

Media Manager

People Directory

Profile

Search Results

Sign In

Sign Up

Dashboard

Dashboard

Today's Earnings

$8,102.32

Yesterday

$29,009.17

This Week

$99,103.67

New User Accounts

138,102

Yesterday

10,009

This Week

178,222

New User Posts

153,900

Yesterday

144,009

This Week

987,212

                            <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
                            Heads up! This alert needs your attention, but it's not super important.

Site Statistics

                                                Average

$9,201

                                                Total

$8,201

Site Visitors

                                                Average

52,201

                                                Total

11,201

Site Impressions

                                                Average

37,101

                                                Total

18,899

Network Performance

Duis autem vel eum iriure dolor in vulputate...

Server Status

Summary of the status of your server.

                                        CPU Usage (40.05 - 32 cpus)

                                        Memory Usage (32.2%)

                                        Disk Usage (82.2%)

                                        Databases (63/100)

                                        Domains (2/10)

                                        Email Account (13/50)

To-Do List Widget

                                                  <input type="checkbox" id="washcar" value="1">
                                                  Wash car in neighbors house

                                                  <input type="checkbox" checked="checked" id="eatpizza" value="1">
                                                  Find and eat pizza anywhere

                                                  <input type="checkbox" checked="checked" id="washdish" value="1">
                                                  Wash the dishes and map the floor

                                                  <input type="checkbox" id="buyclothes" value="1">
                                                  Buy some clothes

                                                  <input type="checkbox" checked="checked" id="throw" value="1">
                                                  Throw the garbage

                                                  <input type="checkbox" id="reply" value="1">
                                                  Reply all emails for this week

                                <form method="post" id="basicWizard" class="panel-wizard">

Step 1: Basic Info

Step 2: Product Info

Step 3: Payment

                                                Firstname

                                                    <input type="text" name="firstname" class="form-control" />

                                                Lastname

                                                    <input type="text" name="lastname" class="form-control" />

                                                Gender

                                                        <input type="radio" checked="checked" id="male" value="m" name="radio">
                                                        Male

                                                        <input type="radio" value="f" id="female" name="radio">
                                                        Female

                                                Product ID

                                                    <input type="text" name="product_id" class="form-control" />

                                                Product Name

                                                    <input type="text" name="product_name" class="form-control" />

                                                Category

                                                    <select class="width100p" data-placeholder="Choose One">
                                                        <option value="">Choose One</option>
                                                        <option value="">3D Animation</option>
                                                        <option value="">Web Design</option>
                                                        <option value="">Software Engineering</option>
                                                    </select>

                                                Card No

                                                    <input type="text" name="cardno" class="form-control" />

                                                Expiration

                                                    <select class="width100p" data-placeholder="Month">
                                                        <option value="">Choose One</option>
                                                        <option value="">January</option>
                                                        <option value="">February</option>
                                                        <option value="">March</option>
                                                        <option value="">...</option>
                                                    </select>

                                                    <select class="width100p" data-placeholder="Year">
                                                        <option value="">Choose One</option>
                                                        <option value="">2013</option>
                                                        <option value="">2014</option>
                                                        <option value="">2015</option>
                                                        <option value="">...</option>
                                                    </select>

                                                CSV

                                                    <input type="text" name="csv" class="form-control" />

<button type="button" class="btn btn-default">Previous</button>

<button type="button" class="btn btn-primary">Next</button>

<button type="submit" class="btn btn-primary">Finish</button>

                                </form>

                                                    Collapsible Group Item #1

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.

                                                    Collapsible Group Item #2

                                                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

                                                    Collapsible Group Item #3

Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch.

Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.


text:
#ifndef DEVICE_DATA_DISPATCHER_H
#define DEVICE_DATA_DISPATCHER_H

#include "../device.h"

/**
 * Returns the length of the data which corresponds to the header.
 * @param header the length of the header
 * @return -1 if we don't find any corresponding header, else the header length
 */
unsigned int getWaitedDataLength(const unsigned char header);

/**
 * Find the device associated with the specified data header.
 * @param deviceHeader the device header (to select device)
 * @param commandHeader the command header (to select command inside device)
 * @param dataLength the length of the InBuffer
 * @param mode DEVICE_MODE_INPUT or DEVICE_MODE_OUTPUT, if we want to find a device
 * by the INPUT (command/notification) or OUTPUT
 * @return the descriptor of the handling device, NULL if no registered device
 * can handle the data header
 */
const Device* deviceDataDispatcherFindDevice(const unsigned char deviceHeader, const unsigned char commandHeader, const int dataLength, const DeviceInterfaceMode mode);

#endif


text:
include $(shell rospack find mk)/cmake.mk

clean: clean_zbar

clean_zbar:
	make -C 3rdparty/zbar clean
	-rm -rf include/zbar* lib/libzbar* lib share


text:
layout: post
title: "More ColdFusion and Flex jobs in Jacksonville, Fl"
category: "Blog"
---
{% include JB/setup %}

I have been recently approached by two different companies in the Jacksonville, Fl area that are trying to hire ColdFusion developers. If you live in Jacksonville or are willing to relocate, these are good opportunities.

There are three open positions at [Taleo](http://www.taleo.com/). If you follow this [link](https://taleo.taleo.net/careersection/2/jobsearch.ftl?lang=en) and do a search for "Software Engineer" it will show the open positions. They are also trying to hire Java, C# and Flex developers.

Another company that is trying find ColdFusion developers is called [Andromeda Systems](http://www.androsysinc.com/Company/Careers.aspx).


text:
package cc.agentx.security;

public class RawCipher extends Cipher {
    @Override
    protected void _init(boolean isEncrypt, byte[] iv) {
        this.iv = new byte[0];
    }

    @Override
    protected byte[] _encrypt(final byte[] originData) {
        return originData;
    }

    @Override
    protected byte[] _decrypt(final byte[] encryptedData) {
        return encryptedData;
    }

    @Override
    public int getIVLength() {
        return 0;
    }
}


text:
@implementation IARLDataController

@synthesize radios = _radios;
@synthesize managedObjectContext = _managedObjectContext;
@synthesize bandFilter = _bandFilter;
@synthesize currentRegion = _currentRegion;

NSString * const IARLBandFilterKey = @"IARLBandFilterKey";
NSString * const IARLHFBandKey = @"HF";
NSString * const IARLVHFBandKey = @"VHF";
NSString * const IARLUHFBandKey = @"UHF";

NSString * const IARLHFCellImageName = @"tower_blue.png";
NSString * const IARLVHFCellImageName = @"tower_red.png";
NSString * const IARLUHFCellImageName = @"tower_orange.png";

NSString * const IARLHFAnnotationImageName = @"tower_blue.png";
NSString * const IARLVHFAnnotationImageName = @"tower_red.png";
NSString * const IARLUHFAnnotationImageName = @"tower_orange.png";

NSString * const IARLCellFont = @"HelveticaNeue-CondensedBold";

NSString * const IARLDataControllerRadiosKey = @"radios";
NSString * const IARLDataControllerBandsFilterKey = @"bandFilter";

- (id)initWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
{
    if (!(self = [self init]))
        return nil;

    _managedObjectContext = managedObjectContext;

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    _bandFilter = ([userDefaults objectForKey:IARLBandFilterKey] == nil)
        ? [NSSet setWithObjects:IARLHFBandKey, IARLVHFBandKey, IARLUHFBandKey, nil]
        : [NSSet setWithArray:[userDefaults objectForKey:IARLBandFilterKey]];

    return self;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.radios count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.backgroundView.backgroundColor = [UIColor blackColor];
        cell.textLabel.font = [UIFont fontWithName:IARLCellFont size:18.0];
        cell.textLabel.textColor = [UIColor colorWithRed:0.435 green:0.612 blue:0.518 alpha:1];
        cell.detailTextLabel.font = [UIFont fontWithName:IARLCellFont size:14.0];
        cell.detailTextLabel.textColor = [UIColor colorWithRed:0.682 green:0.761 blue:0.722 alpha:1];
    }

    IARLRadio *radio = [self.radios objectAtIndex:indexPath.row];

    cell.textLabel.text = radio.callName;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"tx: %@, shift: %@", radio.tx, radio.shift];

    NSString *band = [radio.tx bandFromFrequency];

    if ([band isEqualToString:IARLHFBandKey])
        cell.imageView.image = [UIImage imageNamed:IARLHFCellImageName];
    else if ([band isEqualToString:IARLVHFBandKey])
        cell.imageView.image = [UIImage imageNamed:IARLVHFCellImageName];
    else if ([band isEqualToString:IARLUHFBandKey])
        cell.imageView.image = [UIImage imageNamed:IARLUHFCellImageName];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // IARLRadio *radio = [self.radios objectAtIndex:indexPath.row];
    // [self.mapController selectAnnotation:radio animated:YES];
}

#pragma mark - MKMapViewDelegate

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    self.currentRegion = mapView.region ;
    [self updateRadiosInCurrentRegion];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    static NSString *AnnotationReuseIdentifier = @"AnnotationReuseIdentifier";
    IARLAnnotationView *annotationView = (IARLAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationReuseIdentifier];

    if (!annotationView) {
        annotationView = [[IARLAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationReuseIdentifier];
    }

    annotationView.annotation = annotation;

    if (annotation == mapView.userLocation) {
        annotationView.canShowCallout = NO;
    }
    else {
        annotationView.canShowCallout = NO;
        UIButton *callOutButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [callOutButton addTarget:nil action:@selector(annotationDisclosureButtonTapped:) forControlEvents:UIControlEventAllTouchEvents];
        annotationView.rightCalloutAccessoryView = callOutButton;
    }

    return annotationView;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    IARLAnnotationView *annotationView = (IARLAnnotationView *)view;
    CGRect calloutRect;
    calloutRect.size = CGSizeMake(1.0, 1.0);
    calloutRect.origin = [mapView convertCoordinate:view.annotation.coordinate toPointToView:mapView];

    IARLRadioDetailViewController *rdvc = [[IARLRadioDetailViewController alloc] init];
    rdvc.radio = (IARLRadio *)view.annotation;
    UIPopoverController *pc = [[UIPopoverController alloc] initWithContentViewController:rdvc];
    annotationView.popoverController = pc;
    pc.passthroughViews = [NSArray arrayWithObject:mapView];
    [pc presentPopoverFromRect:calloutRect inView:mapView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view
{
    IARLAnnotationView *annotationView = (IARLAnnotationView *)view;
    [annotationView.popoverController dismissPopoverAnimated:YES];
    annotationView.popoverController = nil;
}

#pragma mark - API

- (void)setBandFilter:(NSSet *)bandFilter
{
    [self willChangeValueForKey:IARLDataControllerBandsFilterKey];
    _bandFilter = [bandFilter copy];
    [self didChangeValueForKey:IARLDataControllerBandsFilterKey];

    [self updateRadiosInCurrentRegion];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[_bandFilter allObjects] forKey:IARLBandFilterKey];
    [userDefaults synchronize];
}

- (NSArray *)radiosInRegion:(MKCoordinateRegion)region
{

    double latitudeDelta = region.span.latitudeDelta / 2.0;
    double minLatitude = region.center.latitude - latitudeDelta;
    double maxLatitude = region.center.latitude + latitudeDelta;

    double longitudeDelta = region.span.longitudeDelta / 2.0;
    double minLongitude = region.center.longitude - longitudeDelta;
    double maxLongitude = region.center.longitude + longitudeDelta;

    [_bandFilter count];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:
                              @"latitude BETWEEN {%@, %@} AND longitude BETWEEN {%@, %@} AND bandFrequency IN %@",
                              [NSNumber numberWithDouble:minLatitude], [NSNumber numberWithDouble:maxLatitude],
                              [NSNumber numberWithDouble:minLongitude], [NSNumber numberWithDouble:maxLongitude],
                              _bandFilter,
                              nil];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"IARLRadio" inManagedObjectContext:self.managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"IARLRadio"];
    fetchRequest.predicate = predicate;
    fetchRequest.entity = entity;

    NSError *error;
    NSArray *radiosInRegion = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    if (radiosInRegion == nil) {
        // error.
    }

    return radiosInRegion;
}

- (void)updateRadiosInCurrentRegion
{
    [self updateRadiosInRegion:_currentRegion];
}

- (void)updateRadiosInRegion:(MKCoordinateRegion)region
{
    self.radios = [self radiosInRegion:region];
}

@end


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CM.Payments.Client.Model;
using System.Reflection;
using CM.Payments.Client.Enums;

//<auto-generated>
//	IMPORTANT NOTE:
//	This code is generated by MessageUnitTestGenerator in this project.
//	Date and time: 06-04-2018 14:52:27
//
//	Changes to this file may cause incorrect behavior and will be lost on the next code generation.
//</auto-generated>
namespace CM.Payments.Client.Test
{
	[TestClass, ExcludeFromCodeCoverage]
	public partial class BancontactDetailsResponseTests : BaseJsonConvertTests
	{
		public TestContext TestContext { get; set; }

		[TestMethod]
		public void BancontactDetailsResponse()
		{
			var obj = new BancontactDetailsResponse
			{
				AuthenticationUrl = "Lorum_649",
				CallbackUrl = "Lorum_503",
				CancelledUrl = "Lorum_888",
				ExpiredUrl = "Lorum_48",
				FailedUrl = "Lorum_619",
				Issuer = "Lorum_539",
				Issuers = new []
				{
					"Lorum_694",
					"Lorum_412"
				},
				MaskedPan = "Lorum_940",
				PurchaseId = "Lorum_508",
				ReasonForFailure = "Lorum_900",
				SuccessUrl = "Lorum_166"
			};
			var deserialized = ConversionTest(obj);
			Assert.IsNotNull(deserialized);
			Assert.AreEqual(obj.AuthenticationUrl, deserialized.AuthenticationUrl);
			Assert.AreEqual(obj.CallbackUrl, deserialized.CallbackUrl);
			Assert.AreEqual(obj.CancelledUrl, deserialized.CancelledUrl);
			Assert.AreEqual(obj.ExpiredUrl, deserialized.ExpiredUrl);
			Assert.AreEqual(obj.FailedUrl, deserialized.FailedUrl);
			Assert.AreEqual(obj.Issuer, deserialized.Issuer);
			Assert.AreEqual(obj.Issuers.IsFixedSize, deserialized.Issuers.IsFixedSize);
			Assert.AreEqual(obj.Issuers.IsReadOnly, deserialized.Issuers.IsReadOnly);
			Assert.AreEqual(obj.Issuers.IsSynchronized, deserialized.Issuers.IsSynchronized);
			Assert.AreEqual(obj.Issuers.Length, deserialized.Issuers.Length);
			Assert.AreEqual(obj.Issuers.LongLength, deserialized.Issuers.LongLength);
			Assert.AreEqual(obj.Issuers.Rank, deserialized.Issuers.Rank);
			Assert.AreEqual(obj.MaskedPan, deserialized.MaskedPan);
			Assert.AreEqual(obj.PurchaseId, deserialized.PurchaseId);
			Assert.AreEqual(obj.ReasonForFailure, deserialized.ReasonForFailure);
			Assert.AreEqual(obj.SuccessUrl, deserialized.SuccessUrl);
		}
	}
}


text:
"""Support to embed Sonos."""
from __future__ import annotations

import asyncio
from collections import OrderedDict
import datetime
from enum import Enum
from functools import partial
import logging
import socket
from urllib.parse import urlparse

from soco import events_asyncio
import soco.config as soco_config
from soco.core import SoCo
from soco.exceptions import NotSupportedException, SoCoException
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.components import ssdp
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOSTS, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_track_time_interval, call_later

from .alarms import SonosAlarms
from .const import (
    AVAILABILITY_CHECK_INTERVAL,
    DATA_SONOS,
    DATA_SONOS_DISCOVERY_MANAGER,
    DISCOVERY_INTERVAL,
    DOMAIN,
    PLATFORMS,
    SONOS_CHECK_ACTIVITY,
    SONOS_REBOOTED,
    SONOS_SPEAKER_ACTIVITY,
    UPNP_ST,
)
from .favorites import SonosFavorites
from .speaker import SonosSpeaker

_LOGGER = logging.getLogger(__name__)

CONF_ADVERTISE_ADDR = "advertise_addr"
CONF_INTERFACE_ADDR = "interface_addr"
DISCOVERY_IGNORED_MODELS = ["Sonos Boost"]

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema(
            {
                MP_DOMAIN: vol.All(
                    cv.deprecated(CONF_INTERFACE_ADDR),
                    vol.Schema(
                        {
                            vol.Optional(CONF_ADVERTISE_ADDR): cv.string,
                            vol.Optional(CONF_INTERFACE_ADDR): cv.string,
                            vol.Optional(CONF_HOSTS): vol.All(
                                cv.ensure_list_csv, [cv.string]
                            ),
                        }
                    ),
                )
            }
        )
    },
    extra=vol.ALLOW_EXTRA,
)

class SoCoCreationSource(Enum):
    """Represent the creation source of a SoCo instance."""

    CONFIGURED = "configured"
    DISCOVERED = "discovered"
    REBOOTED = "rebooted"

class SonosData:
    """Storage class for platform global data."""

    def __init__(self) -> None:
        """Initialize the data."""
        # OrderedDict behavior used by SonosAlarms and SonosFavorites
        self.discovered: OrderedDict[str, SonosSpeaker] = OrderedDict()
        self.favorites: dict[str, SonosFavorites] = {}
        self.alarms: dict[str, SonosAlarms] = {}
        self.topology_condition = asyncio.Condition()
        self.hosts_heartbeat = None
        self.discovery_ignored: set[str] = set()
        self.discovery_known: set[str] = set()
        self.boot_counts: dict[str, int] = {}
        self.mdns_names: dict[str, str] = {}

async def async_setup(hass, config):
    """Set up the Sonos component."""
    conf = config.get(DOMAIN)

    hass.data[DOMAIN] = conf or {}

    if conf is not None:
        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN, context={"source": config_entries.SOURCE_IMPORT}
            )
        )

    return True

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Sonos from a config entry."""
    soco_config.EVENTS_MODULE = events_asyncio

    if DATA_SONOS not in hass.data:
        hass.data[DATA_SONOS] = SonosData()

    data = hass.data[DATA_SONOS]
    config = hass.data[DOMAIN].get("media_player", {})
    hosts = config.get(CONF_HOSTS, [])
    _LOGGER.debug("Reached async_setup_entry, config=%s", config)

    if advertise_addr := config.get(CONF_ADVERTISE_ADDR):
        soco_config.EVENT_ADVERTISE_IP = advertise_addr

    if deprecated_address := config.get(CONF_INTERFACE_ADDR):
        _LOGGER.warning(
            "'%s' is deprecated, enable %s in the Network integration (https://www.home-assistant.io/integrations/network/)",
            CONF_INTERFACE_ADDR,
            deprecated_address,
        )

    manager = hass.data[DATA_SONOS_DISCOVERY_MANAGER] = SonosDiscoveryManager(
        hass, entry, data, hosts
    )
    hass.async_create_task(manager.setup_platforms_and_discovery())
    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a Sonos config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    await hass.data[DATA_SONOS_DISCOVERY_MANAGER].async_shutdown()
    hass.data.pop(DATA_SONOS)
    hass.data.pop(DATA_SONOS_DISCOVERY_MANAGER)
    return unload_ok

class SonosDiscoveryManager:
    """Manage sonos discovery."""

    def __init__(
        self, hass: HomeAssistant, entry: ConfigEntry, data: SonosData, hosts: list[str]
    ) -> None:
        """Init discovery manager."""
        self.hass = hass
        self.entry = entry
        self.data = data
        self.hosts = hosts
        self.discovery_lock = asyncio.Lock()

    async def async_shutdown(self):
        """Stop all running tasks."""
        await self._async_stop_event_listener()
        self._stop_manual_heartbeat()

    def _create_soco(self, ip_address: str, source: SoCoCreationSource) -> SoCo | None:
        """Create a soco instance and return if successful."""
        if ip_address in self.data.discovery_ignored:
            return None

        try:
            soco = SoCo(ip_address)
            # Ensure that the player is available and UID is cached
            uid = soco.uid
            _ = soco.volume
            return soco
        except NotSupportedException as exc:
            _LOGGER.debug("Device %s is not supported, ignoring: %s", uid, exc)
            self.data.discovery_ignored.add(ip_address)
        except (OSError, SoCoException) as ex:
            _LOGGER.warning(
                "Failed to connect to %s player '%s': %s", source.value, ip_address, ex
            )
        return None

    async def _async_stop_event_listener(self, event: Event | None = None) -> None:
        await asyncio.gather(
            *(speaker.async_offline() for speaker in self.data.discovered.values())
        )
        if events_asyncio.event_listener:
            await events_asyncio.event_listener.async_stop()

    def _stop_manual_heartbeat(self, event: Event | None = None) -> None:
        if self.data.hosts_heartbeat:
            self.data.hosts_heartbeat()
            self.data.hosts_heartbeat = None

    def _discovered_player(self, soco: SoCo) -> None:
        """Handle a (re)discovered player."""
        try:
            speaker_info = soco.get_speaker_info(True)
            _LOGGER.debug("Adding new speaker: %s", speaker_info)
            speaker = SonosSpeaker(self.hass, soco, speaker_info)
            self.data.discovered[soco.uid] = speaker
            for coordinator, coord_dict in (
                (SonosAlarms, self.data.alarms),
                (SonosFavorites, self.data.favorites),
            ):
                if soco.household_id not in coord_dict:
                    new_coordinator = coordinator(self.hass, soco.household_id)
                    new_coordinator.setup(soco)
                    coord_dict[soco.household_id] = new_coordinator
            speaker.setup(self.entry)
        except (OSError, SoCoException):
            _LOGGER.warning("Failed to add SonosSpeaker using %s", soco, exc_info=True)

    def _manual_hosts(self, now: datetime.datetime | None = None) -> None:
        """Players from network configuration."""
        for host in self.hosts:
            ip_addr = socket.gethostbyname(host)
            known_uid = next(
                (
                    uid
                    for uid, speaker in self.data.discovered.items()
                    if speaker.soco.ip_address == ip_addr
                ),
                None,
            )
            if not known_uid:
                soco = self._create_soco(ip_addr, SoCoCreationSource.CONFIGURED)
                if soco and soco.is_visible:
                    self._discovered_player(soco)

        self.data.hosts_heartbeat = call_later(
            self.hass, DISCOVERY_INTERVAL.total_seconds(), self._manual_hosts
        )

    def _discovered_ip(self, ip_address):
        soco = self._create_soco(ip_address, SoCoCreationSource.DISCOVERED)
        if soco and soco.is_visible:
            self._discovered_player(soco)

    async def _async_create_discovered_player(self, uid, discovered_ip, boot_seqnum):
        """Only create one player at a time."""
        async with self.discovery_lock:
            if uid not in self.data.discovered:
                await self.hass.async_add_executor_job(
                    self._discovered_ip, discovered_ip
                )
                return

            if boot_seqnum and boot_seqnum > self.data.boot_counts[uid]:
                self.data.boot_counts[uid] = boot_seqnum
                if soco := await self.hass.async_add_executor_job(
                    self._create_soco, discovered_ip, SoCoCreationSource.REBOOTED
                ):
                    async_dispatcher_send(self.hass, f"{SONOS_REBOOTED}-{uid}", soco)
            else:
                async_dispatcher_send(
                    self.hass, f"{SONOS_SPEAKER_ACTIVITY}-{uid}", "discovery"
                )

    async def _async_ssdp_discovered_player(
        self, info: ssdp.SsdpServiceInfo, change: ssdp.SsdpChange
    ) -> None:
        if change == ssdp.SsdpChange.BYEBYE:
            return

        uid = info.upnp[ssdp.ATTR_UPNP_UDN]
        if not uid.startswith("uuid:RINCON_"):
            return

        uid = uid[5:]
        discovered_ip = urlparse(info.ssdp_location).hostname
        boot_seqnum = info.ssdp_headers.get("X-RINCON-BOOTSEQ")
        self.async_discovered_player(
            "SSDP",
            info,
            discovered_ip,
            uid,
            boot_seqnum,
            info.upnp.get(ssdp.ATTR_UPNP_MODEL_NAME),
            None,
        )

    @callback
    def async_discovered_player(
        self, source, info, discovered_ip, uid, boot_seqnum, model, mdns_name
    ):
        """Handle discovery via ssdp or zeroconf."""
        if model in DISCOVERY_IGNORED_MODELS:
            _LOGGER.debug("Ignoring device: %s", info)
            return
        if boot_seqnum:
            boot_seqnum = int(boot_seqnum)
            self.data.boot_counts.setdefault(uid, boot_seqnum)
        if mdns_name:
            self.data.mdns_names[uid] = mdns_name

        if uid not in self.data.discovery_known:
            _LOGGER.debug("New %s discovery uid=%s: %s", source, uid, info)
            self.data.discovery_known.add(uid)
        asyncio.create_task(
            self._async_create_discovered_player(uid, discovered_ip, boot_seqnum)
        )

    async def setup_platforms_and_discovery(self):
        """Set up platforms and discovery."""
        await asyncio.gather(
            *(
                self.hass.config_entries.async_forward_entry_setup(self.entry, platform)
                for platform in PLATFORMS
            )
        )
        self.entry.async_on_unload(
            self.hass.bus.async_listen_once(
                EVENT_HOMEASSISTANT_STOP, self._async_stop_event_listener
            )
        )
        _LOGGER.debug("Adding discovery job")
        if self.hosts:
            self.entry.async_on_unload(
                self.hass.bus.async_listen_once(
                    EVENT_HOMEASSISTANT_STOP, self._stop_manual_heartbeat
                )
            )
            await self.hass.async_add_executor_job(self._manual_hosts)
            return

        self.entry.async_on_unload(
            await ssdp.async_register_callback(
                self.hass, self._async_ssdp_discovered_player, {"st": UPNP_ST}
            )
        )

        self.entry.async_on_unload(
            async_track_time_interval(
                self.hass,
                partial(
                    async_dispatcher_send,
                    self.hass,
                    SONOS_CHECK_ACTIVITY,
                ),
                AVAILABILITY_CHECK_INTERVAL,
            )
        )


text:
'use strict';

import * as assert from 'assert';
import * as path from 'path';
import { parseArgs } from 'vs/platform/environment/node/argv';
import { parseExtensionHostPort, parseUserDataDir } from 'vs/platform/environment/node/environmentService';

suite('EnvironmentService', () => {

	test('parseExtensionHostPort when built', () => {
		const parse = a => parseExtensionHostPort(parseArgs(a), true);

		assert.deepEqual(parse([]), { port: null, break: false, debugId: undefined });
		assert.deepEqual(parse(['--debugPluginHost']), { port: null, break: false, debugId: undefined });
		assert.deepEqual(parse(['--debugPluginHost=1234']), { port: 1234, break: false, debugId: undefined });
		assert.deepEqual(parse(['--debugBrkPluginHost']), { port: null, break: false, debugId: undefined });
		assert.deepEqual(parse(['--debugBrkPluginHost=5678']), { port: 5678, break: true, debugId: undefined });
		assert.deepEqual(parse(['--debugPluginHost=1234', '--debugBrkPluginHost=5678', '--debugId=7']), { port: 5678, break: true, debugId: '7' });
	});

	test('parseExtensionHostPort when unbuilt', () => {
		const parse = a => parseExtensionHostPort(parseArgs(a), false);

		assert.deepEqual(parse([]), { port: 5870, break: false, debugId: undefined });
		assert.deepEqual(parse(['--debugPluginHost']), { port: 5870, break: false, debugId: undefined });
		assert.deepEqual(parse(['--debugPluginHost=1234']), { port: 1234, break: false, debugId: undefined });
		assert.deepEqual(parse(['--debugBrkPluginHost']), { port: 5870, break: false, debugId: undefined });
		assert.deepEqual(parse(['--debugBrkPluginHost=5678']), { port: 5678, break: true, debugId: undefined });
		assert.deepEqual(parse(['--debugPluginHost=1234', '--debugBrkPluginHost=5678', '--debugId=7']), { port: 5678, break: true, debugId: '7' });
	});

	test('userDataPath', () => {
		const parse = (a, b: { cwd: () => string, env: { [key: string]: string } }) => parseUserDataDir(parseArgs(a), <any>b);

		assert.equal(parse(['--user-data-dir', './dir'], { cwd: () => '/foo', env: {} }), path.resolve('/foo/dir'),
			'should use cwd when --user-data-dir is specified');
		assert.equal(parse(['--user-data-dir', './dir'], { cwd: () => '/foo', env: { 'VSCODE_CWD': '/bar' } }), path.resolve('/bar/dir'),
			'should use VSCODE_CWD as the cwd when --user-data-dir is specified');
	});
});


text:
This is a fork of https://github.com/sherjilozair/char-rnn-tensorflow with modifications to enable the trained models to be used in other environments (e.g. [ofxMSATensorFlow](https://github.com/memo/ofxMSATensorFlow)). Reasons as to why these changes are nessecary are described [here](https://github.com/memo/ofxMSATensorFlow/wiki/Loading-and-using-trained-tensorflow-models-in-openFrameworks).

After training, run:

[sample.py](https://github.com/memo/char-rnn-tensorflow/blob/master/sample.py) with the `--freeze_graph` argument to prune, freeze and save the graph as a binary protobuf to be loaded in C++ (removing unnessecary nodes used in training, and replacing variables with consts). It also saves the character-index map as a text file.

[sample_frozen.py](https://github.com/memo/char-rnn-tensorflow/blob/master/test_frozen.py) demonstrates inference with the frozen graph from python. It also works in [C++/openFrameworks](https://github.com/memo/ofxMSATensorFlow/blob/master/example-char-rnn/src/example-char-rnn.cpp).

---
# char-rnn-tensorflow
Multi-layer Recurrent Neural Networks (LSTM, RNN) for character-level language models in Python using Tensorflow.

Inspired from Andrej Karpathy's [char-rnn](https://github.com/karpathy/char-rnn).

# Requirements
- [Tensorflow 1.0](http://www.tensorflow.org)

# Basic Usage
To train with default parameters on the tinyshakespeare corpus, run `python train.py`.

To sample from a checkpointed model, `python sample.py`.
# Roadmap
- Add explanatory comments
- Expose more command-line arguments
- Compare accuracy and performance with char-rnn


text:
import axios from 'axios';
import { createMemoryHistory, match } from 'react-router';
import createRoutes from '../../app/routes';
import configureStore from '../../app/store/configureStore';
import * as types from '../../app/types';
import { baseURL } from '../../config/app';
import pageRenderer from './pageRenderer';
import fetchDataForRoute from '../../app/utils/fetchDataForRoute';

// configure baseURL for axios requests (for serverside API calls)
axios.defaults.baseURL = baseURL;

/*
 * Export render function to be used in server/config/routes.js
 * We grab the state passed in from the server and the req object from Express/Koa
 * and pass it into the Router.run function.
 */
export default function render(req, res) {
  const authenticated = req.isAuthenticated();
  const history = createMemoryHistory();
  const store = configureStore({}, history);
  const routes = createRoutes(store);

  /*
   * From the react-router docs:
   *
   * This function is to be used for server-side rendering. It matches a set of routes to
   * a location, without rendering, and calls a callback(err, redirect, props)
   * when it's done.
   *
   * The function will create a `history` for you, passing additional `options` to create it.
   * These options can include `basename` to control the base name for URLs, as well as the pair
   * of `parseQueryString` and `stringifyQuery` to control query string parsing and serializing.
   * You can also pass in an already instantiated `history` object, which can be constructed
   * however you like.
   *
   * The three arguments to the callback function you pass to `match` are:
   * - err:       A javascript Error object if an error occurred, `undefined` otherwise.
   * - redirect:  A `Location` object if the route is a redirect, `undefined` otherwise
   * - props:     The props you should pass to the routing context if the route matched,
   *              `undefined` otherwise.
   * If all three parameters are `undefined`, this means that there was no route found matching the
   * given location.
   */
  match({routes, location: req.url}, (err, redirect, props) => {
    if (err) {
      res.status(500).json(err);
    } else if (redirect) {
      res.redirect(302, redirect.pathname + redirect.search);
    } else if (props) {
      // This method waits for all render component
      // promises to resolve before returning to browser
      store.dispatch({ type: types.CREATE_REQUEST });
      fetchDataForRoute(props)
        .then(data => {
          store.dispatch({ type: types.REQUEST_SUCCESS, data });
          const html = pageRenderer(store, props);
          res.status(200).send(html);
        })
        .catch(err => {
          console.log('@@@@@@@@@@@@@@@@@@@@@@@@@ ERROR @@@@@@@@@@@@@@@@@@@@@@@');
          console.log(err.stack);
          console.error(err);
          res.status(500).json(err);
        });
    } else {
      res.sendStatus(404);
    }
  });
}


text:
declare module "promptly" {
  import stream = require('stream');

  interface Callback {
    (err: Error, value: string): void;
  }

  export interface Options {
    default?: string;
    trim?: boolean;
    validator?: any;
    retry?: boolean;
    silent?: boolean;
    input?: NodeJS.ReadableStream;
    output?: NodeJS.WritableStream;
  }

  export function prompt(message: string, fn?: Callback):any;
  export function prompt(message: string, opts: Options, fn?: Callback):any;

  export function password(message: string, fn?: Callback):any;
  export function password(message: string, opts: Options, fn?: Callback):any;

  export function confirm(message: string, fn?: Callback):any;
  export function confirm(message: string, opts: Options, fn?: Callback):any;

  export function choose(message: string, choices: string[], fn?: Callback):any;
  export function choose(message: string, choices: string[], opts: Options, fn?: Callback):any;

}


text:
package com.brandon3055.townbuilder.utills;

import net.minecraftforge.fml.common.FMLCommonHandler;

/**
 * Created by Brandon on 25/02/2015.
 */
public class Utills {

    public static final boolean isSinglePlayerServer() {
        return FMLCommonHandler.instance().getMinecraftServerInstance() != null;
    }

    public static final boolean isMultiPlayerServer() {
        return FMLCommonHandler.instance().getMinecraftServerInstance() == null;
    }

    public static String cutStringToLength(String s, int length) {
        return s.length() <= length ? s : s.substring(0, length);
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Adavanced Data Analytics</title>
    <link>https://DataPrajna.github.io/tags/academic/index.xml</link>
    <description>Recent content on Adavanced Data Analytics</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>&copy; 2016 PrajnaParamita</copyright>
    <atom:link href="/tags/academic/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Getting started with the Academic theme for Hugo</title>
      <link>https://dataprajna.github.io/post/getting-started/</link>
      <pubDate>Wed, 20 Apr 2016 12:00:00 +0000</pubDate>

      <guid>https://dataprajna.github.io/post/getting-started/</guid>
      <description>

The Academic theme enables you to easily create a beautifully simple academic or personal website using the Hugo static site generator.

Key features:

Designed for personal and academic staff/student use

Customizable Biography, Publications, Projects, News/Blog, Teaching, and Contact widgets

Write in Markdown for easy formatting and code highlighting, with LaTeX for mathematical expressions

Academic linking (Scholar etc.), Google Analytics, and Disqus comments

Responsive and mobile friendly

Simple and refreshing one page design

Installation

Install Hugo and create a new website by typing the following commands in your Terminal or Command Prompt app:

hugo new site my_website
cd my_website

Install Academic theme with git:

git clone https://github.com/gcushen/hugo-academic.git themes/academic

Or alternatively, download Academic and extract it into a themes/academic folder within your Hugo website.

If you are creating a new website, copy the contents of the exampleSite folder to your website root folder, overwriting existing files if necessary. The exampleSite folder contains an example config file and content to help you get started.

cp -av themes/academic/exampleSite/* .

Start the Hugo server from your website root folder:

hugo server --watch

Now you can go to localhost:1313 and your new Academic themed website should appear.

Customize your website - refer to the Getting Started section below

Build your site by running the hugo command. Then host it for free using Github Pages. Or alternatively, copy the generated public/ directory (by FTP, Rsync, etc.) to your production web server (such as your university&rsquo;s hosting service).

Getting Started

Assuming you created a new website with the example content following the installation steps above, this section explores just a few more steps in order to customize it.

Core parameters

The core parameters for the website can be edited in the config.toml configuration file:

Set baseurl to your website URL (we recommend GitHub Pages for free hosting)

Set title to your desired website title such as your name

The example Disqus commenting variable should be cleared (e.g. disqusShortname = &quot;&quot;) or set to your own Disqus shortname to enable commenting

Edit your details under [params]; these will be displayed mainly in the homepage about and contact widgets (if used). To disable a contact field, simply clear the value to &quot;&quot;.

Place a square cropped portrait photo named portrait.jpg into the static/img/ folder, overwriting any defaults. Alternatively, you can edit the avatar filepath to point to a different image name or clear the value to disable the avatar feature.

To enable LaTeX math for your site, set math = true

Social/academic networking links are defined as multiples of [[params.social]]. They can be created or deleted as necessary.

Introduce yourself

Edit your biography in the about widget content/home/about.md that you copied across from the themes/academic/exampleSite/ folder. The research interests and qualifications are stored as interests and education variables. The academic qualifications are defined as multiples of [[education.courses]] and can be created or deleted as necessary. It&rsquo;s possible to completely hide the interests and education lists by deleting their respective variables.

Customize homepage widgets

Each widget is responsible for a section on the homepage and contains further parameters that can be edited as desired. The parameters can be found in the preamble/frontmatter (between the pair of +++) for each widget located in the content/home/ folder.

By default, publications will be displayed in a simple list. If you prefer a more detailed list with abstract and image, you can enable the detailed publication list on the homepage by setting detailed_list = true in content/home/publications.md.

Add your content

Refer to our guide on managing content to create your own homepage sections, publications, blog posts, and projects.

Remove unused widgets and pages

How to remove unused widgets and content pages.

Customization &amp; Upgrading

Continue reading below for advanced customization tips and instructions for keeping the theme up-to-date with any improvements that become available.

Advanced customization

It is possible to carry out many customizations without touching any files in themes/academic, making it easier to upgrade the theme in the future.

Navigation menu

The [[menu.main]] entries towards the bottom of config.toml define the navigation links at the top of the website. They can be added or removed as desired.

Website icon

Save your main icon and mobile icon as square PNG images named icon.png and apple-touch-icon.png, respectively. Place them in your root static/img/ folder.

Theme color (CSS)

You can link custom CSS assets (relative to your root static/css) from your config.toml using custom_css = [&quot;custom.css&quot;].

For example, lets make a green theme. First, define custom_css = [&quot;green.css&quot;] in config.toml. Then we can download the example green theme and save it as static/css/green.css, relative to your website root (i.e. not in the themes directory).

Analytics

To enable Google Analytics, add your tracking code in config.toml similarly to googleAnalytics = &quot;UA-12345678-9&quot;.

Third party and local scripts (JS)

To add a third party script, create a file named head_custom.html in a layouts/partials/ folder at the root of your website (not in the themes folder). Any HTML code added to this file will be included within your website&rsquo;s &lt;head&gt;. Therefore, it&rsquo;s suitable for adding custom metadata or third party scripts specified with the async attribute.

Whereas for your own local scripts, you can link your local JS assets (relative to your root static/js) from your config.toml using custom_js  = [&quot;custom.js&quot;].

Permalinks

Permalinks, or permanent links, are URLs to individual pages and posts on your website. They are permanent web addresses which can be used to link to your content. Using Hugo&rsquo;s permalinks option these can be easily customized. For example, the blog post URL can be changed to the form yourURL/2016/05/01/my-post-slug by adding the following near the top of your config.toml (before [params] settings):

[permalinks]
    post = &quot;/:year/:month/:day/:slug&quot;

Where :slug defaults to the filename of the post, excluding the file extension. However, slug may be overridden on a per post basis if desired, simply by setting slug = &quot;my-short-post-title&quot; in your post preamble.

Upgrading

Feel free to star the project on Github and monitor the commits for updates.

Before upgrading the theme, it is recommended to make a backup of your entire website directory, or at least your themes/academic directory. You can also read about the most recent milestones (but this doesn&rsquo;t necessarily reflect the latest master release).

Before upgrading for the first time, the remote origin repository should be renamed to upstream:

$ cd themes/academic
$ git remote rename origin upstream

To list available updates:

$ cd themes/academic
$ git fetch upstream
$ git log --pretty=oneline --abbrev-commit --decorate HEAD..upstream/master

Then, upgrade by running:

$ git pull upstream

If you have modified files in themes/academic, git will attempt to auto-merge changes. If conflicts are reported, you will need to manually edit the files with conflicts and add them back (git add &lt;filename&gt;).

If there are any issues after upgrading, you may wish to compare your site with the latest example site to check if any settings changed.

Feedback &amp; Contributing

Please use the issue tracker to let me know about any bugs or feature requests, or alternatively make a pull request.

For general questions about Hugo, there is a Hugo discussion forum.

License

Copyright 2016 George Cushen.

Released under the MIT license.

</description>
    </item>

  </channel>
</rss>