text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 5(3-6): 335 (1951)

#### Original name
Hyalomeliolina costaricensis F. Stevens

### Remarks
null


text:
.preview .runner-btnright,
.preview  .runner-wrapper .runner-btnright,
.preview  .runner-wrapper .runner-wrapper .runner-btnright
{
clip:rect(auto auto auto 490px);
}
.preview .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-menutab > *.runner-cc a,
.preview  .runner-wrapper .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-menutab > *.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-menutab > *.runner-cc a
{
color: #404061
}
.preview .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-menutab.active > *.runner-cc a,
.preview  .runner-wrapper .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-menutab.active > *.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-menutab.active > *.runner-cc a
{
color: #404061
}
.preview .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-menutab.current > *.runner-cc a,
.preview  .runner-wrapper .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-menutab.current > *.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-menutab.current > *.runner-cc a
{
color: #404061
}
.preview .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-btnright,
.preview  .runner-wrapper .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-btnright,
.preview  .runner-wrapper .runner-wrapper .runner-s-hmenu .runner-row .runner-b-hmenu .runner-hmenu   .runner-btnright
{
clip:rect(auto auto auto 490px);
}
.preview .runner-s-grid > table > * > tr.style1.runner-row > td.runner-cc a,
.preview .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row > td.runner-cc a
{
color: #404040
}
.preview .runner-s-grid > table > * > tr.style1.runner-toprow > th.runner-cc a,
.preview .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-toprow > th.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-toprow > th.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-toprow > th.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-toprow > th.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-toprow > th.runner-cc a
{
color: #FFFFFF
}
.preview .runner-s-grid > table > * > tr.style1.runner-row.footer > td.runner-cc a,
.preview .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.footer > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row.footer > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.footer > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row.footer > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.footer > td.runner-cc a
{
color: #FFFFFF
}
.preview .runner-s-grid > table > * > tr.style1.runner-row > td.runner-cc a,
.preview .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row > td.runner-cc a
{
color: #404040
}
.preview .runner-s-grid > table > * > tr.style1.runner-row.interlaced > td.runner-cc a,
.preview .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.interlaced > td.runner-cc a,
.preview .runner-s-grid > table > * > tr > td.runner-cg > table > * > .runner-row > td.runner-cc a.alt,
.preview  .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row.interlaced > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.interlaced > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > .runner-row > td.runner-cc a.alt,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row.interlaced > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.interlaced > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > .runner-row > td.runner-cc a.alt
{
color: #404040
}
.preview .runner-s-grid > table > * > tr.style1.runner-row.hovered > td.runner-cc a,
.preview .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.hovered > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row.hovered > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.hovered > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row.hovered > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.hovered > td.runner-cc a
{
color: #404040
}
.preview .runner-s-grid > table > * > tr.style1.runner-row.hovered.interlaced > td.runner-cc a,
.preview .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.hovered.interlaced > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row.hovered.interlaced > td.runner-cc a,
.preview  .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.hovered.interlaced > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr.style1.runner-row.hovered.interlaced > td.runner-cc a,
.preview  .runner-wrapper .runner-wrapper .runner-s-grid > table > * > tr > td.runner-cg > table > * > tr.style1.runner-row.hovered.interlaced > td.runner-cc a
{
color: #404040
}

redpajama_set_name: RedPajamaGithub


text:
namespace Kvasir {
//Basic Timer Counter 6
}


text:
def event_key(event):
    try:
        return event['start']['dateTime']
    except KeyError:
        return event['start']['date']


text:
namespace MediaToolkit
{
    using System;
    using System.Configuration;
    using System.Diagnostics;
    using System.IO;
    using System.IO.Compression;
    using System.Reflection;
    using System.Threading;

    using MediaToolkit.Properties;
    using MediaToolkit.Util;

    public class EngineBase : IDisposable
    {
        private bool isDisposed;

        /// <summary>   Used for locking the FFmpeg process to one thread. </summary>
        private const string LockName = "MediaToolkit.Engine.LockName";

        private const string DefaultFFmpegFilePath = @"/MediaToolkit/ffmpeg.exe";

        /// <summary>   Full pathname of the FFmpeg file. </summary>
        protected readonly string FFmpegFilePath;

        /// <summary>   The Mutex. </summary>
        protected readonly Mutex Mutex;

        /// <summary>   The ffmpeg process. </summary>
        protected Process FFmpegProcess;

         protected EngineBase()
            : this(ConfigurationManager.AppSettings["mediaToolkit.ffmpeg.path"])
        {
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///     <para> Initializes FFmpeg.exe; Ensuring that there is a copy</para>
        ///     <para> in the clients temp folder & isn't in use by another process.</para>
        /// </summary>
        protected EngineBase(string ffMpegPath)
        {
            this.Mutex = new Mutex(false, LockName);
            this.isDisposed = false;

            if (ffMpegPath.IsNullOrWhiteSpace())
            {
                ffMpegPath = DefaultFFmpegFilePath;
            }

            this.FFmpegFilePath = ffMpegPath;

            this.EnsureDirectoryExists ();
            this.EnsureFFmpegFileExists();
            this.EnsureFFmpegIsNotUsed ();
        }

        private void EnsureFFmpegIsNotUsed()
        {
            try
            {
                this.Mutex.WaitOne();
                Process.GetProcessesByName(Resources.FFmpegProcessName)
                       .ForEach(process =>
                       {
                           process.Kill();
                           process.WaitForExit();
                       });
            }
            finally
            {
                this.Mutex.ReleaseMutex();
            }
        }

        private void EnsureDirectoryExists()
        {
            string directory = Path.GetDirectoryName(this.FFmpegFilePath) ?? Directory.GetCurrentDirectory(); ;

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
        }

        private void EnsureFFmpegFileExists()
        {
            if (!File.Exists(this.FFmpegFilePath))
            {
                UnpackFFmpegExecutable(this.FFmpegFilePath);
            }
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Unpack ffmpeg executable. </summary>
        /// <exception cref="Exception">    Thrown when an exception error condition occurs. </exception>
        private static void UnpackFFmpegExecutable(string path)
        {
            Stream compressedFFmpegStream = Assembly.GetExecutingAssembly()
                                                    .GetManifestResourceStream(Resources.FFmpegManifestResourceName);

            if (compressedFFmpegStream == null)
            {
                throw new Exception(Resources.Exceptions_Null_FFmpeg_Gzip_Stream);
            }

            using (FileStream fileStream = new FileStream(path, FileMode.Create))
            using (GZipStream compressedStream = new GZipStream(compressedFFmpegStream, CompressionMode.Decompress))
            {
                compressedStream.CopyTo(fileStream);
            }
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///     Performs application-defined tasks associated with freeing, releasing, or resetting
        ///     unmanaged resources.
        /// </summary>
        /// <remarks>   Aydin Aydin, 30/03/2015. </remarks>
        public virtual void Dispose()
        {
            this.Dispose(true);
        }

        private void Dispose(bool disposing)
        {
            if (!disposing || this.isDisposed)
            {
                return;
            }

            if(FFmpegProcess != null)
            {
                this.FFmpegProcess.Dispose();
            }
            this.FFmpegProcess = null;
            this.isDisposed = true;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset= "utf-8">
    <title>Amari Ashwood</title>
    <link rel="stylesheet" href="css/normalize.css">
    <link href='https://fonts.googleapis.com/css?family=OswaldDroid+Serif:400,400italic,700italic,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="css/responsive.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Amari Ashwood

Reality changes when it is closely observed.

Portfolio

About

Contact

Stuff ONNNNEEEE is the loneliest number you could ever dooooooooo.

Stuff Stuff Two is the lonliest number since the number onnnneeee. Except not if you're with an awesome partner in mischief and you solemnly swear you are up to no good.

Stuff Stuff Stuff Three! is the luckiest of numbers. Haven't you noticed the triangles that occur in the universe? They're everywhere, man. Every.where.

Stuff Stuff Stuff Stuff FOUR! the perfect number for a very small orgy.

Stuff Stuff Stuff Stuff Stuff FIVE! just enough to make someone always feel left out. like they should. Why are they here anyways?

© 2016 Amari Ashwood.


text:
from flask import Response, request
from flask_restful import Resource
from bson.json_util import dumps
import re

class SlideSet(Resource):
	def __init__(self, db, config):
		"""initialize SlideSet resource

		Args:
			db: mongo db connection
			config: application configurations
			opt: deep zoom configurations

		Returns:
			None
		"""
		self.db = db
		self.config = config
		self.slides = self.db[self.config["db_collection"]]

	def get(self, id):
		"""
        Get slides for slide set
        ---
        tags:
          - Slide Set
        parameters:
          - in: path
            name: id
            description: slide set name - EMORY_BIOBANK
            type: string
          - in: query
            name: start
            description: start position for the set of slides to return
            type: integer
          - in: query
            name: count
            description: number of slides to return relative to the starting position
            type: integer
        responses:
          200:
            description: Returns set of slides
        """

		start = request.args.get('start', 0)
		count = request.args.get('count', 20)
		filters = {"set": str(id), "bad": {"$exists": False}}
		tmp = []

		for key in request.args:
			val = request.args.get(key)
			m = re.match(r"(.*)\[(.*)\]", key)
			if m:
				op = m.group(1)
				field = m.group(2)

				if op == "filter" and val != '':
					filters[field] = { "$regex": str(".*" + val + ".*"), "$options": "i" }
				if op == "facets" and val != '':
					val = "true"
					filters["facets."+field] = True if val == "true" else val

		images = self.slides.find(filters, {'scanProperties': False}).skip(int(start)).limit(int(count))
		for image in images:
			image["id"] = str(image["_id"])
			tmp.append(image)

		data = dumps({"data": tmp, "pos": int(start), "total_count": self.slides.find(filters).count()})
		return Response(data, status=200, mimetype='application/json')


text:
import mechanize
import requests
import os
import argparse

import csv

# Sample for getting Spring Semester of 2015:
# python scraper.py -c true -ft 1 -fy 2015 -lt 1 -ly 2015

# 1 is Spring, 4 is Summer, 7 is Fall
parser = argparse.ArgumentParser()
#if we want to do conversion
parser.add_argument('-c', '--convert', nargs='+', type=bool)
#ft is the first term, in this case spring
parser.add_argument('-ft', '--firstterm', nargs='+', type=int)
#lt is the last term, begin with spring(1)
parser.add_argument('-lt', '--lastterm', nargs='+', type=int)

#first years, are years that we will start terms with. For example:
#if fyears are 2013, 2014, and last years are 2014, 2015 we will download 2013-2014 and 2014-2015
parser.add_argument('-fy', '--firstyears', nargs='+', type=int)
parser.add_argument('-ly', '--lastyears', nargs='+', type=int)
arguments = parser.parse_args()

#this is the boiler plate for the browser
br = mechanize.Browser()
br.set_handle_robots(False)   # ignore robots
br.set_handle_refresh(False)  # can sometimes hang without this
br.addheaders = [('User-agent', 'Firefox')]

#this sets the department we want, in this case we use entire campus
fcqdpt = 'BD : Entire Campus ## BD'
# fcqdpt = 'AS : MATHEMATICS -- MATH'
# 1 is Spring, 4 is Summer, 7 is Fall
#fterm is the first term, in this case spring
#lterm is the last term, spring as well.
#ftrm = '1'
ftrm = str(arguments.firstterm[0])
#ltrm = '1'
ltrm = str(arguments.lastterm[0])

fileFrmt = 'XLS'

#years that we are interested in, from first years to last years
fyrs = map(str,arguments.firstyears)
lyrs = map(str,arguments.lastyears)
#fyrs = ['2013', '2012', '2011', '2010', '2009', '2008', '2007']
#lyrs = ['2014', '2013', '2012', '2011', '2010', '2009', '2008']
# The instructor group grp1=[*ALL, TTT, OTH, T_O, TA]
grp1 = 'ALL'

def convert_csv(input_file,output_file):
    with open(input_file, 'rb') as f:
        with open(output_file,'w') as f1:
            # f.next() # skip header line
            first = True
            for line in f:
                if first:
                    # This is the custom header line that our import task wants.
                    f1.write('yearterm,subject,crse,sec,onlinefcq,bdcontinedcrse,instructor_last,instructor_first,formsrequested,formsreturned,percentage_passed,courseoverall,courseoverall_sd,instructoroverall,instructoroverall_sd,hoursperwkinclclass,priorinterest,instreffective,availability,challenge,howmuchlearned,instrrespect,course_title,courseoverall_old,courseoverall_sd_old,instroverall_old,instroverall_sd_old,r_fair,r_access,workload,r_divstu,r_diviss,r_presnt,r_explan,r_assign,r_motiv,r_learn,r_complx,campus,college,asdiv,level,fcqdept,instr_group,i_num\n')
                    # f1.write('yearterm,subject,crse,sec,onlineFCQ,bd_continuing_education,instructor_last,instructor_first,formsrequested,formsreturned,percentage_passed,course_overall,course_overall_SD,instructoroverall,instructoroverall_SD,total_hours,prior_interest,effectiveness,availability,challenge,amount_learned,respect,course_title,courseOverall_old,courseOverall_SD_old,instrOverall_old,instrOverall_SD_old,r_Fair,r_Access,workload,r_Divstu,r_Diviss,r_Presnt,r_Explan,r_Assign,r_Motiv,r_Learn,r_Complx,campus,college,aSdiv,level,fcqdept,instr_group,i_Num\n')
                    first = False
                else:
                    # Replace double quotes with null, relace spaced commas with normal commas, replace the big comma chunk with a bigger one for our header.
                    line = line.replace('"','').replace(',,,,,,',',,,,,,,,,,,,,,,',1).replace(', ',',',1).replace(', ',' ')
                    f1.write(line)
    print("DONE")

for i in range (0,len(fyrs)):

    #the url for the fcq site
    url = 'https://fcq.colorado.edu/UCBdata.htm'

    #we open the url
    response = br.open(url)

    control = br.select_form("frmFCQ")

    #go through all of the form options so we can change them
    for control in br.form.controls:
        #this will show us all of our default value for the fields. See page options for the output of the FCQ page as of 1/3/15
        #print "DEFAULT: type=%s, name=%s value=%s" % (control.type, control.name, br[control.name])

        if (control.name == 'fcqdpt'):
            br[control.name] = [fcqdpt]
            print "CHANGE fcqdpt type=%s, name=%s value=%s" % (control.type, control.name, br[control.name])

        elif (control.name == 'ftrm'):
            br[control.name] = [ftrm]
            print "CHANGE first term type=%s, name=%s value=%s" % (control.type, control.name, br[control.name])

        elif (control.name == 'ltrm'):
            br[control.name] = [ltrm]
            print "CHANGE last term type=%s, name=%s value=%s" % (control.type, control.name, br[control.name])

        elif (control.name == 'fileFrmt'):
            br[control.name] = [fileFrmt]
            print "CHANGE fileFrmt type=%s, name=%s value=%s" % (control.type, control.name, br[control.name])

        elif (control.name == 'fyr'):
            br[control.name] = [fyrs[i]]
            print "CHANGE first year type=%s, name=%s value=%s" % (control.type, control.name, br[control.name])

        elif (control.name == 'lyr'):
            br[control.name] = [lyrs[i]]
            print "CHANGE last year type=%s, name=%s value=%s" % (control.type, control.name, br[control.name])

    response = br.submit()

    if 'Currently, Excel files with FCQ results are limited to 50,000 rows.' in response.read():
        print('CAUTION REQUEST HAS MORE THAN 50,000 LINES!')

    for link in br.links():
        if (link.text == 'Click here'):
            print(link.url)
            original = link.url
            #need to split because output link is: javascript:popup('/fcqtemp/BD010395426.xls','BD010395426','750','550','yes','yes')
            split = original.replace("\'","").split(',')
            #get this BD010395426
            proper_link = "https://fcq.colorado.edu/fcqtemp/{xcel}.xls".format(xcel=split[1])
            print proper_link

    r = requests.get(proper_link)
    file_name = "{ftrm}-{fyr}_{ltrm}-{lyr}".format(ftrm=ftrm,fyr=fyrs[i],ltrm=ltrm,lyr=lyrs[i])
    xcel_path = "../raw/{file_name}.xls".format(file_name=file_name)

    output = open(xcel_path,'wb')
    output.write(r.content)
    output.close()

    csv_path = "../fcq/{file_name}.csv".format(file_name=file_name)
    convert_command = "ssconvert -S {path} temp.csv".format(path=xcel_path)
    rm_command = "rm temp.csv.*"

    if arguments.convert:
        os.system(convert_command)
        convert_csv('temp.csv.1',csv_path)
        os.system(rm_command)

        print "Converted!"
    else:
        print "Did not convert!"

    convert_csv

print("SUCCESS!")


text:
Website maintenance

The website is currently under maintenance. Please return later.


text:
- [ ] Convert AUTHORS to markdown
- [ ] Update INSTALL file / convert to markdown
- [x] Fix copyright in each file
- [ ] Add code format config


text:
importScripts("/resources/testharness.js");
importScripts("/html/canvas/resources/canvas-tests.js");

var t = async_test("");
var t_pass = t.done.bind(t);
var t_fail = t.step_func(function(reason) {
    throw reason;
});
t.step(function() {

var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');

_assertSame(ctx.textAlign, 'start', "ctx.textAlign", "'start'");
t.done();

});
done();


text:
<?php namespace Gitlab\Tests\Api;

use Gitlab\Api\AbstractApi;
use Gitlab\Api\MergeRequests;

class MergeRequestsTest extends TestCase
{
    /**
     * @test
     */
    public function shouldGetAll()
    {
        $expectedArray = $this->getMultipleMergeRequestsData();

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('get')
            ->with('projects/1/merge_requests', array())
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->all(1));
    }

    /**
     * @test
     */
    public function shouldGetAllWithParams()
    {
        $expectedArray = $this->getMultipleMergeRequestsData();

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('get')
            ->with('projects/1/merge_requests', ['page' => 2, 'per_page' => 5, 'order_by' => 'updated_at', 'sort' => 'desc'])
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->all(1, ['page' => 2, 'per_page' => 5, 'order_by' => 'updated_at', 'sort' => 'desc']));
    }

    /**
     * @test
     */
    public function shouldShowMergeRequest()
    {
        $expectedArray = array('id' => 2, 'name' => 'A merge request');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('get')
            ->with('projects/1/merge_requests/2')
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->show(1, 2));
    }

    /**
     * @test
     */
    public function shouldCreateMergeRequestWithoutOptionalParams()
    {
        $expectedArray = array('id' => 3, 'title' => 'Merge Request');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('post')
            ->with('projects/1/merge_requests', array(
                'title' => 'Merge Request',
                'target_branch' => 'master',
                'source_branch' => 'develop',
                'description' => null,
                'assignee_id' => null,
                'target_project_id' => null
            ))
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->create(1, 'develop', 'master', 'Merge Request'));
    }

    /**
     * @test
     */
    public function shouldCreateMergeRequestWithOptionalParams()
    {
        $expectedArray = array('id' => 3, 'title' => 'Merge Request');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('post')
            ->with('projects/1/merge_requests', array(
                'title' => 'Merge Request',
                'target_branch' => 'master',
                'source_branch' => 'develop',
                'description' => 'Some changes',
                'assignee_id' => 6,
                'target_project_id' => 20
            ))
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->create(1, 'develop', 'master', 'Merge Request', 6, 20, 'Some changes'));
    }

    /**
     * @test
     */
    public function shouldUpdateMergeRequest()
    {
        $expectedArray = array('id' => 2, 'title' => 'Updated title');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('put')
            ->with('projects/1/merge_requests/2', array('title' => 'Updated title', 'description' => 'No so many changes now', 'state_event' => 'close'))
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->update(1, 2, array(
            'title' => 'Updated title',
            'description' => 'No so many changes now',
            'state_event' => 'close'
        )));
    }

    /**
     * @test
     */
    public function shouldMergeMergeRequest()
    {
        $expectedArray = array('id' => 2, 'title' => 'Updated title');

        $api = $this->getApiMock();
        $api->expects($this->exactly(2))
            ->method('put')
            ->with('projects/1/merge_requests/2/merge', array('merge_commit_message' => 'Accepted'))
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->merge(1, 2, 'Accepted'));
        $this->assertEquals($expectedArray, $api->merge(1, 2, array('merge_commit_message' => 'Accepted')));
    }

    /**
     * @test
     */
    public function shouldGetMergeRequestNotes()
    {
        $expectedArray = array(
            array('id' => 1, 'body' => 'A comment'),
            array('id' => 2, 'body' => 'Another comment')
        );

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('get')
            ->with('projects/1/merge_requests/2/notes')
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->showNotes(1, 2));
    }

    /**
     * @test
     */
    public function shouldGetMergeRequestChanges()
    {
        $expectedArray = array('id' => 1, 'title' => 'A merge request');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('get')
            ->with('projects/1/merge_requests/2/changes')
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->changes(1, 2));
    }

    /**
     * @test
     */
    public function shouldGetIssuesClosedByMergeRequest()
    {
        $expectedArray = array('id' => 1, 'title' => 'A merge request');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('get')
            ->with('projects/1/merge_requests/2/closes_issues')
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->closesIssues(1, 2));
    }

    /**
     * @test
     */
    public function shouldGetMergeRequestByIid()
    {
        $expectedArray = array('id' => 1, 'title' => 'A merge request');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('get')
            ->with('projects/1/merge_requests', array('iids' => [2]))
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->all(1, ['iids' => [2]]));
    }

    /**
     * @test
     */
    public function shouldApproveMergeRequest()
    {
        $expectedArray = array('id' => 1, 'title' => 'Approvals API');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('post')
            ->with('projects/1/merge_requests/2/approve')
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->approve(1, 2));
    }

    /**
     * @test
     */
    public function shouldUnApproveMergeRequest()
    {
        $expectedArray = array('id' => 1, 'title' => 'Approvals API');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('post')
            ->with('projects/1/merge_requests/2/unapprove')
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->unapprove(1, 2));
    }

    /**
     * @test
     */
    public function shouldGetMergeRequestApprovals()
    {
        $expectedArray = array('id' => 1, 'title' => 'Approvals API');

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('get')
            ->with('projects/1/merge_requests', array('iids' => [2]))
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->all(1, ['iids' => [2]]));
    }

    /**
     * @test
     */
    public function shouldGetMergeRequestAwardEmoji()
    {
        $expectedArray = array(
            array('id' => 1, 'name' => 'sparkles'),
            array('id' => 2, 'name' => 'heart_eyes'),
        );

        $api = $this->getApiMock();
        $api->expects($this->once())
            ->method('get')
            ->with('projects/1/merge_requests/2/award_emoji')
            ->will($this->returnValue($expectedArray))
        ;

        $this->assertEquals($expectedArray, $api->awardEmoji(1, 2));
    }

    protected function getMultipleMergeRequestsData()
    {
        return array(
            array('id' => 1, 'title' => 'A merge request'),
            array('id' => 2, 'title' => 'Another merge request')
        );
    }

    protected function getApiClass()
    {
        return 'Gitlab\Api\MergeRequests';
    }
}


text:
A base configuration and starter project for a simple JavaScript library / Component

##Getting Started

####Clone this repository
Setup a new directory and update the origin
```javascript
git clone git@github.com:bnorton/lib.js.git {{name}}.js
```

Open this project in a text editor

####Search the project for things to replace
1. Rename `{{name}}` to the new library name
1. Rename `{{username}}` with yours on GitHub and CircleCI respectively
1. Rename `{{full name}}` with your name and company name (if any)

####Set the git remote to be the new remote
```javascript
cd {{name}}.js
git remote set-url origin git@github.com:{{username}}/{{name}}.js.git
```

####Add and Install dependencies
Add any libraries / dependencies that you know of then
```bash
$ npm install -g browserify
$ npm install -g uglify
$ npm install
```

####Add tests
```bash
$ make test
```

####Add implementations
```bash
$ make test
```

####Build you first browserified / minified versions and publish
```bash
$ make
$ git commit -am "[Release] Version x.y.z"
$ git tag -a 0.9.0 -m "[Release] Version x.y.z" -m "Other words of wisdom and what has changed"
$ npm publish
```

#### Add this project to CircleCI
Enable the build status at the top of the README.lib.md doc

------------------------

####Replace this document with the real deal and `#win`
```bash
$ mv README.lib.md README.md
```


text:
from os.path import join, dirname, abspath
import unittest
from datetime import datetime
from lanyon.app import Site

FIXTURE_DIR = join(dirname(abspath(__file__)), 'fixtures', 'default_headers')
SETTINGS = {'input_dir': '/default_headers'}
site = Site(SETTINGS)

class DefaultHeaderTests(unittest.TestCase):
    """Tests for the default headers"""

    def test_values(self):
        """Test that the returned headers are valid."""
        input_filename = join(SETTINGS['input_dir'], 'foobar.rst')
        result = site._get_default_headers(input_filename)
        expected = {
            'status': 'live',
            'template': 'default.html',
            'title': 'Foobar',
            'url': 'default',
            'slug': 'foobar'
        }
        for key in expected:
            self.assertEquals(expected[key], result[key])
        self.assert_(isinstance(result['date'], datetime))

class SlugDefaultHeaderTests(unittest.TestCase):
    """Tests for the slug header default"""

    def test_filename_as_slug(self):
        """Check that the filename is used as the slug."""
        input_filename = join(SETTINGS['input_dir'], 'foobar.rst')
        expected = 'foobar'
        result = site._get_default_headers(input_filename)
        self.assertEquals(expected, result['slug'])

    def test_dirname_as_slug(self):
        """
        Check that the directory name is used as the slug if
        the file is named "index.*".
        """
        input_filename = join(SETTINGS['input_dir'], 'bar', 'index.rst')
        expected = 'bar'
        result = site._get_default_headers(input_filename)
        self.assertEquals(expected, result['slug'])

    def test_index_as_slug(self):
        """
        Check that the filename is used as the slug if the file
        is named "index.*" but is located in the root input dir.
        """
        input_filename = join(SETTINGS['input_dir'], 'index.rst')
        expected = 'index'
        result = site._get_default_headers(input_filename)
        self.assertEquals(expected, result['slug'])

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


text:
package org.dyfaces;

public enum FacesParam {
	AJAX("javax.faces.partial.ajax"), RENDER("javax.faces.partial.render"),
	EXECUTE("javax.faces.partial.execute"), SOURCE("javax.faces.source"),
	EVENT("javax.faces.behavior.event");

	private String name;

	private FacesParam(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.jacpfx.api.componentLayout</title>
<meta name="date" content="2015-07-23">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.jacpfx.api.componentLayout

Interface Summary

Interface
Description

BaseLayout<C>

Defines a bean containing the defined tool bars and the main menu

PerspectiveLayoutInterface<M,B>

Defines layout of a perspective and the container for included editors and
 views (target component); for use in perspective handle method.

WorkbenchLayout<C>

Defines the base layout of a workbench and the application.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
package org.kuali.rice.kns.web.comparator;

import org.displaytag.model.Cell;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class CellComparatorHelperTest {

    @Test public void testExtractFromHref() {

        String href = "needle";

        Cell cell = new Cell(href);

        assertEquals(CellComparatorHelper.getSanitizedStaticValue(cell), "needle");

    }

    @Test public void testExtractFromHrefAndRemoveNbsp() {

        String href = "needle ";

        Cell cell = new Cell(href);

        assertEquals(CellComparatorHelper.getSanitizedStaticValue(cell), "needle");

    }

    @Test public void testRemoveNbsp() {

        String bad = "needle ";

        Cell cell = new Cell(bad);

        assertEquals(CellComparatorHelper.getSanitizedStaticValue(cell), "needle");

    }

    @Test public void testLeaveSimpleValueAlone() {

        String good = "needle";
        Cell cell = new Cell(good);
        assertEquals(CellComparatorHelper.getSanitizedStaticValue(cell), "needle");

    }

    @Test public void testMessyHref() {

        String href = "needle ";

        Cell cell = new Cell(href);

        assertEquals(CellComparatorHelper.getSanitizedStaticValue(cell), "needle");

    }

}


text:
module Gitlab
  class AwardEmoji
    CATEGORIES = {
      objects: "Objects",
      travel: "Travel",
      symbols: "Symbols",
      nature: "Nature",
      people: "People",
      activity: "Activity",
      flags: "Flags",
      food: "Food"
    }.with_indifferent_access

    def self.normalize_emoji_name(name)
      aliases[name] || name
    end

    def self.emoji_by_category
      unless @emoji_by_category
        @emoji_by_category = Hash.new { |h, key| h[key] = [] }

        emojis.each do |emoji_name, data|
          data["name"] = emoji_name

          # Skip Fitzpatrick(tone) modifiers
          next if data["category"] == "modifier"

          category = data["category"]

          @emoji_by_category[category] << data
        end

        @emoji_by_category = @emoji_by_category.sort.to_h
      end

      @emoji_by_category
    end

    def self.emojis
      @emojis ||=
        begin
          json_path = File.join(Rails.root, 'fixtures', 'emojis', 'index.json' )
          JSON.parse(File.read(json_path))
        end
    end

    def self.aliases
      @aliases ||=
        begin
          json_path = File.join(Rails.root, 'fixtures', 'emojis', 'aliases.json')
          JSON.parse(File.read(json_path))
        end
    end

    # Returns an Array of Emoji names and their asset URLs.
    def self.urls
      @urls ||= begin
                  path = File.join(Rails.root, 'fixtures', 'emojis', 'digests.json')
                  # Construct the full asset path ourselves because
                  # ActionView::Helpers::AssetUrlHelper.asset_url is slow for hundreds
                  # of entries since it has to do a lot of extra work (e.g. regexps).
                  prefix = Gitlab::Application.config.assets.prefix
                  digest = Gitlab::Application.config.assets.digest
                  base =
                    if defined?(Gitlab::Application.config.relative_url_root) && Gitlab::Application.config.relative_url_root
                      Gitlab::Application.config.relative_url_root
                    else
                      ''
                    end

                  JSON.parse(File.read(path)).map do |hash|
                    if digest
                      fname = "#{hash['unicode']}-#{hash['digest']}"
                    else
                      fname = hash['unicode']
                    end

                    { name: hash['name'], path: File.join(base, prefix, "#{fname}.png") }
                  end
                end
    end
  end
end


text:
package io.spine.server.entity.rejection;

import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.Any;
import io.spine.annotation.GeneratedMixin;
import io.spine.base.RejectionMessage;
import io.spine.protobuf.AnyPacker;

/**
 * Interface common for standard rejections which is used during routing.
 */
@Immutable
@GeneratedMixin
public interface StandardRejection extends RejectionMessage {

    /**
     * Obtains the packed version of ID of the entity which caused the rejection.
     */
    Any getEntityId();

    /**
     * Obtains the ID of the entity from the {@linkplain #getEntityId() packed form}.
     */
    default Object entityId() {
        Object result = AnyPacker.unpack(getEntityId());
        return result;
    }
}


text:
namespace PrintSwitch
{
    partial class MainForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.iconContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.printersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
            this.label1 = new System.Windows.Forms.Label();
            this.iconContextMenuStrip.SuspendLayout();
            this.SuspendLayout();
            //
            // iconContextMenuStrip
            //
            this.iconContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.printersToolStripMenuItem,
            this.exitToolStripMenuItem});
            this.iconContextMenuStrip.Name = "iconContextMenuStrip";
            this.iconContextMenuStrip.Size = new System.Drawing.Size(153, 70);
            //
            // printersToolStripMenuItem
            //
            this.printersToolStripMenuItem.Name = "printersToolStripMenuItem";
            this.printersToolStripMenuItem.Size = new System.Drawing.Size(116, 22);
            this.printersToolStripMenuItem.Text = "&Printers";
            //
            // exitToolStripMenuItem
            //
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.exitToolStripMenuItem.Text = "E&xit";
            this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
            //
            // notifyIcon1
            //
            this.notifyIcon1.ContextMenuStrip = this.iconContextMenuStrip;
            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
            this.notifyIcon1.Text = "PrintSwitch";
            this.notifyIcon1.Visible = true;
            this.notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.ContextMenuStrip = this.iconContextMenuStrip;
            this.label1.Location = new System.Drawing.Point(12, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(201, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "There\'s nothing to see here. Move along.";
            //
            // MainForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(223, 33);
            this.ContextMenuStrip = this.iconContextMenuStrip;
            this.Controls.Add(this.label1);
            this.Name = "MainForm";
            this.ShowInTaskbar = false;
            this.Text = "PrintSwitch";
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.Resize += new System.EventHandler(this.MainForm_Resize);
            this.iconContextMenuStrip.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ContextMenuStrip iconContextMenuStrip;
        private System.Windows.Forms.NotifyIcon notifyIcon1;
        private System.Windows.Forms.ToolStripMenuItem printersToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
        private System.Windows.Forms.Label label1;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Asterina rehmii Henn.

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:orientation="horizontal"
    android:background="@color/colorTest1">

    <android.inputmethodservice.KeyboardView
        android:id="@android:id/keyboardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:popupLayout="@layout/keyboard_popup_layout"
        android:keyBackground="@color/colorTest2"
        android:background="@color/colorPrimary"/>
    <ImageButton android:id="@android:id/closeButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorTest3"
        android:layout_gravity="center"
        android:layout_marginStart="6dp"
        android:layout_marginLeft="6dp"
        android:layout_marginEnd="6dp"
        android:layout_marginRight="6dp"
        android:clickable="true"
        android:src="@drawable/ic_clear_white_24dp"/>
</LinearLayout>


text:
package com.github.shynixn.astraledit.bukkit.logic.business.command;

import com.github.shynixn.astraledit.api.bukkit.business.command.PlayerCommand;
import com.github.shynixn.astraledit.api.bukkit.business.entity.Selection;
import com.github.shynixn.astraledit.bukkit.AstralEditPlugin;
import com.github.shynixn.astraledit.bukkit.Permission;
import com.github.shynixn.astraledit.bukkit.logic.business.Operation;
import com.github.shynixn.astraledit.bukkit.logic.business.OperationType;
import com.github.shynixn.astraledit.bukkit.logic.business.SelectionHolder;
import com.github.shynixn.astraledit.bukkit.logic.business.SelectionManager;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

public class PlaceCommand implements PlayerCommand {
    private final Plugin plugin;
    private final SelectionManager manager;

    /**
     * Creates a new instance of the PlaceCommand which depends on a Plugin and a SelectionManager.
     *
     * @param plugin the Plugin
     * @param manager the SelectionManager
     */
    public PlaceCommand(Plugin plugin, SelectionManager manager) {
        this.plugin = plugin;
        this.manager = manager;
    }

    /**
     * Executes the PlaceCommand, if the arguments match and the Player has a valid ({@link Permission#PLACE}) Permission.
     *
     * @param player executing the command.
     * @param args   arguments.
     * @return True if this command was executed. False if the arguments do not match.
     */
    @Override
    public boolean onPlayerExecuteCommand(Player player, String[] args) {
        if (args.length != 1 || !args[0].equalsIgnoreCase("place") || !Permission.PLACE.hasPermission(player)) {
            return false;
        }

        this.plugin.getServer().getScheduler().runTaskAsynchronously(this.plugin, () -> {
            final Selection selection = this.manager.getSelection(player);
            if (selection == null) {
                player.sendMessage(AstralEditPlugin.PREFIX_ERROR + "You don't have a valid render.");
            } else {
                player.sendMessage(AstralEditPlugin.PREFIX_SUCCESS + "Placing render ...");
                final Operation operation = new Operation(OperationType.PLACE);
                operation.setOperationData(((SelectionHolder) selection).getTemporaryStorage());
                selection.placeBlocks(() -> {
                    this.manager.addOperation(player, operation);
                    player.sendMessage(AstralEditPlugin.PREFIX_SUCCESS + "Finished placing render.");
                });
            }
        });

        return true;
    }
}


text:
#include <inviwo/core/util/systemcapabilities.h>
#include <inviwo/core/util/formatconversion.h>
#include <inviwo/core/util/logcentral.h>
#ifdef IVW_SIGAR
#include <sigar/include/sigar.h>
#endif

namespace inviwo {

#define SystemInfoNotFound(message) { LogInfoCustom("SystemInfo",message << " Info could not be retrieved"); }

SystemCapabilities::SystemCapabilities() {
#ifdef IVW_SIGAR
    sigar_open(&sigar_);
#endif
}

SystemCapabilities::~SystemCapabilities() {
#ifdef IVW_SIGAR
    sigar_close(sigar_);
#endif
}

bool SystemCapabilities::canAllocate(glm::u64 dataSize, glm::u8 percentageOfAvailableMemory) {
    return getAvailableMemory()*percentageOfAvailableMemory/100 >= dataSize;
}

uvec3 SystemCapabilities::calculateOptimalBrickSize(uvec3 dimensions, size_t formatSizeInBytes, glm::u8 percentageOfAvailableMemory) {
    uvec3 currentBrickDimensions = dimensions;

    while (!canAllocate(getMemorySizeInBytes(currentBrickDimensions, formatSizeInBytes), percentageOfAvailableMemory)) {
        int theMaxDim = (currentBrickDimensions.x > currentBrickDimensions.y ? (currentBrickDimensions.x > currentBrickDimensions.z ? 0 : 2) :
                         (currentBrickDimensions.y > currentBrickDimensions.z ? 1 : 2));

        if (currentBrickDimensions[theMaxDim] % 2 != 0)
            currentBrickDimensions[theMaxDim]++; //Make the dim we are dividing even

        currentBrickDimensions[theMaxDim] /= 2;
    }

    return currentBrickDimensions;
}

void SystemCapabilities::retrieveStaticInfo() {
    successOSInfo_ = lookupOSInfo();
}

void SystemCapabilities::retrieveDynamicInfo() {
    successCPUInfo_ = lookupCPUInfo();
    successMemoryInfo_ = lookupMemoryInfo();
    successDiskInfo_ = lookupDiskInfo();
    successProcessMemoryInfo_ = lookupProcessMemoryInfo();
}

bool SystemCapabilities::lookupOSInfo() {
#ifdef IVW_SIGAR
    int status;
    sigar_sys_info_t systeminfo;
    status = sigar_sys_info_get(sigar_, &systeminfo);
    bool SUCCESS = (status == SIGAR_OK);

    if (SUCCESS) {
        infoOS_.description = std::string(systeminfo.description);

        if (strcmp(systeminfo.arch, "x86") == 0)
            infoOS_.platform = 32;
        else
            infoOS_.platform = 64;
    }

    return SUCCESS;
#else
    return false;
#endif

}

bool SystemCapabilities::lookupCPUInfo() {
    infoCPUs_.clear();
#ifdef IVW_SIGAR
    int status;
    sigar_cpu_info_list_t cpulinfolist;
    status = sigar_cpu_info_list_get(sigar_, &cpulinfolist);
    bool SUCCESS = (status == SIGAR_OK);

    if (SUCCESS) {
        infoCPUs_.resize(cpulinfolist.number);

        for (unsigned long i=0; i<cpulinfolist.number; i++) {
            sigar_cpu_info_t cpu_info = cpulinfolist.data[i];
            infoCPUs_[i].vendor = std::string(cpu_info.vendor);
            infoCPUs_[i].model = std::string(cpu_info.model);
            infoCPUs_[i].mhz = static_cast<glm::u64>(cpu_info.mhz);
        }
    }

    sigar_cpu_info_list_destroy(sigar_, &cpulinfolist);
    return SUCCESS;
#else
    return false;
#endif
}

bool SystemCapabilities::lookupMemoryInfo() {
#ifdef IVW_SIGAR
    int status;
    sigar_mem_t meminfo;
    status = sigar_mem_get(sigar_, &meminfo);
    bool SUCCESS = (status == SIGAR_OK);

    if (SUCCESS) {
        infoRAM_.total = MEGABYTES_TO_BYTES(static_cast<glm::u64>(meminfo.ram));
        infoRAM_.available = static_cast<glm::u64>(meminfo.free);
    }

    return SUCCESS;
#else
    return false;
#endif
}

bool SystemCapabilities::lookupDiskInfo() {
    infoDisks_.clear();
#ifdef IVW_SIGAR
    int status;
    sigar_file_system_list_t diskinfolist;
    sigar_file_system_usage_t diskusageinfo;
    status = sigar_file_system_list_get(sigar_, &diskinfolist);
    bool SUCCESS = (status == SIGAR_OK);

    if (SUCCESS) {
        for (unsigned long i=0; i<diskinfolist.number; i++) {
            sigar_file_system_t disk_info = diskinfolist.data[i];
            status = sigar_file_system_usage_get(sigar_, disk_info.dir_name, &diskusageinfo);

            if (status == SIGAR_OK) {
                DiskInfo currentDiskInfo;
                currentDiskInfo.diskType = std::string(disk_info.type_name);
                currentDiskInfo.diskType[0] = static_cast<char>(toupper(currentDiskInfo.diskType[0]));

                if (currentDiskInfo.diskType == "Local") {
                    currentDiskInfo.diskName = std::string(disk_info.dev_name);
                    currentDiskInfo.total = KILOBYTES_TO_BYTES(static_cast<glm::u64>(diskusageinfo.total));
                    currentDiskInfo.free = KILOBYTES_TO_BYTES(static_cast<glm::u64>(diskusageinfo.free));
                    infoDisks_.push_back(currentDiskInfo);
                }
            }
        }
    }

    sigar_file_system_list_destroy(sigar_, &diskinfolist);
    return SUCCESS;
#else
    return false;
#endif
}

bool SystemCapabilities::lookupProcessMemoryInfo() {
#ifdef IVW_SIGAR
    int status;
    sigar_proc_mem_t meminfo;
    status = sigar_proc_mem_get(sigar_, sigar_pid_get(sigar_), &meminfo);
    bool SUCCESS = (status == SIGAR_OK);

    if (SUCCESS) {
        infoProcRAM_.residentMem = static_cast<glm::u64>(meminfo.resident);
        infoProcRAM_.sharedMem = static_cast<glm::u64>(meminfo.share);
        infoProcRAM_.virtualMem = static_cast<glm::u64>(meminfo.size);
    }

    return SUCCESS;
#else
    return false;
#endif
}

void SystemCapabilities::printInfo() {
    retrieveDynamicInfo();

    // Try to retrieve operating system information
    if (successOSInfo_) {
        LogInfoCustom("SystemInfo","OS: " << infoOS_.description << " " << infoOS_.platform << "-bit");
    } else {
        SystemInfoNotFound("OS:");
    }

    // Try to retrieve CPU information
    if (successCPUInfo_) {
        std::string prevCPU = std::string("");
        std::ostringstream cpuStream;
        unsigned long count=0;
        for (unsigned long i=0; i<infoCPUs_.size(); i++){
            cpuStream.str("");
            cpuStream << infoCPUs_[i].vendor << " " << infoCPUs_[i].model;
            if(prevCPU != cpuStream.str()){
                if(!prevCPU.empty()){
                    if(count>0){
                        LogInfoCustom("SystemInfo","CPU " << i+1 << "-" << i+1+count << ": " << prevCPU);
                    }
                    else{
                        LogInfoCustom("SystemInfo","CPU " << i+1 << ": " << prevCPU);
                    }
                }
                prevCPU = cpuStream.str();
                count = 0;
            }
            else{
                count++;
            }
        }
        if(!prevCPU.empty()){
            if(count>0){
                LogInfoCustom("SystemInfo","CPU " << infoCPUs_.size()-count << "-" << infoCPUs_.size() << ": " << prevCPU);
            }
            else{
                LogInfoCustom("SystemInfo","CPU " << infoCPUs_.size() << ": " << prevCPU);
            }
        }
    }
    else
        SystemInfoNotFound("CPU:");

    // Try to retrieve memory information
    if (successMemoryInfo_) {
        LogInfoCustom("SystemInfo", "RAM: Total - " << formatBytesToString(infoRAM_.total)
                                                    << ", Available - "
                                                    << formatBytesToString(infoRAM_.available));
    } else {
        SystemInfoNotFound("RAM:");
    }

    // Try to retrieve Disk information
    if (successDiskInfo_) {
        for (auto& elem : infoDisks_)
            LogInfoCustom("SystemInfo", "Disk: " << elem.diskName << " Total - "
                                                 << formatBytesToString(elem.total) << ", Free - "
                                                 << formatBytesToString(elem.free));
    }
    else
        SystemInfoNotFound("Disk:");

    // Try to retrieve this process memory information
    if (successProcessMemoryInfo_) {
        LogInfoCustom("SystemInfo",
                      "Processor Memory: Resident - "
                          << formatBytesToString(infoProcRAM_.residentMem) << ", Shared - "
                          << formatBytesToString(infoProcRAM_.sharedMem) << ", Virtual - "
                          << formatBytesToString(infoProcRAM_.virtualMem));
    } else {
        SystemInfoNotFound("Processor Memory:");
    }  //*/
}

int SystemCapabilities::numberOfCores() const {
     if (successCPUInfo_) {
        return static_cast<int>(infoCPUs_.size());
     } else {
        return -1;
     }
}

glm::u64 SystemCapabilities::getAvailableMemory() {
    successMemoryInfo_ = lookupMemoryInfo();

    if (successMemoryInfo_)
        return infoRAM_.available;

    return 0;
}

glm::u64 SystemCapabilities::getCurrentResidentMemoryUsage() {
    successProcessMemoryInfo_ = lookupProcessMemoryInfo();

    if (successMemoryInfo_)
        return infoProcRAM_.residentMem;

    return 0;
}

} // namespace


text:
ACCEPTED

#### According to
Interim Register of Marine and Nonmarine Genera

#### Published in
Bull. Fan Mem. Inst. Biol. , 3, 87.

#### Original name
null

### Remarks
null


text:
package tut.heikki.visualrestclient;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class SettingsActivity extends Activity{

	IntentFilter intentFilter;

    private Button btnDevice;
    private Button btnVrest;
    private Button btnAutomaticMetadataUpload;
    private Button btnXMPP;
    private Button btnAddedFiles;

    @Override
    public void onResume(){
    	super.onResume();
    	//---intent filter
    	intentFilter = new IntentFilter();
    	intentFilter.addAction("USER_AUTH");
    	//---register the receiver---
    	registerReceiver(intentReceiver, intentFilter);

        // Check VisualREST authentication parameters
        SharedPreferences prefs = getSharedPreferences("AccountSettings", MODE_PRIVATE);

        if ( prefs.contains("username") && prefs.contains("password"))
        {
	        String username = prefs.getString("username", "");
	        String password = prefs.getString("password", "");

	        Intent intent = new Intent(getBaseContext(), HTTPRequestService.class);
	        Bundle extras = new Bundle();
	        extras.putInt("action", 1); //"authenticateUser"
	        extras.putString("username", username);
	        extras.putString("password", password);

	        intent.putExtras(extras);

	        startService(intent);
        }

        // Check device settings
        SharedPreferences xmppprefs = getSharedPreferences("XMPPSettings", MODE_PRIVATE);
		if ( xmppprefs.contains("devicename") ){
        	ImageView icon = (ImageView) findViewById(R.id.deviceOKIcon);
            icon.setImageResource(R.drawable.online_32);
            btnXMPP.setEnabled(true);
            btnAutomaticMetadataUpload.setEnabled(true);
            btnAddedFiles.setEnabled(true);
		}
		else{
    		ImageView icon = (ImageView) findViewById(R.id.deviceOKIcon);
            icon.setImageResource(R.drawable.offline_32);
            btnXMPP.setEnabled(false);
            btnAutomaticMetadataUpload.setEnabled(false);
            btnAddedFiles.setEnabled(false);
		}

		// Check newFileObserver
        IsNewFileObserverRunning();

        // Check XMPPService
		IsXMPPServiceRunning();

    }

    @Override
    public void onPause(){
    	super.onPause();
    	this.unregisterReceiver(intentReceiver);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);

        btnVrest = (Button) findViewById(R.id.btnVrestSettings);
        btnVrest.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	startActivity(new Intent("tut.heikki.accountsettings"));
            }
        });

        btnDevice = (Button) findViewById(R.id.btnDeviceSettings);
        btnDevice.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	startActivity(new Intent("tut.heikki.devicesettings"));
            }
        });

        btnAutomaticMetadataUpload = (Button) findViewById(R.id.btnAutomaticMetadataUpload);
        btnAutomaticMetadataUpload.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// Change automaticMetadataUpload either on/off
				if( IsNewFileObserverRunning() ){
					// Stop the service
					Intent intent = new Intent(getBaseContext(), NewFileObserverService.class);
					getBaseContext().stopService(intent);
				}
				else{
					// Start the service
					Intent intent = new Intent();
					intent.setClassName("tut.heikki.visualrestclient", "tut.heikki.visualrestclient.NewFileObserverService");
					getBaseContext().startService(intent);
					Toast.makeText(getBaseContext(), "All new photos are automatically added to container program!", Toast.LENGTH_SHORT).show();
				}
				// Update the view
				IsNewFileObserverRunning();

				// Update the widget
                UpdateWidget();
			}
		});

        btnXMPP = (Button) findViewById(R.id.btnXMPPSettings);
        btnXMPP.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// Change automaticMetadataUpload either on/off
				if( IsXMPPServiceRunning() ){
					// Stop the service
					Intent intent = new Intent(getBaseContext(), XMPPService.class);
					getBaseContext().stopService(intent);
				}
				else{
					// Start the service
					Intent intent = new Intent();
					intent.setClassName("tut.heikki.visualrestclient", "tut.heikki.visualrestclient.XMPPService");
					getBaseContext().startService(intent);
					Toast.makeText(getBaseContext(), "XMPP messages can now be received from the server!", Toast.LENGTH_SHORT).show();
				}
				// Update the view
				IsXMPPServiceRunning();

				// Update the widget
				UpdateWidget();

			}
		});

        btnAddedFiles = (Button) findViewById(R.id.btnAddedFiles);
        btnAddedFiles.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent("tut.heikki.containerfiles"));
            }
        });

        SettingsActivity.showTips("showTipSettings",
                "'VisualREST account settings': Save your VisualREST account username and password.\n\n" +
                "'Device settings': Link container program with VisualREST server.\n\n" +
                "'Start automatic metadata upload' Toggle whether to automatically add new photos to container program.\n\n" +
                "'Start XMPP service': Toggle XMPP connection on/off.\n\n" +
                "'Container files': Show photos of container program and allows you to add/manage container photos.",
                this);
    }

    private boolean IsNewFileObserverRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("tut.heikki.visualrestclient.NewFileObserverService".equals(service.service.getClassName())) {
            	// Set the icon
            	ImageView icon = (ImageView) findViewById(R.id.automaticMetadataUploadOKIcon);
                icon.setImageResource(R.drawable.online_32);

                // Set the text
                btnAutomaticMetadataUpload.setText(R.string.stopAutomaticMetadataUpload);

                return true;
            }
        }
        // Set the icon
		ImageView icon = (ImageView) findViewById(R.id.automaticMetadataUploadOKIcon);
        icon.setImageResource(R.drawable.offline_32);

        // Set the text
        btnAutomaticMetadataUpload.setText(R.string.startAutomaticMetadataUpload);

        return false;
    }

    private boolean IsXMPPServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("tut.heikki.visualrestclient.XMPPService".equals(service.service.getClassName())) {
            	// Set the icon
            	ImageView icon = (ImageView) findViewById(R.id.XMPPOKIcon);
                icon.setImageResource(R.drawable.online_32);

                // Set the text
                btnXMPP.setText(R.string.stopXMPPService);

                return true;
            }
        }
		ImageView icon = (ImageView) findViewById(R.id.XMPPOKIcon);
        icon.setImageResource(R.drawable.offline_32);

        // Set the text
        btnXMPP.setText(R.string.startXMPPService);
        return false;
    }

    private void UpdateWidget(){
        ComponentName thisWidget = new ComponentName(getApplicationContext(),
            VrestWidgetProvider.class);
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getBaseContext().getApplicationContext());
        int[] allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget);
        // Build the intent to call the service
        Intent intent = new Intent(getBaseContext().getApplicationContext(),
                UpdateWidgetService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds2);

        // Update the widgets via the service
        getBaseContext().startService(intent);
    }

    private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

        	Bundle extras = intent.getExtras();
        	if (extras != null){

        		String action = intent.getAction();

        		if ( action.equals("USER_AUTH") ){

	  	    	    Boolean success = extras.getBoolean("USER_AUTH");
	  	    	    if (success == true){
	  	                ImageView icon = (ImageView) findViewById(R.id.accountOKIcon);
	  	                icon.setImageResource(R.drawable.online_32);
	  	    	    }
	  	    	    else if( success == false){
	  	  	    		Toast.makeText(getBaseContext(), "Error authenticating user!", Toast.LENGTH_SHORT).show();
	  	  	    		ImageView icon = (ImageView) findViewById(R.id.accountOKIcon);
	  	  	    		icon.setImageResource(R.drawable.offline_32);
	  	    	    }
        		}

        	}

        }
    };

    public static void showTips(final String tipName, String tip, Context context){

        final SharedPreferences prefs = context.getSharedPreferences("AccountSettings", MODE_PRIVATE);

        if( prefs.getBoolean("showTips", true) && prefs.getBoolean(tipName, true) ){

            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.help_dialog);
            TextView t = (TextView) dialog.findViewById(R.id.tvHelp);
            t.setText(tip);
            Button b = (Button) dialog.findViewById(R.id.ok);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    CheckBox c = (CheckBox) dialog.findViewById(R.id.checkNoTips);
                    if( c.isChecked() ){
                        // Do not show tips in the future
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putBoolean("showTips", false);
                        editor.commit();
                    }

                    c = (CheckBox) dialog.findViewById(R.id.checkNoTip);
                    if( c.isChecked() ){
                        // Do not show this tip in the future
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putBoolean(tipName, false);
                        editor.commit();
                    }

                    dialog.cancel();
                }
            });
            dialog.setTitle("Tips");
            dialog.show();
        }

    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.thinkgem.jeesite.mapper.UserTokenMapper" >
  <resultMap id="BaseResultMap" type="com.thinkgem.jeesite.vo.UserToken" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="code" property="code" jdbcType="VARCHAR" />
    <result column="access_token" property="access_token" jdbcType="VARCHAR" />
    <result column="expires_in" property="expires_in" jdbcType="VARCHAR" />
    <result column="refresh_token" property="refresh_token" jdbcType="VARCHAR" />
    <result column="openid" property="openid" jdbcType="VARCHAR" />
    <result column="scope" property="scope" jdbcType="VARCHAR" />
    <result column="in_time" property="inTime" jdbcType="TIMESTAMP" />
    <result column="in_out_time" property="inOutTime" jdbcType="TIMESTAMP" />
  </resultMap>
  <sql id="Example_Where_Clause" >
    <where >
      <foreach collection="oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause" >
    <where >
      <foreach collection="example.oredCriteria" item="criteria" separator="or" >
        <if test="criteria.valid" >
          <trim prefix="(" suffix=")" prefixOverrides="and" >
            <foreach collection="criteria.criteria" item="criterion" >
              <choose >
                <when test="criterion.noValue" >
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue" >
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue" >
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue" >
                  and ${criterion.condition}
                  <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List" >
    id, code, access_token, expires_in, refresh_token, openid, scope, in_time, in_out_time
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.thinkgem.jeesite.vo.UserTokenExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    'true' as QUERYID,
    <include refid="Base_Column_List" />
    from user_token
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null" >
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select
    <include refid="Base_Column_List" />
    from user_token
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from user_token
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.thinkgem.jeesite.vo.UserTokenExample" >
    delete from user_token
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.thinkgem.jeesite.vo.UserToken" >
    insert into user_token (id, code, access_token,
      expires_in, refresh_token, openid,
      scope, in_time, in_out_time
      )
    values (#{id,jdbcType=INTEGER}, #{code,jdbcType=VARCHAR}, #{access_token,jdbcType=VARCHAR},
      #{expires_in,jdbcType=VARCHAR}, #{refresh_token,jdbcType=VARCHAR}, #{openid,jdbcType=VARCHAR},
      #{scope,jdbcType=VARCHAR}, #{inTime,jdbcType=TIMESTAMP}, #{inOutTime,jdbcType=TIMESTAMP}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.thinkgem.jeesite.vo.UserToken" >
    insert into user_token
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="code != null" >
        code,
      </if>
      <if test="access_token != null" >
        access_token,
      </if>
      <if test="expires_in != null" >
        expires_in,
      </if>
      <if test="refresh_token != null" >
        refresh_token,
      </if>
      <if test="openid != null" >
        openid,
      </if>
      <if test="scope != null" >
        scope,
      </if>
      <if test="inTime != null" >
        in_time,
      </if>
      <if test="inOutTime != null" >
        in_out_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="code != null" >
        #{code,jdbcType=VARCHAR},
      </if>
      <if test="access_token != null" >
        #{access_token,jdbcType=VARCHAR},
      </if>
      <if test="expires_in != null" >
        #{expires_in,jdbcType=VARCHAR},
      </if>
      <if test="refresh_token != null" >
        #{refresh_token,jdbcType=VARCHAR},
      </if>
      <if test="openid != null" >
        #{openid,jdbcType=VARCHAR},
      </if>
      <if test="scope != null" >
        #{scope,jdbcType=VARCHAR},
      </if>
      <if test="inTime != null" >
        #{inTime,jdbcType=TIMESTAMP},
      </if>
      <if test="inOutTime != null" >
        #{inOutTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.thinkgem.jeesite.vo.UserTokenExample" resultType="java.lang.Integer" >
    select count(*) from user_token
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update user_token
    <set >
      <if test="record.id != null" >
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.code != null" >
        code = #{record.code,jdbcType=VARCHAR},
      </if>
      <if test="record.access_token != null" >
        access_token = #{record.access_token,jdbcType=VARCHAR},
      </if>
      <if test="record.expires_in != null" >
        expires_in = #{record.expires_in,jdbcType=VARCHAR},
      </if>
      <if test="record.refresh_token != null" >
        refresh_token = #{record.refresh_token,jdbcType=VARCHAR},
      </if>
      <if test="record.openid != null" >
        openid = #{record.openid,jdbcType=VARCHAR},
      </if>
      <if test="record.scope != null" >
        scope = #{record.scope,jdbcType=VARCHAR},
      </if>
      <if test="record.inTime != null" >
        in_time = #{record.inTime,jdbcType=TIMESTAMP},
      </if>
      <if test="record.inOutTime != null" >
        in_out_time = #{record.inOutTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update user_token
    set id = #{record.id,jdbcType=INTEGER},
      code = #{record.code,jdbcType=VARCHAR},
      access_token = #{record.access_token,jdbcType=VARCHAR},
      expires_in = #{record.expires_in,jdbcType=VARCHAR},
      refresh_token = #{record.refresh_token,jdbcType=VARCHAR},
      openid = #{record.openid,jdbcType=VARCHAR},
      scope = #{record.scope,jdbcType=VARCHAR},
      in_time = #{record.inTime,jdbcType=TIMESTAMP},
      in_out_time = #{record.inOutTime,jdbcType=TIMESTAMP}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.thinkgem.jeesite.vo.UserToken" >
    update user_token
    <set >
      <if test="code != null" >
        code = #{code,jdbcType=VARCHAR},
      </if>
      <if test="access_token != null" >
        access_token = #{access_token,jdbcType=VARCHAR},
      </if>
      <if test="expires_in != null" >
        expires_in = #{expires_in,jdbcType=VARCHAR},
      </if>
      <if test="refresh_token != null" >
        refresh_token = #{refresh_token,jdbcType=VARCHAR},
      </if>
      <if test="openid != null" >
        openid = #{openid,jdbcType=VARCHAR},
      </if>
      <if test="scope != null" >
        scope = #{scope,jdbcType=VARCHAR},
      </if>
      <if test="inTime != null" >
        in_time = #{inTime,jdbcType=TIMESTAMP},
      </if>
      <if test="inOutTime != null" >
        in_out_time = #{inOutTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.thinkgem.jeesite.vo.UserToken" >
    update user_token
    set code = #{code,jdbcType=VARCHAR},
      access_token = #{access_token,jdbcType=VARCHAR},
      expires_in = #{expires_in,jdbcType=VARCHAR},
      refresh_token = #{refresh_token,jdbcType=VARCHAR},
      openid = #{openid,jdbcType=VARCHAR},
      scope = #{scope,jdbcType=VARCHAR},
      in_time = #{inTime,jdbcType=TIMESTAMP},
      in_out_time = #{inOutTime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>


text:
from OpenSSL import crypto
import datetime
from django_ca.models import Certificate, CertificateAuthority
import datetime

def create_key():
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA,2048)
    return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)

def create_csr(csr,key):
    san_list = []
    for san in csr['san']:
        san_list.append("DNS:%s" %san)
    pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
    req = crypto.X509Req()
    req.set_pubkey(pkey)
    req.set_version(2)
    req.add_extensions([crypto.X509Extension(b"subjectAltName", False, bytes(", ".join(san_list), 'utf-8')),
                        crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE')])
    subj = req.get_subject()
    subj.CN = csr['CN']
    subj.C = csr['C']
    subj.ST = csr['S']
    subj.L = csr['L']
    subj.O = "TheVPN"
    req.sign(pkey, "sha256")
    return crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)

def sign_csr(csr,ca_cn,attrib,algorithm='sha512',expires=1825):
    ca = CertificateAuthority.objects.get(cn=ca_cn)
    # TODO: Check to see if the certificate already exists, and if so, is it the same user? Revoke the old one?
    cert = Certificate(ca=ca, csr=csr)
    expiry = datetime.datetime.now() + datetime.timedelta(expires)
    cert.x509 = Certificate.objects.init(
            ca=ca, csr=csr, algorithm=algorithm, expires=expiry, subject={'CN': attrib.get('CN'), },
            subjectAltName=attrib['san'])
    cert.save()
    return cert.pub

def create_cert(cn, c, s, l, san, ca_cn='routers.ca.thevpn.co.uk'):
    key = create_key()
    attrib = {'CN': cn, 'C': c, 'S': s, 'L': l, 'san': san}
    csr = create_csr(csr=attrib, key=key)
    cert = sign_csr(csr, ca_cn, attrib)
    return key, cert


text:
echo "Making the javascript cry (Minifying)."
for f in js/*.js
do
    npm run minify -- "$f" --out-file "$f"
done


text:
namespace Umbraco.Cms.ManagementApi.ViewModels.Tree;

public class DocumentTreeItemViewModel : ContentTreeItemViewModel
{
    public bool IsProtected { get; set; }

    public bool IsPublished { get; set; }

    public bool IsEdited { get; set; }
}


text:
using UnityEngine;
using System.Collections;

public class GlobalObject : MonoBehaviour {

	public static GlobalObject sInstance;
	public static string HIGH_SCORE_STAGE1 = "high_score_stage1";
	public static string HIGH_SCORE_STAGE2 = "high_score_stage2";
	public static string HIGH_SCORE_STAGE3 = "high_score_stage3";
	public static string HIGH_SCORE_STAGE4 = "high_score_stage4";

	public static bool isCreardStage1;
	public static bool isCreardStage2;
	public static bool isCreardStage3;
	public static bool isCreardStage4;
	public static int PlayingStageNumber = 0;

	private GlobalObject(){
		isCreardStage1 = false;
     	isCreardStage2 = false;
     	isCreardStage3 = false;
     	isCreardStage4 = false;
	}
}


text:
var couchbase = require("couchbase");
var fs = require('fs');
var so1 = require("./so.json");
var so2 = require("./so2.json");
var cso = require("./cso.json");

// Connect to Couchbase Server

var cluster = new couchbase.Cluster('127.0.0.1:8091');
var bucket = cluster.openBucket('serviceobjects', function(err) {
  if (err) {
    throw err;
  }
  bucket.upsert(fs.readFileSync("./SO.id","utf8").replace(/(\r\n|\n|\r)/gm,""), JSON.stringify(so1), function(err, result) {
    if (err) {
      throw err;
    }
      console.log(result);
  });
  bucket.upsert(fs.readFileSync("./SO2.id","utf8").replace(/(\r\n|\n|\r)/gm,""), JSON.stringify(so2), function(err, result) {
    if (err) {
      throw err;
    }

      console.log(result);
  });
  bucket.upsert(fs.readFileSync("./CSO.id","utf8").replace(/(\r\n|\n|\r)/gm,""), JSON.stringify(cso), function(err, result) {
    if (err) {
      throw err;
    }
      console.log(result);
      process.exit();
  });
});


text:
/*	$NetBSD: machdep.c,v 1.2 1998/09/12 19:15:00 matthias Exp $	*/

/*
 * Copyright (c) 1994 Philip L. Budne.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Philip L. Budne.
 * 4. The name of Philip L. Budne may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * pc532 standalone machdep code
 * Phil Budne, May 10, 1994
 *
 */

#include <sys/types.h>
#include <machine/cpufunc.h>

#include <lib/libsa/stand.h>

#include <pc532/stand/common/samachdep.h>
#include <pc532/stand/common/so.h>

/* XXX TEMP; would like to use code more like hp300 scsi.c */

int
scsialive(ctlr)
	int ctlr;
{
	return 1;		/* controller always alive! */
}

int
scsi_tt_read(ctlr, slave, buf, len, blk, nblk)
	int ctlr, slave;
	void *buf;
	u_int len;
	daddr_t blk;
	u_int nblk;
{
	if (sc_rdwt(DISK_READ, blk, buf, nblk, 1 << slave, 0) == 0)
		return 0;
	return EIO;
}

int
scsi_tt_write(ctlr, slave, buf, len, blk, nblk)
	int ctlr, slave;
	u_char *buf;
	u_int len;
	daddr_t blk;
	u_int nblk;
{
	return EIO;
}

void
machdep_start(entry, howto, loadaddr, ssym, esym)
	char *entry;
	int howto;
	char *loadaddr;
	char *ssym;
	char *esym;
{
	char *load;
	extern u_int opendev;

	load = (char *)((long)entry & 0x00ffff00);

	if (load != loadaddr) {
		memcpy(load, loadaddr, esym - loadaddr);
		ssym += loadaddr - load;
		esym += loadaddr - load;
	}
	entry = (char *)((long)entry & 0xffffff);

	printf("\n");

	run_prog((u_long)howto,		/* r7 */
		 (u_long)opendev,	/* r6 */
		 (u_long)load,		/* r5 */
		 (u_long)esym,		/* r4 */
		 (u_long)3253232532UL,	/* r3 */
		 (u_long)entry);	/* pc */
}

void
_rtt()
{
	/* Use monitor scratch area as stack. */
	lprd(sp, 0x2000);

	/* Copy start of ROM. */
	memcpy((void *)0, (void *)0x10000000, 0x1f00);

	/* Jump into ROM copy. */
	__asm __volatile("jump @0");

	while (1)
		;
}


text:
package com.tlongdev.spicio.network.model;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * Outer layer, Network.
 * Represents a single episode.
 *
 * @author Long
 * @since 2016. 02. 23.
 */
@Root(name = "Episode", strict = false)
public class TvdbEpisode {

    @Element(name = "id")
    private int id;

    @Element(name = "seasonid")
    private int seasonId;

    @Element(name = "EpisodeNumber")
    private int episodeNumber;

    @Element(name = "EpisodeName")
    private String episodeName;

    @Element(name = "FirstAired")
    private String firstAired;

    @Element(name = "GuestStars")
    private String guestStars;

    @Element(name = "Director")
    private String director;

    @Element(name = "Writer")
    private String writers;

    @Element(name = "Overview")
    private String overView;

    @Element(name = "SeasonNumber")
    private int seasonNumber;

    @Element(name = "absolute_number")
    private int absoluteNumber;

    @Element(name = "filename")
    private String fileName;

    @Element(name = "seriesid")
    private int seriesId;

    @Element(name = "IMDB_ID")
    private String imdbId;

    @Element(name = "Rating")
    private double tvdbRating;

    public int getId() {
        return id;
    }

    public int getSeasonId() {
        return seasonId;
    }

    public int getEpisodeNumber() {
        return episodeNumber;
    }

    public String getEpisodeName() {
        return episodeName;
    }

    public String getFirstAired() {
        return firstAired;
    }

    public String getGuestStars() {
        return guestStars;
    }

    public String getDirector() {
        return director;
    }

    public String getWriters() {
        return writers;
    }

    public String getOverView() {
        return overView;
    }

    public int getSeasonNumber() {
        return seasonNumber;
    }

    public int getAbsoluteNumber() {
        return absoluteNumber;
    }

    public String getFileName() {
        return fileName;
    }

    public int getSeriesId() {
        return seriesId;
    }

    public String getImdbId() {
        return imdbId;
    }

    public double getTvdbRating() {
        return tvdbRating;
    }
}


text:
namespace Engine
{
	class MainMenuScreen :
		public MenuScreen
	{
#pragma region Initialization
	public:
		MainMenuScreen(void);
		~MainMenuScreen(void);
#pragma endregion

#pragma region Handle Input
		void PlayGameMenuEntrySelected(void* sender,int playerIndex);
		void OptionsMenuSelected(void* sender,int playerIndex);
		void OnCancel(void* sender,int playerIndex);
		void ConfirmExitMessageBoxAccepted(void* sender,int playerIndex);
#pragma endregion
	};

}


text:
package org.gradle.api.internal.artifacts;

import org.gradle.api.artifacts.ArtifactIdentifier;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.internal.component.external.model.DefaultModuleComponentArtifactIdentifier;

import static org.gradle.api.internal.artifacts.DefaultModuleVersionIdentifier.newId;

public class DefaultArtifactIdentifier implements ArtifactIdentifier {
    private final ModuleVersionIdentifier moduleVersionIdentifier;
    private final String name;
    private final String type;
    private final String extension;
    private final String classifier;

    public DefaultArtifactIdentifier(ModuleVersionIdentifier moduleVersionIdentifier, String name, String type, String extension, String classifier) {
        this.moduleVersionIdentifier = moduleVersionIdentifier;
        this.name = name;
        this.type = type;
        this.extension = extension;
        this.classifier = classifier;
    }

    public DefaultArtifactIdentifier(DefaultModuleComponentArtifactIdentifier id) {
        this(newId(id.getComponentIdentifier()), id.getName().getName(), id.getName().getType(), id.getName().getExtension(), id.getName().getClassifier());
    }

    public ModuleVersionIdentifier getModuleVersionIdentifier() {
        return moduleVersionIdentifier;
    }

    public String getName() {
        return name;
    }

    public String getType() {
        return type;
    }

    public String getExtension() {
        return extension;
    }

    public String getClassifier() {
        return classifier;
    }

    @Override
    public String toString() {
        return String.format("module: %s, name: %s, ext: %s, classifier: %s", moduleVersionIdentifier, name, extension, classifier);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof DefaultArtifactIdentifier)) {
            return false;
        }

        DefaultArtifactIdentifier that = (DefaultArtifactIdentifier) o;

        if (classifier != null ? !classifier.equals(that.classifier) : that.classifier != null) {
            return false;
        }
        if (extension != null ? !extension.equals(that.extension) : that.extension != null) {
            return false;
        }
        if (moduleVersionIdentifier != null ? !moduleVersionIdentifier.equals(that.moduleVersionIdentifier) : that.moduleVersionIdentifier != null) {
            return false;
        }
        if (name != null ? !name.equals(that.name) : that.name != null) {
            return false;
        }
        if (type != null ? !type.equals(that.type) : that.type != null) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = moduleVersionIdentifier != null ? moduleVersionIdentifier.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (type != null ? type.hashCode() : 0);
        result = 31 * result + (extension != null ? extension.hashCode() : 0);
        result = 31 * result + (classifier != null ? classifier.hashCode() : 0);
        return result;
    }
}


text:
require 'volt/server/html_parser/view_parser'
require 'volt/tasks/task_handler'

# Initialize with the path to a component and returns all the front-end
# setup code (for controllers, models, views, and routes)
module Volt
  class ComponentTemplates
    # client is if we are generating for the client or backend
    def initialize(component_path, component_name, client = true)
      @component_path = component_path
      @component_name = component_name
      @client         = client
    end

    def code
      code = generate_routes_code + generate_view_code
      if @client
        # On the backend, we just need the views
        code << generate_controller_code + generate_model_code + generate_tasks_code
      end

      code
    end

    def page_reference
      '$page'
    end

    def generate_view_code
      code       = ''
      views_path = "#{@component_path}/views/"

      # Load all templates in the folder
      Dir["#{views_path}*/*.html"].sort.each do |view_path|
        # Get the path for the template, supports templates in folders
        template_path = view_path[views_path.size..((-1 * ('.html'.size + 1)))]
        template_path = "#{@component_name}/#{template_path}"

        all_templates = ViewParser.new(File.read(view_path), template_path)

        binding_initializers = []
        all_templates.templates.each_pair do |name, template|
          binding_code = []

          if template['bindings']
            template['bindings'].each_pair do |key, value|
              binding_code << "#{key.inspect} => [#{value.join(', ')}]"
            end
          end

          binding_code = "{#{binding_code.join(', ')}}"

          code << "#{page_reference}.add_template(#{name.inspect}, #{template['html'].inspect}, #{binding_code})\n"
        end
      end

      code
    end

    def generate_controller_code
      code             = ''
      controllers_path = "#{@component_path}/controllers/"

      Dir["#{controllers_path}*_controller.rb"].sort.each do |controller_path|
        code << File.read(controller_path) + "\n\n"
      end

      code
    end

    def generate_model_code
      code        = ''
      models_path = "#{@component_path}/models/"

      Dir["#{models_path}*.rb"].sort.each do |model_path|
        code << File.read(model_path) + "\n\n"

        model_name = model_path.match(/([^\/]+)[.]rb$/)[1]
      end

      code
    end

    def generate_routes_code
      code        = ''
      routes_path = "#{@component_path}/config/routes.rb"

      if File.exist?(routes_path)
        code << "#{page_reference}.add_routes do\n"
        code << "\n" + File.read(routes_path) + "\n"
        code << "end\n\n"
      end

      code
    end

    def generate_tasks_code
      Task.known_handlers.map do |handler|
        "class #{handler.name} < Volt::Task; end"
      end.join "\n"
    end
  end
end


text:
In the spirit of open source, we welcome contributions. These can be as trivial as fixing typos or grammatical errors, to suggesting new areas of guidance in the style guide.

We will review your submission and may suggest amendments via the comments system. However, we are not obliged to accept all contributions and will maintain editorial control.

## Process
Submissions should be made as pull requests. Each piece will be reviewed by a content specialist, who will make sure it stays true to the GOV.UK style as well as the spirit of the manual.

Once a change has been submitted it will stay open as a pull request for a few days so that teams throughout GDS and beyond get a chance to review and comment.

Remember to:

* [write helpful commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
* [check the GDS style guide](https://www.gov.uk/design-principles/style-guide) for tips on how to write to our standard
* [check the service manual](https://www.gov.uk/service-manual/design-and-content) for tips on how to create content