text:
package processor

import (
	"fmt"
	"image"
	"image/png"
	"os"
	"path"
	"strings"

	"github.com/mrcook/smstilemap/assembly"
	"github.com/mrcook/smstilemap/cmd/smstilemap/processor/internal/tiler"
	"github.com/mrcook/smstilemap/sms"
)

type Processor struct {
	pngInputFilename string
	outputDirectory  string
	baseFilename     string

	image image.Image
	sega  sms.SMS
}

func New(srcFilename, outputDir string) *Processor {
	return &Processor{
		pngInputFilename: srcFilename,
		outputDirectory:  outputDirectory(outputDir, srcFilename),
		baseFilename:     baseFilename(srcFilename),
	}
}

func (p *Processor) CreateOutputDirectory() error {
	if err := os.MkdirAll(p.outputDirectory, 0755); err != nil {
		return fmt.Errorf("error creating output directory: %w", err)
	}
	return nil
}

func (p *Processor) PngToSMS() error {
	if err := p.readPNG(p.pngInputFilename); err != nil {
		return fmt.Errorf("PNG input file error: %w", err)
	}
	if err := p.imageToSMS(); err != nil {
		return fmt.Errorf("PNG to SMS data error: %w", err)
	}
	return nil
}

func (p *Processor) ToAssembly() error {
	var sb strings.Builder

	sb.WriteString(assembly.Tilemap(p.sega.TilemapData()).String())
	sb.WriteString("\n")
	sb.WriteString(assembly.Palettes(p.sega.PaletteData()).String())
	sb.WriteString("\n")
	sb.WriteString(assembly.Tiles(p.sega.TileData()).String())

	f, err := os.Create(path.Join(p.outputDirectory, p.baseFilename+".asm"))
	if err != nil {
		return fmt.Errorf("error creating ASM file: %w", err)
	}
	defer f.Close()

	if _, err := f.WriteString(sb.String()); err != nil {
		return fmt.Errorf("error writing SMS assembly to file: %w", err)
	}
	return nil
}

// SaveTilesToImage converts the SMS tiles to an image
func (p *Processor) SaveTilesToImage() error {
	dstImage, err := p.smsTilesToImage()
	if err != nil {
		return err
	}
	return p.saveImageToFilename(dstImage, p.pngTilesFilename())
}

// SaveTilemapToImage converts the SMS tilemap data back to a normal image
func (p *Processor) SaveTilemapToImage() error {
	dstImage, err := p.smsToImage()
	if err != nil {
		return err
	}
	return p.saveImageToFilename(dstImage, p.pngFilename())
}

func (p *Processor) readPNG(filename string) error {
	f, err := os.Open(filename)
	if err != nil {
		return err
	}
	defer f.Close()

	p.image, err = png.Decode(f)
	if err != nil {
		return err
	}

	return nil
}

// convert the PNG image to an SMS representation
func (p *Processor) imageToSMS() error {
	// validate image is suitable for conversion to the SMS
	if p.image == nil {
		return fmt.Errorf("source image is nil")
	} else if p.image.Bounds().Dx() > sms.ScreenWidth || p.image.Bounds().Dy() > sms.ScreenHeight {
		return fmt.Errorf("image size too big for SMS screen (%d x %d)", sms.ScreenWidth, sms.ScreenHeight)
	}
	tiled := tiler.FromImage(p.image, 8)

	// check there are too many colours for the SMS
	if tiled.ColourCount() > sms.MaxColourCount {
		return fmt.Errorf("too many unique colours for SMS (max: %d)", sms.MaxColourCount)
	}

	// add the image tiles to the SMS
	for i := 0; i < tiled.TileCount(); i++ {
		tile, _ := tiled.GetTile(i)
		if err := p.convertAndAddTileToSms(tile); err != nil {
			return err
		}
	}
	return nil
}

func (p *Processor) convertAndAddTileToSms(tile *tiler.Tile) error {
	if err := p.addTileColoursToSmsPalette(tile); err != nil {
		return fmt.Errorf("error adding colours to SMS palette: %w", err)
	}

	smsTile, err := p.convertToSmsTile(tile)
	if err != nil {
		return fmt.Errorf("error converting image tile to SMS tile: %w", err)
	}

	tid, err := p.sega.AddTile(smsTile)
	if err != nil {
		return err
	}

	if err := p.addTileToTilemap(tile, tid); err != nil {
		return fmt.Errorf("error adding tile to SMS tilemap: %w", err)
	}

	return nil
}

// make sure all tile colours are added to the SMS palette
func (p *Processor) addTileColoursToSmsPalette(tile *tiler.Tile) error {
	for _, c := range tile.Palette() {
		r, g, b, _ := c.RGBA()
		colour := sms.FromNearestMatchRGB(uint8(r), uint8(g), uint8(b))
		if _, err := p.sega.AddPaletteColour(colour); err != nil {
			return err
		}
	}
	return nil
}

// convert to an SMS tile, matching colours to SMS palette colours
func (p *Processor) convertToSmsTile(tile *tiler.Tile) (*sms.Tile, error) {
	smsTile := sms.Tile{}

	for row := 0; row < tile.Size(); row++ {
		for col := 0; col < tile.Size(); col++ {
			// get the colour for the current pixel
			c, err := tile.OrientationAt(row, col, tile.Orientation())
			if err != nil {
				return nil, err
			}
			r, g, b, _ := c.RGBA()
			colour := sms.FromNearestMatchRGB(uint8(r), uint8(g), uint8(b))

			// find the palette ID for the colour
			pid, err := p.sega.PaletteIdForColour(colour)
			if err != nil {
				return nil, err
			}

			// sets the pixel colour using the palette ID
			if err := smsTile.SetPaletteIdAt(row, col, pid); err != nil {
				return nil, err
			}
		}
	}

	return &smsTile, nil
}

// update tilemap with the tile+duplicate locations
func (p *Processor) addTileToTilemap(tile *tiler.Tile, tileId uint16) error {
	word := sms.Word{TileNumber: tileId}

	// the tile
	word.SetFlippedStateFromOrientation(p.smsOrientation(tile.Orientation()))
	if err := p.sega.AddTilemapEntryAt(tile.Row(), tile.Col(), word); err != nil {
		return err
	}

	// and its duplicates
	for did := 0; did < tile.DuplicateCount(); did++ {
		inf, err := tile.GetDuplicateInfo(did)
		if err != nil {
			return err
		}

		word.SetFlippedStateFromOrientation(p.smsOrientation(inf.Orientation()))
		if err := p.sega.AddTilemapEntryAt(inf.Row(), inf.Col(), word); err != nil {
			return err
		}
	}
	return nil
}

// converts a tiler orientation to an SMS orientation.
func (p *Processor) smsOrientation(or tiler.Orientation) sms.Orientation {
	switch or {
	case tiler.OrientationFlippedV:
		return sms.OrientationFlippedV
	case tiler.OrientationFlippedH:
		return sms.OrientationFlippedH
	case tiler.OrientationFlippedVH:
		return sms.OrientationFlippedVH
	default:
		return sms.OrientationNormal
	}
}

// smsTilesToImage converts the SMS tile data to a new NRGBA image.
func (p *Processor) smsTilesToImage() (image.Image, error) {
	tileSize := 8
	height, width := p.tileSheetSizeInPixels(tileSize)

	img := image.NewNRGBA(image.Rectangle{
		Min: image.Point{X: 0, Y: 0},
		Max: image.Point{X: width, Y: height},
	})

	errorMessage := "drawing tile to image"
	rowOffset := 0
	colOffset := 0

	for i := uint16(0); i < sms.MaxTileCount; i++ {
		tile, err := p.sega.TileAt(i)
		if err != nil {
			return nil, err
		} else if tile == nil {
			break
		}

		// draw the tile to the image
		for y := 0; y < tileSize; y++ {
			for x := 0; x < tileSize; x++ {
				paletteId, err := tile.PaletteIdAt(y, x)
				if err != nil {
					return nil, fmt.Errorf("%s: %w", errorMessage, err)
				}
				colour, err := p.sega.PaletteColour(paletteId)
				if err != nil {
					return nil, fmt.Errorf("%s: %w", errorMessage, err)
				}
				img.Set(colOffset+x, rowOffset+y, colour)
			}
		}

		// next column
		colOffset += tileSize

		// next row?
		if colOffset >= width {
			colOffset = 0
			rowOffset += tileSize
		}
	}

	return img, nil
}

func (p *Processor) tileSheetSizeInPixels(tileSize int) (int, int) {
	height := sms.MaxTileCount / p.sega.WidthInTiles()
	if sms.MaxTileCount%p.sega.WidthInTiles() > 0 {
		height += 1 // make up missing row
	}
	height *= tileSize // set height in pixels
	width := p.sega.WidthInPixels()

	return height, width
}

// smsToImage converts the SMS data to a new NRGBA image, with the tile layout
// as defined in the tilemap name table.
func (p *Processor) smsToImage() (image.Image, error) {
	img := image.NewNRGBA(image.Rectangle{
		Min: image.Point{X: 0, Y: 0},
		Max: image.Point{X: p.sega.WidthInPixels(), Y: p.sega.HeightInPixels()},
	})

	for row := 0; row < p.sega.HeightInTiles(); row++ {
		for col := 0; col < p.sega.WidthInTiles(); col++ {
			if err := p.drawTilemapEntry(img, row, col); err != nil {
				return nil, err
			}
		}
	}

	return img, nil
}

// draws a tile to the image using the tilemap entry data
func (p *Processor) drawTilemapEntry(img *image.NRGBA, row, col int) error {
	tile, err := p.smsTileForTilemapEntryAt(row, col)
	if err != nil {
		return err
	}

	errorMessage := "drawing tile to image"
	pxOffsetY := row * tile.Size()
	pxOffsetX := col * tile.Size()

	for y := 0; y < tile.Size(); y++ {
		for x := 0; x < tile.Size(); x++ {
			paletteId, err := tile.PaletteIdAt(y, x)
			if err != nil {
				return fmt.Errorf("%s: %w", errorMessage, err)
			}
			colour, err := p.sega.PaletteColour(paletteId)
			if err != nil {
				return fmt.Errorf("%s: %w", errorMessage, err)
			}
			img.Set(pxOffsetX+x, pxOffsetY+y, colour)
		}
	}
	return nil
}

// returns the mapped tile for the given row/col.
func (p *Processor) smsTileForTilemapEntryAt(row, col int) (*sms.Tile, error) {
	processingErrorMessage := "converting tilemap tile to correctly flipped tile"

	mapEntry, err := p.sega.TilemapEntryAt(row, col)
	if err != nil {
		return nil, fmt.Errorf("%s: %w", processingErrorMessage, err)
	}
	tile, err := p.sega.TileAt(mapEntry.TileNumber)
	if err != nil {
		return nil, fmt.Errorf("%s: %w", processingErrorMessage, err)
	}

	// set the correct orientation based on tilemap entry.
	return tile.AsTilemap(mapEntry), nil
}

func (p *Processor) saveImageToFilename(i image.Image, filename string) error {
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()

	err = png.Encode(f, i)
	if err != nil {
		return err
	}
	return nil
}

func (p *Processor) pngFilename() string {
	return path.Join(p.outputDirectory, p.baseFilename+"-generated.png")
}

func (p *Processor) pngTilesFilename() string {
	return path.Join(p.outputDirectory, p.baseFilename+"-tiles.png")
}

func outputDirectory(dir, inFilename string) string {
	if len(dir) > 0 {
		return dir
	}
	return path.Dir(inFilename)
}

func baseFilename(input string) string {
	file := path.Base(input)
	return strings.ReplaceAll(file, path.Ext(file), "")
}

repository: mrcook/smstilemap

repo_name: mrcook/smstilemap


text:
package typeconv

import (
	"reflect"
	"testing"
)

func Test_convertInterfaceSliceToTypedSlice(t *testing.T) {
	type args struct {
		interfaceSlice []interface{}
	}
	tests := []struct {
		name    string
		args    args
		want    interface{}
		wantErr bool
	}{
		{
			name: "int slice",
			args: args{
				interfaceSlice: []interface{}{
					1,
					2,
					3,
				},
			},
			want: []int{1, 2, 3},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := ConvertInterfaceSliceToTypedSlice(tt.args.interfaceSlice)
			if (err != nil) != tt.wantErr {
				t.Errorf("convertInterfaceSliceToTypedSlice() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("convertInterfaceSliceToTypedSlice() = %v, want %v", got, tt.want)
			}
		})
	}
}

license: MIT

repository: brunotm/go-tensorflow

license_type: permissive

repo_name: brunotm/go-tensorflow

branch_name: refs/heads/master

extension: go


text:
@article{Miele_2011,
 author = {Miele, Solange Ana Belen and Garavaglia, Mat{\'{\i}}as Javier and Belaich, Mariano Nicol{\'{a}}s and Ghiringhelli, Pablo Daniel},
 title = {Baculovirus: Molecular Insights on Their Diversity and Conservation},
 journal = {International Journal of Evolutionary Biology},
 publisher = {Hindawi Limited},
 year = {2011},
 month = {apr},
 volume = {2011},
 pages = {1--15},
 url = {https://doi.org/10.4061%2F2011%2F379424},
 doi = {10.4061/2011/379424}
}

extension: bib


text:
@Article{valdez2018priming,
  title = {Priming and anchoring effects in visualization},
  author = {Andre Calero Valdez and Martina Ziefle and Michael Sedlmair},
  pages = {584--594},
  year = {2018},
  journal = {IEEE Transactions on Visualization \& Computer Graphics},
  number = {1},
  publisher = {IEEE},
  date = {2018-01-01},
}

repository: Sumidu/academic-kickstart

repo_name: Sumidu/academic-kickstart


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

package blog

import (
	"context"

	"bitbucket.com/iamjollof/server/models"
	"bitbucket.com/iamjollof/server/plugins"
	"bitbucket.com/iamjollof/server/protos/blog"
	"github.com/golang/protobuf/ptypes"
	"github.com/jinzhu/copier"
)

//Server - Struct holding Blogs
type Server struct {
	blog.BlogServer
}

//GetAllBlogs - Lists all the blogs
//Todo: Handle errors
//sudo service postgresql start
//export PATH="$PATH:$(go env GOPATH)/bin"
func (*Server) GetAllBlogs(ctx context.Context, r *blog.GetAllBlogsRequest) (*blog.GetAllBlogsResponse, error) {
	blogs, count, err := models.GetAllBlogs(r.GetPageNumber(), r.GetResultPerPage())
	if err != nil {
		plugins.LogError("API Service", "Error at: GetAllBlogs", err)
		return &blog.GetAllBlogsResponse{}, err
	}
	var arrayOfBlogs []*blog.GetBlogResponse
	copier.Copy(&arrayOfBlogs, blogs)
	for i := 0; i < len(arrayOfBlogs); i++ {
		createdAt, err := ptypes.TimestampProto(blogs[i].CreatedAt)
		if err != nil {
			plugins.LogError("API Service", "Error at: GetAllBlogs - time.Time to Proto TimeStamp conversion err", err)
			return &blog.GetAllBlogsResponse{}, err
		}
		arrayOfBlogs[i].CreatedAt = createdAt
	}
	return &blog.GetAllBlogsResponse{
		PageNumber:    r.GetPageNumber(),
		ResultPerPage: r.GetResultPerPage(),
		TotalCount:    count,
		Blogs:         arrayOfBlogs,
	}, nil
}

//CreateBlog - Create new Blog
func (*Server) CreateBlog(ctx context.Context, r *blog.CreateBlogRequest) (*blog.CreateBlogResponse, error) {
	var newBlog models.Blog
	copier.Copy(&newBlog, r)
	createdBlog, err := models.CreateBlog(&newBlog)
	if err != nil {
		plugins.LogError("API Service", "Error at: CreateBlog", err)
		return &blog.CreateBlogResponse{}, err
	}
	var test blog.CreateBlogResponse
	copier.Copy(&test, createdBlog)
	return &test, nil
}

//GetBlog - Get Blog by ID
func (*Server) GetBlog(ctx context.Context, r *blog.GetBlogRequest) (*blog.GetBlogResponse, error) {
	singleBlog, err := models.GetBlog(r.ID)
	if err != nil {
		plugins.LogError("API Service", "Error at: GetBlog", err)
		return &blog.GetBlogResponse{}, err
	}
	var test blog.GetBlogResponse
	copier.Copy(&test, singleBlog)
	createdAt, err := ptypes.TimestampProto(singleBlog.CreatedAt)
	if err != nil {
		plugins.LogError("API Service", "Error at: GetBlog - time.Time to Proto TimeStamp conversion err", err)
		return &blog.GetBlogResponse{}, err
	}
	test.CreatedAt = createdAt
	return &test, nil
}

//UpdateBlog - Update Blog by ID
func (*Server) UpdateBlog(ctx context.Context, r *blog.UpdateBlogRequest) (*blog.UpdateBlogResponse, error) {
	var newBlog models.Blog
	copier.Copy(&newBlog, r)
	if err := models.UpdateBlog(newBlog, r.ID); err != nil {
		plugins.LogError("API Service", "Error at: UpdateBlog", err)
		return &blog.UpdateBlogResponse{}, err
	}
	return &blog.UpdateBlogResponse{
		Message: "Blog Updated successfully",
	}, nil
}

//DeleteBlog - Delete Blog by ID
func (*Server) DeleteBlog(ctx context.Context, r *blog.DeleteBlogRequest) (*blog.DeleteBlogResponse, error) {
	if err := models.DeleteBlog(r.ID); err != nil {
		plugins.LogError("API Service", "Error at: DeleteBlog", err)
		return &blog.DeleteBlogResponse{}, err
	}
	return &blog.DeleteBlogResponse{}, nil
}

repository: paingha/iamjollof-api

repo_name: paingha/iamjollof-api


text:
$(document).ready(function() {
	"use strict";

// ------------- Pre-loader--------------

// makes sure the whole site is loaded
$(window).load(function() {
    // will first fade out the loading animation
    $(".preloader").fadeOut();
    //then background color will fade out slowly
    $("#faceoff").delay(200).fadeOut("slow");
});

// ------------- Owl Carousel--------------

$("#screenshot-slider").owlCarousel({
    navigation : false,
    slideSpeed : 300,
    pagination: false,
    autoPlay: 5000,
    items : 3,
  });

//-------Appearence of navigation----------

  $('header .nav').onePageNav({
    scrollThreshold: 0.2, // Adjust if Navigation highlights too early or too late
    scrollOffset: 45 //Height of Navigation Bar
  });

  $(window).scroll(function() {

	//if (winWidth > 767) {
	  var $scrollHeight = $(window).scrollTop();
	  if ($scrollHeight > 600) {
		$('#header').slideDown(400);
	  } else{
		$('#header').slideUp(400);
	  }
	//}

	 //header version 2

	  var $scrollHeight2 = $(window).scrollTop();
	  if ($scrollHeight2 > 120) {
		$('#header2 nav').addClass('addbg').slideDown(400);
	  } else {
		$('#header2 nav').removeClass('addbg');
	  }

	  //got o top
	  if ($(this).scrollTop() > 200) {
			$('#go-to-top a').fadeIn('slow');
		  } else {
			$('#go-to-top a').fadeOut('slow');
	  }
  });

 //-------scroll to top---------

 $('#go-to-top a').click(function(){
	$("html,body").animate({ scrollTop: 0 }, 750);
	return false;
  });

  //----------- Scroll to Next Section ----------

  $('.next-arrow a').click(function() {
    $('html,body').animate({scrollTop:$('#more_feature').offset().top - 90}, 750);
  });

//--------------- For navigation--------------------

	$('.navbar-collapse ul li a').click(function() {
		$('.navbar-toggle:visible').click();
	});

//--------------- SmoothSroll--------------------
var scrollAnimationTime = 1200,
    scrollAnimation = 'easeInOutExpo';
$('a.scrollto').bind('click.smoothscroll', function (event) {
    event.preventDefault();
    var target = this.hash;
    $('html, body').stop().animate({
        'scrollTop': $(target).offset().top
    }, scrollAnimationTime, scrollAnimation, function () {
        window.location.hash = target;
    });
});

// Animate and WOW Animation
    var wow = new WOW(
        {
            //offset: 50,
            mobile: false
           // live: true
        }
    );
    wow.init();

// ------------- Magnific Image Popup--------------

    $('.screenshot-popup').magnificPopup({
      type:'image',
      closeBtnInside:true,
      // Delay in milliseconds before popup is removed
      removalDelay: 300,

      // Class that is added to popup wrapper and background
      // make it unique to apply your CSS animations just to this exact popup
      mainClass: 'mfp-fade',
      gallery: {
          enabled: true, // set to true to enable gallery

          preload: [0,2], // read about this option in next Lazy-loading section

          navigateByImgClick: true,

          //arrowMarkup: '<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>', // markup of an arrow button

          closeMarkup: '<button title="%title%" class="mfp-close">×</button>',

          tPrev: 'Previous (Left arrow key)', // title for left button
          tNext: 'Next (Right arrow key)', // title for right button
          //tCounter: '%curr% of %total%' // markup of counter
        }
   });

// ------------- Magnific Image Popup--------------

 	$('.play').magnificPopup({
	  disableOn: 700,
	  type: 'iframe',
	  mainClass: 'mfp-fade',
	  removalDelay: 160,
	  preloader: false,
	  fixedContentPos: false
	});

// ------------- FAQs Icon--------------
	var $active = $('#accordion .panel-collapse.in').prev().addClass('active');
	$active.find('a').append('');
	$('#accordion .panel-heading').not($active).find('a').prepend('');
	$('#accordion').on('show.bs.collapse', function (e)
	{
		$('#accordion .panel-heading.active').removeClass('active').find('.glyphicon').toggleClass('glyphicon-plus glyphicon-minus');
		$(e.target).prev().addClass('active').find('.glyphicon').toggleClass('glyphicon-plus glyphicon-minus');
	});
	$('#accordion').on('hide.bs.collapse', function (e)
	{
		$(e.target).prev().removeClass('active').find('.glyphicon').removeClass('glyphicon-minus').addClass('glyphicon-plus');
	});

//-----------Text Slider on Banner-----------

   $('.flex_text').flexslider({
        animation: "slide",
		selector: ".slides li",
		controlNav: false,
		directionNav: false,
		slideshowSpeed: 4000,
		touch: true,
		useCSS: false,
		direction: "vertical",
        before: function(slider){
		 var height = $('.flex_text').find('.flex-viewport').innerHeight();
		 $('.flex_text').find('li').css({ height: height + 'px' });
        }
    });

 // --------------Newsletter-----------------------

	$(".newsletter-signup").ajaxChimp({
		callback: mailchimpResponse,
		url: "http://codepassenger.us10.list-manage.com/subscribe/post?u=6b2e008d85f125cf2eb2b40e9&id=6083876991" // Replace your mailchimp post url inside double quote "".
	});

	function mailchimpResponse(resp) {
		 if(resp.result === 'success') {

			$('.newsletter-success').html(resp.msg).fadeIn().delay(3000).fadeOut();

		} else if(resp.result === 'error') {
			$('.newsletter-error').html(resp.msg).fadeIn().delay(3000).fadeOut();
		}
	};

  // --------------Contact Form Ajax request-----------------------

    $('.contact_form').on('submit', function(event){
    event.preventDefault();

    // $this = $(this);

    var data = {
      name: $('#name').val(),
      phone: $('#phone').val(),
      email: $('#contact_email').val(),
      // subject: $('#subject').val(),
      message: $('#message').val()
    };

    $.ajax({
      type: "POST",
      url: "email.php",
      data: data,
      success: function(msg){
	     $('.contact-success').fadeIn().delay(3000).fadeOut();
      }
    });
  });

/* =================================
===  IE10 ON WINDOWS 8 FIX      ====
=================================== */
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
  var msViewportStyle = document.createElement('style')
  msViewportStyle.appendChild(
    document.createTextNode(
      '@-ms-viewport{width:auto!important}'
    )
  )
  document.querySelector('head').appendChild(msViewportStyle)
}

});

gha_language: CSS

extension: js