text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

namespace core_question\bank;

/**
 * Base class for representing a column in a {@link question_bank_view}.
 *
 * @copyright  2009 Tim Hunt
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

abstract class column_base {
    /**
     * @var question_bank_view
     */
    protected $qbank;

    /** @var bool determine whether the column is td or th. */
    protected $isheading = false;

    /**
     * Constructor.
     * @param $qbank the question_bank_view we are helping to render.
     */
    public function __construct(view $qbank) {
        $this->qbank = $qbank;
        $this->init();
    }

    /**
     * A chance for subclasses to initialise themselves, for example to load lang strings,
     * without having to override the constructor.
     */
    protected function init() {
    }

    /**
     * Set the column as heading
     */
    public function set_as_heading() {
        $this->isheading = true;
    }

    public function is_extra_row() {
        return false;
    }

    /**
     * Output the column header cell.
     */
    public function display_header() {
        echo 'get_classes() . '" scope="col">';
        $sortable = $this->is_sortable();
        $name = get_class($this);
        $title = $this->get_title();
        $tip = $this->get_title_tip();
        if (is_array($sortable)) {
            if ($title) {
                echo '
' . $title . '
';
            }
            $links = array();
            foreach ($sortable as $subsort => $details) {
                $links[] = $this->make_sort_link($name . '-' . $subsort,
                        $details['title'], '', !empty($details['reverse']));
            }
            echo '
' . implode(' / ', $links) . '
';
        } else if ($sortable) {
            echo $this->make_sort_link($name, $title, $tip);
        } else {
            if ($tip) {
                echo '';
            }
            echo $title;
            if ($tip) {
                echo '';
            }
        }
        echo "	\n";
    }

    /**
     * Title for this column. Not used if is_sortable returns an array.
     * @param object $question the row from the $question table, augmented with extra information.
     * @param string $rowclasses CSS class names that should be applied to this row of output.
     */
    protected abstract function get_title();

    /**
     * @return string a fuller version of the name. Use this when get_title() returns
     * something very short, and you want a longer version as a tool tip.
     */
    protected function get_title_tip() {
        return '';
    }

    /**
     * Get a link that changes the sort order, and indicates the current sort state.
     * @param $name internal name used for this type of sorting.
     * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
     * @param $title the link text.
     * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
     * @return string HTML fragment.
     */
    protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
        $currentsort = $this->qbank->get_primary_sort_order($sort);
        $newsortreverse = $defaultreverse;
        if ($currentsort) {
            $newsortreverse = $currentsort > 0;
        }
        if (!$tip) {
            $tip = $title;
        }
        if ($newsortreverse) {
            $tip = get_string('sortbyxreverse', '', $tip);
        } else {
            $tip = get_string('sortbyx', '', $tip);
        }
        $link = 'qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
        $link .= $title;
        if ($currentsort) {
            $link .= $this->get_sort_icon($currentsort < 0);
        }
        $link .= '';
        return $link;
    }

    /**
     * Get an icon representing the corrent sort state.
     * @param $reverse sort is descending, not ascending.
     * @return string HTML image tag.
     */
    protected function get_sort_icon($reverse) {
        global $OUTPUT;
        if ($reverse) {
            return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'), '', array('class' => 'iconsort'));
        } else {
            return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'), '', array('class' => 'iconsort'));
        }
    }

    /**
     * Output this column.
     * @param object $question the row from the $question table, augmented with extra information.
     * @param string $rowclasses CSS class names that should be applied to this row of output.
     */
    public function display($question, $rowclasses) {
        $this->display_start($question, $rowclasses);
        $this->display_content($question, $rowclasses);
        $this->display_end($question, $rowclasses);
    }

    /**
     * Output the opening column tag.  If it is set as heading, it will use  tag instead of
     *
     * @param stdClass $question
     * @param array $rowclasses
     */
    protected function display_start($question, $rowclasses) {
        $tag = 'td';
        $attr = array('class' => $this->get_classes());
        if ($this->isheading) {
            $tag = 'th';
            $attr['scope'] = 'row';
        }
        echo \html_writer::start_tag($tag, $attr);
    }

    /**
     * @return string the CSS classes to apply to every cell in this column.
     */
    protected function get_classes() {
        $classes = $this->get_extra_classes();
        $classes[] = $this->get_name();
        return implode(' ', $classes);
    }

    /**
     * @param object $question the row from the $question table, augmented with extra information.
     * @return string internal name for this column. Used as a CSS class name,
     *     and to store information about the current sort. Must match PARAM_ALPHA.
     */
    public abstract function get_name();

    /**
     * @return array any extra class names you would like applied to every cell in this column.
     */
    public function get_extra_classes() {
        return array();
    }

    /**
     * Output the contents of this column.
     * @param object $question the row from the $question table, augmented with extra information.
     * @param string $rowclasses CSS class names that should be applied to this row of output.
     */
    protected abstract function display_content($question, $rowclasses);

    /**
     * Output the closing column tag
     *
     * @param object $question
     * @param string $rowclasses
     */
    protected function display_end($question, $rowclasses) {
        $tag = 'td';
        if ($this->isheading) {
            $tag = 'th';
        }
        echo \html_writer::end_tag($tag);
    }

    /**
     * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
     * this column required.
     *
     * The return values for all the columns will be checked. It is OK if two
     * columns join in the same table with the same alias and identical JOIN clauses.
     * If to columns try to use the same alias with different joins, you get an error.
     * The only table included by default is the question table, which is aliased to 'q'.
     *
     * It is importnat that your join simply adds additional data (or NULLs) to the
     * existing rows of the query. It must not cause additional rows.
     *
     * @return array 'table_alias' => 'JOIN clause'
     */
    public function get_extra_joins() {
        return array();
    }

    /**
     * @return array fields required. use table alias 'q' for the question table, or one of the
     * ones from get_extra_joins. Every field requested must specify a table prefix.
     */
    public function get_required_fields() {
        return array();
    }

    /**
     * Can this column be sorted on? You can return either:
     *  + false for no (the default),
     *  + a field name, if sorting this column corresponds to sorting on that datbase field.
     *  + an array of subnames to sort on as follows
     *  return array(
     *      'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
     *      'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
     *  );
     * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
     * order to be DESC.
     * @return mixed as above.
     */
    public function is_sortable() {
        return false;
    }

    /**
     * Helper method for building sort clauses.
     * @param bool $reverse whether the normal direction should be reversed.
     * @param string $normaldir 'ASC' or 'DESC'
     * @return string 'ASC' or 'DESC'
     */
    protected function sortorder($reverse) {
        if ($reverse) {
            return ' DESC';
        } else {
            return ' ASC';
        }
    }

    /**
     * @param $reverse Whether to sort in the reverse of the default sort order.
     * @param $subsort if is_sortable returns an array of subnames, then this will be
     *      one of those. Otherwise will be empty.
     * @return string some SQL to go in the order by clause.
     */
    public function sort_expression($reverse, $subsort) {
        $sortable = $this->is_sortable();
        if (is_array($sortable)) {
            if (array_key_exists($subsort, $sortable)) {
                return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
            } else {
                throw new coding_exception('Unexpected $subsort type: ' . $subsort);
            }
        } else if ($sortable) {
            return $sortable . $this->sortorder($reverse);
        } else {
            throw new coding_exception('sort_expression called on a non-sortable column.');
        }
    }
}


text:
import config from "../config"
import { Looker } from "../looker"
import { LookFinder } from "../repliers/look_finder"
import { ReplyContext } from "../reply_context"
import { Command } from "./command"

const FIND_REGEX = new RegExp("find (dashboard|look )? ?(.+)")

export class SearchCommand extends Command {

  public attempt(context: ReplyContext) {

    const match = context.sourceMessage.text.match(FIND_REGEX)
    if (match) {

      let [, type, query] = match

      const firstWord = query.split(" ")[0]
      const foundLooker = Looker.all.filter((l) => l.url.indexOf(firstWord) !== -1)[0]
      if (foundLooker) {
        const words = query.split(" ")
        words.shift()
        query = words.join(" ")
      }
      context.looker = foundLooker || Looker.all[0]

      new LookFinder(context, type, query).start()

      return true
    } else {
      return false
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
```BasicVal.suffix(desired_suffix, [options])```

Checks if the string value ends with the ```desired_suffix```.


text:
import * as React from "react";

export default class List extends React.Component<{}, {}> {
    public render() {
        return (

List

        );
    }
}


text:
package com.svbio.cloudkeeper.linker.examples;

import com.svbio.cloudkeeper.model.beans.element.annotation.MutableAnnotation;
import com.svbio.cloudkeeper.model.beans.element.annotation.MutableAnnotationEntry;
import com.svbio.cloudkeeper.model.beans.element.annotation.MutableAnnotationTypeDeclaration;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;

@Retention(RetentionPolicy.RUNTIME)
public @interface Memory {
    int value();
    String unit();

    final class Beans {
        private Beans() { }

        public static MutableAnnotationTypeDeclaration declaration() {
            return MutableAnnotationTypeDeclaration.fromClass(Memory.class);
        }

        public static MutableAnnotation createAnnotation(int value, String unit) {
            return new MutableAnnotation()
                .setDeclaration(Memory.class.getName())
                .setEntries(Arrays.asList(
                    new MutableAnnotationEntry()
                        .setKey("value")
                        .setValue(value),
                    new MutableAnnotationEntry()
                        .setKey("unit")
                        .setValue(unit)
                ));
        }
    }
}


text:
package com.voxeo.moho.sample;

import com.voxeo.moho.Application;
import com.voxeo.moho.ApplicationContext;
import com.voxeo.moho.State;
import com.voxeo.moho.event.TextEvent;
import com.voxeo.moho.imified.ImifiedTextChannelProvider;
import com.voxeo.moho.textchannel.TextChannels;
import com.voxeo.moho.textchannel.imified.ImifiedEndpoint;

public class ImifiedEcho implements Application {
  private String _name;

  private String _pwd;

  public void destroy() {

  }

  public void init(final ApplicationContext ctx) {
    _name = ctx.getParameter("username");
    _pwd = ctx.getParameter("password");

    TextChannels.registerProvider(new ImifiedTextChannelProvider());
  }

  @State
  public void handleText(final TextEvent e) throws Exception {
    final ImifiedEndpoint endpoint = (ImifiedEndpoint) e.getTo();
    if (_name != null) {
      endpoint.setImifiedUserName(_name);
      if (_pwd != null) {
        endpoint.setImifiedPasswd(_pwd);
      }
    }
    e.getFrom().sendText(endpoint, e.getText(), e.getTextType());
  }
}


text:
#include <aws/apigatewayv2/model/UpdateRouteResponseResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::ApiGatewayV2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

UpdateRouteResponseResult::UpdateRouteResponseResult()
{
}

UpdateRouteResponseResult::UpdateRouteResponseResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

UpdateRouteResponseResult& UpdateRouteResponseResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("modelSelectionExpression"))
  {
    m_modelSelectionExpression = jsonValue.GetString("modelSelectionExpression");

  }

  if(jsonValue.ValueExists("responseModels"))
  {
    Aws::Map<Aws::String, JsonView> responseModelsJsonMap = jsonValue.GetObject("responseModels").GetAllObjects();
    for(auto& responseModelsItem : responseModelsJsonMap)
    {
      m_responseModels[responseModelsItem.first] = responseModelsItem.second.AsString();
    }
  }

  if(jsonValue.ValueExists("responseParameters"))
  {
    Aws::Map<Aws::String, JsonView> responseParametersJsonMap = jsonValue.GetObject("responseParameters").GetAllObjects();
    for(auto& responseParametersItem : responseParametersJsonMap)
    {
      m_responseParameters[responseParametersItem.first] = responseParametersItem.second.AsObject();
    }
  }

  if(jsonValue.ValueExists("routeResponseId"))
  {
    m_routeResponseId = jsonValue.GetString("routeResponseId");

  }

  if(jsonValue.ValueExists("routeResponseKey"))
  {
    m_routeResponseKey = jsonValue.GetString("routeResponseKey");

  }

  return *this;
}


text:
package de.starwit.auth.apacheds;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

@Mojo(name = "stop")
public class ApacheDSStopMojo extends AbstractMojo {

	@Parameter(property = "apacheds.pidFileLocation")
	private String pidFileLocation;

	public void execute() throws MojoExecutionException, MojoFailureException {
		if (pidFileLocation == null) {
			throw new MojoExecutionException("pid file location not provided - exit.");
		}

		String pid = getPidFromFile(pidFileLocation);
		OperatingSystems currentOS = OperatingSystems.getOSType();

		try {
			Runtime.getRuntime().exec(currentOS.getOsCommand() + " " + pid);
		} catch (IOException e) {
			throw new MojoExecutionException("Couldn't kill apacheds process... " + e.getMessage());
		}
	}

	private String getPidFromFile(String pidFilePath) throws MojoExecutionException {

		File pidFile = new File(pidFilePath);
		try {
			String pid = new String(Files.readAllBytes(pidFile.toPath()),"UTF-8");
			getLog().info("Killing apacheds instance with pid " + pid);
			return pid;
		} catch (IOException e1) {
			throw new MojoExecutionException("Couldn't read pidfile - can't shutdown instance. Exit.");
		}
	}
}


text:
/*

This is just a handy Gulp Boilerplate that
handles the compilation of the source elements

Less 	-> 	CSS 3
Jade 	-> 	xHTML

Premailer Options :

options.mode

Type: String Default value: 'html'

Output format. Either 'html' (HTML formatted email) or 'txt' (plaintext email).
options.baseUrl

Type: String Default value: ''

Base URL to append to relative links.
options.bundleExec

Type: Boolean Default value: false

Run premailer with bundle exec ruby.
options.queryString

Type: String Default value: ''

Query string to append to links.
options.css

Type: Array Default value: []

Additional CSS stylesheets to process. Paths are relative to the Gruntfile.js file. Any Grunt compatible globbing and template syntax is supported.
options.removeClasses

Type: Boolean Default value: false

Removes HTML classes.
options.removeScripts

Type: Boolean Default value: false

Removes HTML scripts. _(was true by default until v0.2.5)
options.removeComments

Type: Boolean Default value: false

Removes HTML comments.
options.preserveStyles

Type: Boolean Default value: false

Preserve any link rel=stylesheet and style elements.
options.lineLength

Type: Number Default value: 65

Line length for plaintext version.
options.ioException

Type: Boolean Default value: false

Aborts on I/O errors.
options.verbose

Type: Boolean Default value: false

Prints additional information at runtime.

*/

// =======================---------------- IMPORT DEPENDENCIES --------------------

// Requirements for this build to work :
var gulp = require('gulp');						// main Gulp
var concat = require('gulp-concat');			// combine files

// JS Plugins
var minify = require('gulp-minify');			// squash files

var newer = require('gulp-newer');				// deal with only modified files
var imagemin = require('gulp-imagemin');		// squish images

// CSS Plugins
var less = require('gulp-less');				// compile less files to css

// HTML Plugins
var jade = require('gulp-jade');
var premailer = require('gulp-premailer');
var htmlmin = require('gulp-htmlmin');

var del = require('del');						// delete things and folders
var sequencer = require('run-sequence');

var livereload = require('gulp-livereload');
// =======================---------------- CONFIGURATION --------------------

// Set up paths here!
var SOURCE_FOLDER 			= 'src/';		// Source files Root
var BUILD_FOLDER 			= 'build/';		// Where the initial build occurs (debugable)
var DISTRIBUTION_FOLDER 	= 'dist/';		// Once debugging is complete, copy to server ready files here

// Where do our source files live?
var source = {
	styles 	: SOURCE_FOLDER+'*.less',
	jade 	: SOURCE_FOLDER+'*.jade',
	jade_examples 	: SOURCE_FOLDER+'examples/*.jade',
	images	: SOURCE_FOLDER+'images/**/*'
};

// Where shall we compile them to?
var destination = {
	styles 	: BUILD_FOLDER,
	html 	: BUILD_FOLDER,
	images	: BUILD_FOLDER+'img'
};

var imageCrunchOptions = {
	optimizationLevel: 3,
	progressive: false
};

var premailerOptions = {
	mode:'txt'
};

var htmlSquishOptions = {
	removeComments     : true,
	collapseWhitespace : true,
	minifyCSS          : true,
	keepClosingSlash   : true
};

// =======================---------------- TASK DEFINITIONS --------------------

gulp.task('clean', function(cb) {
	// You can use multiple globbing patterns as you would with `gulp.src`
	del([BUILD_FOLDER,DISTRIBUTION_FOLDER], cb);
});

// Jade ==========================================================
gulp.task('jade', function() {
	// Minify and copy all JavaScript (except vendor scripts)
	// with sourcemaps all the way down
	return 	gulp.src( source.jade )
			.pipe( jade( { pretty:false, debug:false, compileDebug:false } ) )
			.pipe( gulp.dest( destination.html ) );
});

gulp.task('compile-examples', function() {
	// Minify and copy all JavaScript (except vendor scripts)
	// with sourcemaps all the way down
	return 	gulp.src( source.jade_examples )
			.pipe( jade( { pretty:false, debug:false, compileDebug:false } ) )
			.pipe( gulp.dest( destination.html ) );
});

gulp.task('assemble', function () {
    return 	gulp.src( destination.html +'*.html')
			.pipe( premailer(premailerOptions) )
			.pipe( htmlmin(htmlSquishOptions) )
			.pipe( gulp.dest(DISTRIBUTION_FOLDER) );
});

// Image Tasks ===================================================

// Copy all static images & squish
gulp.task('images', function() {
	return 	gulp.src( source.images)
			.pipe( newer(destination.images) )
			// Pass in options to the task
			.pipe( imagemin( imageCrunchOptions ) )
			.pipe( gulp.dest( destination.images ) );
});

// Cascading Style Sheets ========================================

gulp.task('css', function() {
	return 	gulp.src( source.styles )
			.pipe( newer( destination.styles ) )
			// compile less
			.pipe( less( {strictMath: false, compress: true }) )
			// lint
			// squish
			//.pipe( minify() )
			.pipe( gulp.dest( destination.styles ) );
});

// Utilities =====================================================

// Rerun the task when a file changes
gulp.task('watch', function() {

  // Create LiveReload server
  livereload.listen();

  // Watch any files in dist/, reload on change
  gulp.watch(['dist/**']).on('change', livereload.changed);

});
// =======================---------------- TASKS --------------------

/*

// Assembly

1. Compile css from less
2. Squish css

3. Compile Jade templates
4. Inject css into header
5. Inline css into page elements
6. Compress html

7. Minify Images

*/

// compile all assets & create sourcemaps
gulp.task('build', 		[ 'css', 'jade', 'images' ] );

// squish everything & concatanate scripts
gulp.task('deploy', 	[ 'build', 'assemble' ] );
gulp.task('distribute', ['deploy'] );

// create a server to host this project
gulp.task('serve', 		['images', 'watch'] );

// This creates the examples :)
gulp.task('examples', function(callback) {
	sequencer(
		'clean',
		[ 'css', 'compile-examples', 'images' ],
		'assemble',
    callback);
});

// The default task (called when you run `gulp` from cli)
// As many of these tasks are not asynch
gulp.task('default', function(callback) {
	sequencer(
		'clean',
		'build',
		'assemble',
    callback);
});


text:
package com.tngtech.archunit.library.testclasses.second.any.pkg;

import com.tngtech.archunit.library.testclasses.first.any.pkg.FirstAnyPkgClass;

public class SecondAnyClass {
    FirstAnyPkgClass legalTarget;

    void call() {
        legalTarget.callMe();
    }
}


text:
using System;
using System.Linq;
using System.Collections.Generic;

static class Program
{
    static Dictionary<T, int> GroupByOccurence<T>(IEnumerable<T> elements)
    {
        return elements.GroupBy(el => el).ToDictionary(pair => pair.Key, n => n.Count());
    }

    static LinkedList<T> Filter<T>(this LinkedList<T> linkedList, Predicate<T> predicate)
    {
        for (LinkedListNode<T> node = linkedList.First, next; node != null; node = next)
        {
            next = node.Next;

            if (!predicate(node.Value))
                linkedList.Remove(node);
        }

        return linkedList;
    }

    static void Main()
    {
        LinkedList<int> numbers = new LinkedList<int>(new int[] { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 });

        Dictionary<int, int> groupedByOccurence = GroupByOccurence(numbers);

        Console.WriteLine(string.Join(" ", groupedByOccurence));

        numbers.Filter(n => groupedByOccurence[n] % 2 == 0);

        Console.WriteLine(string.Join(" ", numbers));
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <title>Swanix Icons</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,initial-scale=1">

  <link rel="shortcut icon" href="https://swanix.org/assets/images/favicon.ico">
  <link rel="apple-touch-icon" sizes="114x114" href="https://swanix.org/assets/images/apple-touch-icon.png" />

  <link href="https://cdn.jsdelivr.net/gh/swanix/tool-docs/dist/tool-docs.min.css" rel="stylesheet">
  <link href="dist/swanix-icons.css" rel="stylesheet" >
  <link href="assets/styles/custom.css" rel="stylesheet">


text:
module load workspace/scratch
export OMPI_TMPDIR=$SCRATCH
hostname
DOMAINS=domains
EXT=aa.fasta
if [ -f config.txt ]; then
 source config.txt
else
 echo "need config file to set some project-specific variables"
 exit
fi

mkdir -p $DOMAINS/CAZY

if [ ! $EXT ]; then
 EXT=aa.fasta
fi

if [ ! $PROTEINS ]; then
 PROTEINS=pep
fi

module load db-cazy

if [ ! $CAZY_DB ]; then
 echo "Need a CAZY_DB env variable either from config.txt or 'module load db-cazy'"
g exit
fi
CPUS=${SLURM_CPUS_ON_NODE}
if [ ! $CPUS ]; then
 CPUS=1
fi
IN=${SLURM_ARRAY_TASK_ID}

if [ -z $IN ]; then
 IN=$1
 if [ -z $IN ]; then
   IN=1
   echo "defaulting to IN value is 1 - specify with --array or cmdline"
 fi
fi

TOTAL=$(ls $PROTEINS/*.${EXT} | wc -l)
if [ $IN -gt $TOTAL ]; then
 echo "Only $TOTAL files in folder $PROTEINS, skipping $IN"
 exit
fi
INFILE=$(ls $PROTEINS/*.${EXT} | sed -n ${IN}p)
OUT=$DOMAINS/CAZY/$(basename ${INFILE} .${EXT})

if [ ! -f ${OUT}.hmmscan ]; then
    module load hmmer/3.3.2-mpi
    # hmmscan --cpu $CPUS --domtbl ${OUT}.domtbl -o ${OUT}.hmmscan $CAZY_DB $INFILE
    srun hmmscan --mpi --domtbl ${OUT}.domtbl -o ${OUT}.hmmscan $CAZY_DB $INFILE
    bash $CAZY_FOLDER/hmmscan-parser.sh ${OUT}.domtbl | sort > ${OUT}.tsv
    module unload hmmer
fi

if [[ ! -d $OUT.run_dbcan || ! -f $OUT.run_dbcan/overview.txt ]]; then
    module load run_dbcan
    module load hmmer/3
    run_dbcan --db_dir $CAZY_FOLDER --out_dir $OUT.run_dbcan --tools all \
	--stp_cpu $CPUS --eCAMI_jobs $CPUS --hmm_cpu $CPUS --dia_cpu $CPUS --tf_cpu $CPUS \
	$INFILE protein
fi


text:
require 'test/unit'
require 'rest_client'
require 'dbagger'
require 'json'
require 'webmock/test_unit'

class DbaggerTest < Test::Unit::TestCase
  def stubs
    stub_request(:get, "http://api.server/users/gh_username").with(
      :headers => {
        'Accept'=>'*/*; q=0.5, application/xml',
        'Accept-Encoding'=>'gzip, deflate',
        'User-Agent'=>'Ruby'
      }
    ).to_return(
        :status => 200,
        :body => '{"login": "username","name": "name"}',
        :headers => {}
    )
    stub_request(:get, "http://api.server/users/gh_username/keys").with(
      :headers => {
        'Accept'=>'*/*; q=0.5, application/xml',
        'Accept-Encoding'=>'gzip, deflate',
        'User-Agent'=>'Ruby'
      }
    ).to_return(
      :status => 200,
      :body => '[{"id": 666,"key": "ssh-rsa blahblahblahimadirtytramp"}]',
      :headers => {}
    )
  end

  def test_dbagger
    stubs
    result = Dbagger.collect_data({:username=>"username", :groups=>"group", :github_api=>"http://api.server", :shell=>"shell", :gh_username=>"gh_username"})
    assert_equal result, {:id=>"username", :ssh_keys=>["ssh-rsa blahblahblahimadirtytramp"], :groups=>["group"], :shell=>"shell", :comment=>"name", :password=>"*"}
  end
end


text:
/**
 * Meeting Rooms II
 *
 * Given an array of meeting time intervals consisting of start and end times
 * [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required.
 *
 * Example 1:
 *
 * Input: [[0, 30],[5, 10],[15, 20]]
 * Output: 2
 * Example 2:
 *
 * Input: [[7,10],[2,4]]
 * Output: 1
 */

/**
 * Definition for an interval.
 * function Interval(start, end) {
 *     this.start = start;
 *     this.end = end;
 * }
 */

import PriorityQueue from 'common/priority-queue';

/**
 * @param {Interval[]} intervals
 * @return {number}
 */
const minMeetingRooms = intervals => {
  if (!intervals || intervals.length === 0) {
    return 0;
  }

  const timeline = {};
  for (let { start, end } of intervals) {
    // 1 new event will be starting at [start]
    timeline[start] = ~~timeline[start] + 1;
    // 1 new event will be ending at [end];
    timeline[end] = ~~timeline[end] - 1;
  }

  let ongoing = 0;
  let result = 0;

  for (let v of Object.values(timeline)) {
    result = Math.max(result, (ongoing += v));
  }

  return result;
};

/**
 * Solution II - Priority Queue
 * @param {Interval[]} intervals
 * @return {number}
 */
const minMeetingRoomsII = intervals => {
  if (!intervals || intervals.length == 0) {
    return 0;
  }

  // Sort the intervals by start time
  intervals.sort((a, b) => a[0] - b[0]);

  // Use a min heap to track the minimum end time of merged intervals
  const heap = new PriorityQueue({
    comparator: (a, b) => a[1] - b[1],
  });

  // start with the first meeting, put it to a meeting room
  heap.offer(intervals[0]);

  for (let i = 1; i < intervals.length; i++) {
    const current = intervals[i];

    // get the meeting room that finishes earliest
    const interval = heap.poll();

    if (current[0] >= interval[1]) {
      // if the current meeting starts right after
      // there's no need for a new room, merge the interval
      interval[1] = current[1];
    } else {
      // otherwise, this meeting needs a new room
      heap.offer(current);
    }

    // don't forget to put the meeting room back
    heap.offer(interval);
  }

  return heap.size();
};

export { minMeetingRooms, minMeetingRoomsII };


text:
'use strict';

describe('Directive: pwCheck', function () {

  // load the directive's module
  beforeEach(module('paperchaseApp'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
  }));

  it('should make hidden element visible', inject(function ($compile) {
    element = angular.element('<pw-check></pw-check>');
    element = $compile(element)(scope);
    expect(element.text()).toBe('this is the pwCheck directive');
  }));
});


text:
package com.oasisfeng.android.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Process;
import android.util.Log;

import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.CheckResult;
import androidx.annotation.Nullable;

/**
 * Simplify the AIDL service usage
 *
 * Created by Oasis on 2015/5/19.
 */
public class Services {

	public interface ServiceReadyThrows<I extends IInterface, E extends Exception> {
		void onServiceReady(I service) throws E;
	}

	public interface AidlStub<I extends IInterface> {
		I asInterface(IBinder obj);
	}

	/** Bind to the specified service for one-time procedure, then unbind the service. */
	public static <I extends IInterface, E extends Exception> boolean use(final Context context, final Class<I> itf, final AidlStub<I> stub, final ServiceReadyThrows<I, E> procedure) {
		return bind(context, itf, new ServiceConnection() {
			@Override public void onServiceConnected(final ComponentName name, final IBinder binder) {
				final I service = stub.asInterface(binder);
				try {
					procedure.onServiceReady(service);
				} catch (final Exception e) {
					Log.e(TAG, "Error in " + procedure, e);
				} finally {
					try { context.unbindService(this); } catch (final RuntimeException ignored) {}
				}
			}

			@Override public void onServiceDisconnected(final ComponentName name) {}
			@Override public String toString() { return "ServiceConnection{" + procedure.toString() + "}"; }	// About the source of service invocation
		});
	}

	public static boolean bind(final Context context, final Class<? extends IInterface> service_interface, final ServiceConnection conn) {
		final Intent service_intent = buildServiceIntent(context, service_interface);
		if (service_intent == null) {
			Log.w(TAG, "No matched service for " + service_interface.getName());
			return false;
		}
		return context.bindService(service_intent, conn, Context.BIND_AUTO_CREATE);
	}

	public static @CheckResult @Nullable <I extends IInterface> I bindLocal(final Context context, final Class<I> service_interface) {
		if (! sRegistry.isEmpty()) {
			@SuppressWarnings("unchecked") final I instance = (I) sRegistry.get(service_interface);
			if (instance != null) return instance;
		}
		return LocalAidlServices.bind(context, service_interface, buildServiceIntent(context, service_interface));
	}

	public static @Nullable Service createLocal(final Context context, final String classname) {
		return LocalAidlServices.createService(context, classname);
	}

	public static void destroyLocal(final Service service) {
		LocalAidlServices.destroyService(service);
	}

	public static <I extends IInterface> void unbindLocal(final Context context, final I instance) {
		if (sRegistry.containsValue(instance)) return;		// TODO: Reference counting registered services
		LocalAidlServices.unbind(context, instance);
	}

	public static <I extends IInterface> void register(final Class<I> service_interface, final I instance) {
		final IInterface existent = sRegistry.get(service_interface);
		if (existent != null) {
			if (existent == instance) return;
			throw new IllegalStateException(service_interface + " was already registered with " + existent.getClass());
		}
		sRegistry.put(service_interface, instance);
	}

	public static <I extends IInterface> boolean unregister(final Class<I> service_interface, final I instance) {
		final IInterface existent = sRegistry.get(service_interface);
		if (existent == null) return false;
		if (instance != existent) throw new IllegalStateException(service_interface + " was registered with " + existent + ", but being unregistered with " + instance);
		sRegistry.remove(service_interface);
		return true;
	}

	public static <I extends IInterface> I peekService(final Context context, final Class<I> service_interface) {
		final IBinder binder = peekService(context, buildServiceIntent(context, service_interface));
		if (binder == null) return null;
		try {	//noinspection unchecked
			return (I) service_interface.getMethod("asInterface", IBinder.class).invoke(null, binder);
		} catch (final Exception e) {
			Log.e(TAG, "Error calling " + service_interface.getCanonicalName() + ".asInterface() on " + binder, e);
			return null;
		}
	}

	public static IBinder peekService(final Context context, final Intent intent) {
		return sDummyReceiver.peekService(context, intent);
	}

	private static @Nullable Intent buildServiceIntent(final Context context, final Class<?> service_interface) {
		final String name = service_interface.getName(); final Intent intent = new Intent(name);
		final PackageManager pm = context.getPackageManager(); final int uid = Process.myUid();

		final ComponentName component = resolveServiceIntent(context, intent, new Comparator<ResolveInfo>() { @Override public int compare(final ResolveInfo left, final ResolveInfo right) {
			final ApplicationInfo app_left = left.serviceInfo.applicationInfo, app_right = right.serviceInfo.applicationInfo;
			// 1 - UID
			int rank_left = app_left.uid != uid ? 1 : 0;
			int rank_right = app_right.uid != uid ? 1 : 0;
			if (rank_left != rank_right) return rank_left - rank_right;
			// 2 - Priority
			final int priority_diff = left.priority - right.priority;
			if (priority_diff != 0) return (- priority_diff);        // Higher priority wins
			// 3 - Package update time
			if (! app_left.packageName.equals(app_right.packageName)) {
				final PackageInfo pkg_left, pkg_right;
				try {
					pkg_left = pm.getPackageInfo(app_left.packageName, 0);
				} catch (final PackageManager.NameNotFoundException e) {
					return 1;
				}        // right wins
				try {
					pkg_right = pm.getPackageInfo(app_right.packageName, 0);
				} catch (final PackageManager.NameNotFoundException e) {
					return - 1;
				}        // left wins
				if (pkg_left.lastUpdateTime != pkg_right.lastUpdateTime)
					return (int) - (pkg_left.lastUpdateTime - pkg_right.lastUpdateTime);    // Newer wins
			}
			// 4 - Package name
			final String pkg = context.getPackageName();
			rank_left = pkg.equals(app_left.packageName) ? 0 : 1;
			rank_right = pkg.equals(app_right.packageName) ? 0 : 1;
			if (rank_left != rank_right) return rank_left - rank_right;
			return 0;
		}});
		if (component == null) return null;
		intent.setComponent(component);
		return intent;
	}

	/** @param comparator comparator for resolving candidates, smaller wins */
	private static @Nullable ComponentName resolveServiceIntent(final Context context, final Intent intent, final Comparator<ResolveInfo> comparator) {
		final List<ResolveInfo> matches = context.getPackageManager().queryIntentServices(intent, 0);
		if (matches == null || matches.isEmpty()) return null;

		ResolveInfo best_match = matches.get(0);
		final int my_uid = Process.myUid();
		for (final ResolveInfo match : matches) {
			if (! match.serviceInfo.exported && match.serviceInfo.applicationInfo.uid != my_uid) continue;
			if (best_match != match && comparator.compare(match, best_match) < 0)
				best_match = match;
		}

		final ComponentName component = new ComponentName(best_match.serviceInfo.packageName, best_match.serviceInfo.name);
		if (matches.size() > 1) Log.w(TAG, "Final match for " + intent + " among " + matches.size() + ": " + component.flattenToShortString());

		return component;
	}

	private static final Map<Class, IInterface> sRegistry = new IdentityHashMap<>();
	private static final BroadcastReceiver sDummyReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) {}};
	private static final String TAG = "Services";
}


text:
/*$(function () {

});*/

window.onload = function () {
    	if (document.getElementById("evemail").innerHTML!=""){

		var email = document.getElementById("evemail").innerHTML;
		var ebtoken =  document.getElementById("ebtoken").innerHTML;
		var fullname =	document.getElementById("evfullname").innerHTML;

		var dataString = 'email=' + email + '&ebtoken=' + ebtoken;

		if (fullname != ""){
			var firstname= fullname.substring(0, fullname.indexOf(' '));
			var lastname= fullname.substring(fullname.indexOf(' ')+1, fullname.length);
			var dataString = 'email=' + email + '&ebtoken=' + ebtoken + '&firstname=' + firstname + '&lastname=' + lastname;

		}
		//alert (dataString);
		// AJAX code to submit form.
		$.ajax({
		type: "POST",
		url: "query/evloginquery.php",
		data: dataString,
		cache: false,
		success: function(result) {
				//alert(result);
				sweetAlert("We're in!", "Login successful" , "success");
				//if(result==='inserted row') {setInterval(gotoCreateEvent, 1500);}
				//else {setInterval(gotoURL, 1500);}
				// gotoURL();
				setTimeout(gotoURL, 1500);
				//gotoURL();
			},
		error: function (request, status, error) {
		        	sweetAlert("Error", "Error" , "error");
		    }
		});

	}
}

/*function registerattempt(){
	//alert(document.getElementById("registeremail").value);
	registeremail=document.getElementById("registeremail").value;
}*/

function gotoURL(){
	//alert("salam");
	var gotourl =  document.getElementById("goto").value;
	window.location= gotourl;
	//var location = "http://www.cardstak.com/"+gotourl;
	//alert(location);
	return false;
}

function gotoCreateEvent(){
	window.location="http://www.cardstak.com/create_event.php";
}

function evhover(element) {
    element.setAttribute('src', 'http://cardstak.com/images/evsignin-hover.png');
}

function evunhover(element) {
    element.setAttribute('src', 'http://cardstak.com/images/evsignin.png');
}

function hover(element) {
    element.setAttribute('src', 'http://cardstak.com/images/Sign-In-Large---Hover.png');
}
function unhover(element) {
    element.setAttribute('src', 'http://cardstak.com/images/Sign-In-Large---Default.png');
}

function loginattempt(){
	$("body").css("cursor", "progress");
	$(":button").css("cursor", "progress");
	whitenFields();
	var email = document.getElementById("email").value;
	var password =  document.getElementById("password").value;

	var dataString = 'email=' + email + '&password=' + password;

	if (email == '') {
		swal("Oops...", "Please enter your email", "error");
		document.getElementById("email").style.border="2px solid red";
		document.getElementById("email").style.background="rgb(255, 238, 238)";
		 $("body").css("cursor", "default");
		 $(":button").css("cursor", "pointer");
	}
	else if( password== '' ){
		sweetAlert("Oops...", "Please enter your password", "error");
		document.getElementById("password").style.border="2px solid red";
		document.getElementById("password").style.background="rgb(255, 238, 238)";
		 $("body").css("cursor", "default");
		 $(":button").css("cursor", "pointer");
	} else {

		// AJAX code to submit form.
		$.ajax({
		type: "POST",
		url: "query/loginquery.php",
		data: dataString,
		cache: false,
		success: function(result) {
		if(result=="Login successful"){
			sweetAlert("We're in!", result , "success");
			setInterval(gotoURL, 1500);
		}
		else{
			sweetAlert("Oops...", result, "error");
		}
		//alert(html);
		//window.location=eventurl;
		 $("body").css("cursor", "default");
		 $(":button").css("cursor", "pointer");
			},
		error: function (request, status, error) {
		        //alert(request.responseText);
		  $("body").css("cursor", "default");
		 $(":button").css("cursor", "pointer");
		    }
		});
	}
	return false;
}

function registerattempt(){
	$("body").css("cursor", "progress");
	$(":button").css("cursor", "progress");
	whitenFields();
	var registeremail = document.getElementById("registeremail").value;
	var registerpassword =  document.getElementById("registerpassword").value;
	var registerfirstname = document.getElementById("registerfirstname").value;
	var registerlastname = document.getElementById("registerlastname").value;

	var dataString = 'registeremail=' + registeremail + '&registerpassword=' + registerpassword + '&registerfirstname=' + registerfirstname + '&registerlastname=' + registerlastname;

	if (registeremail == '') {
		swal("Oops...", "Please enter your email", "error");
		document.getElementById("registeremail").style.border="2px solid red";
		document.getElementById("registeremail").style.background="rgb(255, 238, 238)";
		$("body").css("cursor", "default");
		$(":button").css("cursor", "pointer");
	}
	else if( registerpassword== '' ){
		sweetAlert("Oops...", "Please enter your password", "error");
		document.getElementById("registerpassword").style.border="2px solid red";
		document.getElementById("registerpassword").style.background="rgb(255, 238, 238)";
		$("body").css("cursor", "default");
		$(":button").css("cursor", "pointer");
	}
	else if( registerfirstname== '' ){
		sweetAlert("Oops...", "Please enter your firstname", "error");
		document.getElementById("registerfirstname").style.border="2px solid red";
		document.getElementById("registerfirstname").style.background="rgb(255, 238, 238)";
		$("body").css("cursor", "default");
		$(":button").css("cursor", "pointer");
	}
	else if( registerlastname== '' ){
		sweetAlert("Oops...", "Please enter your lastname", "error");
		document.getElementById("registerlastname").style.border="2px solid red";
		document.getElementById("registerlastname").style.background="rgb(255, 238, 238)";
		$("body").css("cursor", "default");
		$(":button").css("cursor", "pointer");
	} else {
		// AJAX code to submit form.
		$.ajax({
		type: "POST",
		url: "query/registerquery.php",
		data: dataString,
		cache: false,
		success: function(result) {
		if(result=="User Registered"){
			clearFields();
			document.getElementById("password").focus();
			sweetAlert("Congrats!", result+", please re-enter your password to Login" , "success");
			document.getElementById("loginmessage").innerHTML="<b>Please re-enter your password to Login</b>";
			document.getElementById("email").value=registeremail;
			document.getElementById("password").style.border="2px solid blue";

		}
		else{
			sweetAlert("Oops...", result, "error");
		}
		 $("body").css("cursor", "default");
		 $(":button").css("cursor", "pointer");
			},
		error: function (request, status, error) {
		        //alert(request.responseText);
		 $("body").css("cursor", "default");
		 $(":button").css("cursor", "pointer");
		    }
		});
	}
	return false;
}

function whitenFields(){
	document.getElementById("email").style.border="";
	document.getElementById("email").style.background="";
	document.getElementById("password").style.border="";
	document.getElementById("password").style.background="";

	document.getElementById("registeremail").style.border="";
	document.getElementById("registeremail").style.background="";
	document.getElementById("registerpassword").style.border="";
	document.getElementById("registerpassword").style.background="";
	document.getElementById("registerfirstname").style.border="";
	document.getElementById("registerfirstname").style.background="";
	document.getElementById("registerlastname").style.border="";
	document.getElementById("registerlastname").style.background="";

}

function clearFields(){
	document.getElementById("email").value="";
	document.getElementById("password").value="";
	document.getElementById("registeremail").value="";
	document.getElementById("registerpassword").value="";
	document.getElementById("registerfirstname").value="";
	document.getElementById("registerlastname").value="";
}


text:
layout: post
title: "🎨 New Theme"
---

I'm a little late on this, but I finally took the time to put a new theme
together. Here are some of the highlights.

{% include toc.md %}

## A look back

After two and a half years of the spartan, utilitarian look, I decided it was
time to freshen up the place a bit. That original theme was not without its
purpose—consuming content on the web can be exhausting, so I wanted a
place where I could provide content free from all the shackles of modern web
presentation. I didn't use any analytics (still don't), the colors I did use
were slight tweaks on the browser defaults, and the font stack was whatever your
operating system gave you.

{% include figure.html src='/assets/images/redesign/previous.png' alt='Previous
design of bshow.co, featuring a rather bland appearance' caption="It's called
MVP for a reason, right?" %}

As much as I did quite like the minimalist approach, it started to feel like I
was sending the wrong signals. I consider myself a designer, after all, so
shouldn't my site have at least some personality?

## Starting over

I started my little redesign by scouring the web for inspiration. There are
certainly lots of hot 🔥 trends these days, but I still wanted to keep things on
the more low-key side.

{% include figure.html src='/assets/images/redesign/rough_sketch.jpg' alt='Rough
wireframe-style sketch of the new website home page, drawn with digital ink
on a dot grid' caption='Home page sketch in Goodnotes 5' %}

The home page is the obvious choice for injecting a little bit of flair. I took
to Goodnotes on my iPad and started sketching up some ideas. The above wireframe
is what I finally settled on—a layered intro section with a picture and a
text blurb, then two massive links to featured portfolio and blog items.

With a goal in mind, I hopped over to
[CodePen](https://codepen.io/bobbyshowalter/pen/69870e7eff425d59fcca5318f97ef553)
to get a feel for how this design could work. I also grabbed a color scheme from
[Color Hunt](https://colorhunt.co/palette/168262).

{% include figure.html src='/assets/images/redesign/colors.png' alt='New color
palette of lighter and darker shades of a lavender-like purple, red, and orange'
caption='A nice departure from black on white' %}

{% include figure.html src='/assets/images/redesign/mockup.png' alt='HTML and
CSS mockup of new home page' caption='CodePen is a great environment for sussing
things out without worrying about scaffolding a particular dev setup' %}

Getting into code made it simple to start experimenting with the color and
layout beyond what my simple sketch could have done. I rotated my headshot
picture a bit and added some gradients to the featured content links.

Personality! 😎

## More than just a pretty face

With the home page in place, it was time to tackle…well, everything else.

I quite like a "featured image" on a blog post when it's done well. Trouble is,
coming up with an appropriate image for every post is an extra chore that I'm
just not interested in. Luckily, neat services like
[Unsplash](https://source.unsplash.com/) exist. I had read that the Birmingham
Museums Trust uploaded a large collection of their [watercolour
paintings](https://unsplash.com/collections/9248817/watercolour) for use, so I
wired up my post headers to pull a random image from their collection at every
page load. That way every post gets a pleasing picture without having to spend
any time thinking about it. I may come back at some point and enhance the post
layout by allowing for a defined featured image, but this works great for now.

The typography received a great deal of attention as well. I'm still using the
same `70ch`-wide body text column as before, but now it is set within a larger
page grid that allows for much more creativity. I pulled the list punctuation
out into the left margin (except on smaller views where it could get lost against
the edge of the browser), bumped up the base `font-size`, and even opted for a
new typeface duo of [Archivo](https://fonts.google.com/specimen/Archivo) and
[Archivo Black](https://fonts.google.com/specimen/Archivo+Black).

## That's all…for now

I think that about takes care of the important updates. It took over a [dozen
commits](https://github.com/orangedaisy/bshowco/issues/12) to get here, but I'm
pleased with the result and have enjoyed working with this new look as I
continue to make content updates.

Is it finished? Gosh, no. I have some cleanup to do to make the page and post
styles a little <abbr title="Don't Repeat Yourself">DRY</abbr>-er. Dark themes
are just about expected these days, so I need to figure that out as well. But
I'll get there eventually, perhaps on a day where I need a mental break or spark
of joy from more stressful situations. That's what makes this such a great
[worry stone](https://ethanmarcotte.com/wrote/let-a-website-be-a-worry-stone/).


text:
.PHONY: test
test:
	ant clean test


text:
namespace daq_api.Models.WebMap
{
    public class BaseMapLayer
    {
        public string Id { get; set; }
        public string LayerType { get; set; }
        public string Url { get; set; }
        public bool Visibility { get; set; }
        public int Opacity { get; set; }
        public string Title { get; set; }
        public string TemplateUrl { get; set; }
        public FullExtent FullExtent { get; set; }
        public TileInfo TileInfo { get; set; }
        public WmtsInfo WmtsInfo { get; set; }
        public string Type { get; set; }
        public bool? IsReference { get; set; }
        public string ItemId { get; set; }
    }
}


text:
namespace freeze {

int setNonBlock(int fd, bool value);

class TcpConn {
 public:
  TcpConn();
  int connect(const std::string& host, int port);
 private:
  std::string dest_host_;
  int dest_port_;
};

class TcpServer{
 public:
  TcpServer();
  int bind(const std::string& host, int port);
  //int startServer(const std::string& host, int port);
  int accept();
 private:
  int fd_;
  Poller poller_;

};

}


text:
#include <modules/qtwidgets/properties/listpropertywidgetqt.h>

#include <inviwo/core/properties/listproperty.h>                     // for ListProperty, ListPr...
#include <inviwo/core/properties/property.h>                         // for Property
#include <inviwo/core/util/exception.h>                              // for Exception
#include <inviwo/core/util/rendercontext.h>                          // for RenderContext
#include <inviwo/core/util/sourcecontext.h>                          // for IVW_CONTEXT
#include <inviwo/core/util/zip.h>                                    // for enumerate, zipIterator
#include <modules/qtwidgets/inviwoqtutils.h>                         // for toQString
#include <modules/qtwidgets/properties/compositepropertywidgetqt.h>  // for CompositePropertyWid...

#include <string>       // for operator+, string
#include <string_view>  // for string_view
#include <vector>       // for __vector_base<>::val...

#include <QAction>        // for QAction
#include <QCursor>        // for QCursor
#include <QHBoxLayout>    // for QHBoxLayout
#include <QLayout>        // for QLayout
#include <QLayoutItem>    // for QLayoutItem
#include <QMenu>          // for QMenu
#include <QToolButton>    // for QToolButton
#include <QVariant>       // for QVariant
#include <QtGlobal>       // for uint
#include <flags/flags.h>  // for operator&, flags

class QHBoxLayout;

namespace inviwo {

ListPropertyWidgetQt::ListPropertyWidgetQt(ListProperty* property)
    : CompositePropertyWidgetQt(property), listProperty_(property) {

    if (!listProperty_) {
        throw Exception("ListPropertyWidgetQt got a null ListProperty", IVW_CONTEXT);
    }

    setShowIfEmpty(true);
    setEmptyLabelString("No list entries");

    auto headerlayout = dynamic_cast<QHBoxLayout*>(layout()->itemAt(0)->layout());
    if (!headerlayout) {
        throw Exception("CompositePropertyWidget has no header layout.", IVW_CONTEXT);
    }

    // inject "add" button in the header of the composite property for adding list elements
    addItemButton_ = new QToolButton(this);
    addItemButton_->setObjectName("addListItemButton");
    addItemButton_->setToolTip("Add list element");

    setFocusPolicy(addItemButton_->focusPolicy());
    setFocusProxy(addItemButton_);

    connect(addItemButton_, &QToolButton::clicked, this, [&]() {
        if (listProperty_ && listProperty_->getPrefabCount() > 0) {
            // need to activate the default render context in case the property contains member
            // depending on OpenGL
            RenderContext::getPtr()->activateDefaultRenderContext();
            if (listProperty_->getPrefabCount() == 1) {
                addNewItem(0);
            } else {
                // show context menu since there exist more than one prefab in the list property
                QMenu m;
                for (auto&& item : util::enumerate(listProperty_->getPrefabs())) {
                    auto addAction =
                        m.addAction(utilqt::toQString(item.second()->getDisplayName()));
                    addAction->setData(static_cast<uint>(item.first()));
                }

                if (auto selectedAction = m.exec(QCursor::pos())) {
                    addNewItem(selectedAction->data().toUInt());
                }
            }
        }
    });

    addItemButton_->setVisible(
        static_cast<bool>(listProperty_->getUIFlags() & ListPropertyUIFlag::Add));

    headerlayout->insertWidget(headerlayout->count() - 2, addItemButton_);
}

void ListPropertyWidgetQt::updateFromProperty() {
    CompositePropertyWidgetQt::updateFromProperty();
    addItemButton_->setEnabled(canAddElements());
}

bool ListPropertyWidgetQt::isChildRemovable() const {
    return static_cast<bool>(listProperty_->getUIFlags() & ListPropertyUIFlag::Remove);
}

std::unique_ptr<QMenu> ListPropertyWidgetQt::getContextMenu() {
    auto menu = CompositePropertyWidgetQt::getContextMenu();

    menu->addSeparator();

    if (listProperty_->getUIFlags() & ListPropertyUIFlag::Add) {
        if (listProperty_->getPrefabCount() == 1) {
            auto addAction = menu->addAction(
                utilqt::toQString("Add " + listProperty_->getPrefabs().front()->getDisplayName()));
            connect(addAction, &QAction::triggered, this, [this]() { addNewItem(0); });
        } else {
            auto addItemMenu = menu->addMenu("&Add Item");
            if (listProperty_->getPrefabCount() > 0) {
                for (auto&& item : util::enumerate(listProperty_->getPrefabs())) {
                    auto addAction =
                        addItemMenu->addAction(utilqt::toQString(item.second()->getDisplayName()));
                    connect(addAction, &QAction::triggered, this,
                            [this, index = item.first()]() { addNewItem(index); });
                }
            } else {  // no prefab objects available
                auto action = addItemMenu->addAction("No templates available");
                action->setEnabled(false);
            }

            // disable add item menu if list property is already fully filled
            addItemMenu->setEnabled(canAddElements());
        }
    }

    if (listProperty_->getUIFlags() & ListPropertyUIFlag::Remove) {
        auto clearAction = menu->addAction(tr("&Clear Items"));
        connect(clearAction, &QAction::triggered, this, [&]() {
            listProperty_->setInitiatingWidget(this);
            listProperty_->clear();
            listProperty_->clearInitiatingWidget();
        });
    }

    menu->addSeparator();

    return menu;
}

void ListPropertyWidgetQt::addNewItem(size_t index) {
    listProperty_->setInitiatingWidget(this);
    listProperty_->constructProperty(index);
    listProperty_->setCollapsed(false);
    listProperty_->clearInitiatingWidget();
}

bool ListPropertyWidgetQt::canAddElements() const {
    return (listProperty_->getMaxNumberOfElements() == 0) ||
           (listProperty_->size() < listProperty_->getMaxNumberOfElements());
}

}  // namespace inviwo


text:
#import <SenTestingKit/SenTestingKit.h>

#import "ChumpChunk.h"

@interface ChumpChunkTests : SenTestCase

// class
- (void)testParseSize;

// instance
- (void)testInit;
- (void)testInitWithPayload;
- (void)testToData;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Octopus
{
    public class DataItemSorter : IComparer<string>
    {
        private static readonly Lazy<DataItemSorter> _instance
                = new Lazy<DataItemSorter>(() => new DataItemSorter());

        private DataItemSorter() { }

        public static DataItemSorter Instance
        {
            get
            {
                return _instance.Value;
            }
        }

        public int Compare(string x, string y)
        {
            return 1;
        }
    }
}


text:
.td-center
{
    text-align: center;
}

.link-disabled
{
    cursor: default !important;
    pointer-events: none;
}


text:
<?php
namespace tests\app\decibel\http;

use app\decibel\http\DOk;
use app\decibel\test\DTestCase;

/**
 * Test class for DOk.
 * @group http
 */
class DOkTest extends DTestCase
{
    /**
     * @covers app\decibel\http\DOk::execute
     */
    public function testExecute()
    {
        $response = new DOk();
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );
    }

    /**
     * @covers app\decibel\http\DOk::execute
     */
    public function testExecutePartialContent()
    {
        $response = new DOk();
        $this->markTestIncomplete(
            'This test has not been implemented yet.'
        );
    }
    /**
     * @covers app\decibel\http\DOk::getStatusCode
     */
    public function testGetStatusCode()
    {
        $response = new DOk();
        $this->assertSame(200, $response->getStatusCode());
    }

    /**
     * @covers app\decibel\http\DOk::getResponseType
     */
    public function testGetResponseType()
    {
        $response = new DOk();
        $this->assertSame('HTTP/1.1 200 OK', $response->getResponseType());
    }
}


text:
package com.sun.awt;

import java.awt.*;
import java.awt.geom.*;

import sun.awt.AWTAccessor;

/**
 * Security Warning control interface.
 *
 * This class provides a couple of methods that help a developer relocate
 * the AWT security warning to an appropriate position relative to the current
 * window size. A "top-level window" is an instance of the {@code Window}
 * class (or its descendant, such as {@code JFrame}). The security warning
 * is applied to all windows created by an untrusted code. All such windows
 * have a non-null "warning string" (see {@link Window#getWarningString()}).
 *

 * WARNING: This class is an implementation detail and only meant
 * for limited use outside of the core platform. This API may change
 * drastically between update release, and it may even be
 * removed or be moved to some other packages or classes.
 */
public final class SecurityWarning {

    /**
     * The SecurityWarning class should not be instantiated
     */
    private SecurityWarning() {
    }

    /**
     * Gets the size of the security warning.
     *
     * The returned value is not valid until the peer has been created. Before
     * invoking this method a developer must call the {@link Window#pack()},
     * {@link Window#setVisible()}, or some other method that creates the peer.
     *
     * @param window the window to get the security warning size for
     *
     * @throws NullPointerException if the window argument is null
     * @throws IllegalArgumentException if the window is trusted (i.e.
     * the {@code getWarningString()} returns null)
     */
    public static Dimension getSize(Window window) {
        if (window == null) {
            throw new NullPointerException(
                    "The window argument should not be null.");
        }
        if (window.getWarningString() == null) {
            throw new IllegalArgumentException(
                    "The window must have a non-null warning string.");
        }
        // We don't check for a non-null peer since it may be destroyed
        // after assigning a valid value to the security warning size.

        return AWTAccessor.getWindowAccessor().getSecurityWarningSize(window);
    }

    /**
     * Sets the position of the security warning.
     *

     * The {@code alignmentX} and {@code alignmentY} arguments specify the
     * origin of the coordinate system used to calculate the position of the
     * security warning. The values must be in the range [0.0f...1.0f].  The
     * {@code 0.0f} value represents the left (top) edge of the rectangular
     * bounds of the window. The {@code 1.0f} value represents the right
     * (bottom) edge of the bounds. Whenever the size of the window changes,
     * the origin of the coordinate system gets relocated accordingly. For
     * convenience a developer may use the {@code Component.*_ALIGNMENT}
     * constants to pass predefined values for these arguments.
     *

     * The {@code point} argument specifies the location of the security
     * warning in the coordinate system described above. If both {@code x} and
     * {@code y} coordinates of the point are equal to zero, the warning will
     * be located right in the origin of the coordinate system. On the other
     * hand, if both {@code alignmentX} and {@code alignmentY} are equal to
     * zero (i.e. the origin of the coordinate system is placed at the top-left
     * corner of the window), then the {@code point} argument represents the
     * absolute location of the security warning relative to the location of
     * the window. The "absolute" in this case means that the position of the
     * security warning is not effected by resizing of the window.
     *

     * Note that the security warning managment code guarantees that:
     *

     *
The security warning cannot be located farther than two pixels from
     * the rectangular bounds of the window (see {@link Window#getBounds}), and
     *
The security warning is always visible on the screen.
     *

     * If either of the conditions is violated, the calculated position of the
     * security warning is adjusted by the system to meet both these
     * conditions.
     *

     * The default position of the security warning is in the upper-right
     * corner of the window, two pixels to the right from the right edge. This
     * corresponds to the following arguments passed to this method:
     *

     *
{@code alignmentX = Component.RIGHT_ALIGNMENT}
     *
{@code alignmentY = Component.TOP_ALIGNMENT}
     *
{@code point = (2, 0)}
     *

     *
     * @param window the window to set the position of the security warning for
     * @param alignmentX the horizontal origin of the coordinate system
     * @param alignmentY the vertical origin of the coordinate system
     * @param point the position of the security warning in the specified
     * coordinate system
     *
     * @throws NullPointerException if the window argument is null
     * @throws NullPointerException if the point argument is null
     * @throws IllegalArgumentException if the window is trusted (i.e.
     * the {@code getWarningString()} returns null
     * @throws IllegalArgumentException if the alignmentX or alignmentY
     * arguments are not within the range [0.0f ... 1.0f]
     */
    public static void setPosition(Window window, Point2D point,
            float alignmentX, float alignmentY)
    {
        if (window == null) {
            throw new NullPointerException(
                    "The window argument should not be null.");
        }
        if (window.getWarningString() == null) {
            throw new IllegalArgumentException(
                    "The window must have a non-null warning string.");
        }
        if (point == null) {
            throw new NullPointerException(
                    "The point argument must not be null");
        }
        if (alignmentX < 0.0f || alignmentX > 1.0f) {
            throw new IllegalArgumentException(
                    "alignmentX must be in the range [0.0f ... 1.0f].");
        }
        if (alignmentY < 0.0f || alignmentY > 1.0f) {
            throw new IllegalArgumentException(
                    "alignmentY must be in the range [0.0f ... 1.0f].");
        }

        AWTAccessor.getWindowAccessor().setSecurityWarningPosition(window,
                point, alignmentX, alignmentY);
    }
}


text:
.c-slider {
  position: relative;
  overflow: hidden;
}

.c-slider-content {
  position: relative;
  height: 100%;

  &.transition {
    transition: transform 0.2s;
  }

  & > * {
    position: absolute;
    width: 100%;
    height: 100%;
  }
}

.c-slider-indicators {
  position: absolute;
  width: 100%;
  bottom: dpr(20px);
  text-align: center;
  overflow: hidden;
}

.c-slider-indicator {
  display: inline-block;
  margin: dpr(8px);
  width: dpr(16px);
  height: dpr(16px);
  border-radius: 50%;
  background-color: color(white alpha(0.5));

  &.active {
    background-color: white;
  }
}


text: Bookmark service


text:
// Copyright 2016 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Directive for the Search Bar.
 */

require('filters/string-utility-filters/truncate.filter.ts');

require('domain/utilities/LanguageUtilService.ts');
require('domain/utilities/UrlInterpolationService.ts');
require('services/ConstructTranslationIdsService.ts');
require('services/DebouncerService.ts');
require('services/HtmlEscaperService.ts');
require('services/NavigationService.ts');
require('services/SearchService.ts');
require('services/contextual/UrlService.ts');

angular.module('oppia').directive('searchBar', [
  'UrlInterpolationService', function(UrlInterpolationService) {
    return {
      restrict: 'E',
      scope: {},
      bindToController: {},
      templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
        '/pages/library-page/search-bar/search-bar.directive.html'),
      controllerAs: '$ctrl',
      controller: [
        '$location', '$rootScope', '$scope', '$timeout', '$translate',
        '$window', 'ConstructTranslationIdsService', 'DebouncerService',
        'HtmlEscaperService', 'LanguageUtilService', 'NavigationService',
        'SearchService', 'UrlService', 'SEARCH_DROPDOWN_CATEGORIES',
        function(
            $location, $rootScope, $scope, $timeout, $translate,
            $window, ConstructTranslationIdsService, DebouncerService,
            HtmlEscaperService, LanguageUtilService, NavigationService,
            SearchService, UrlService, SEARCH_DROPDOWN_CATEGORIES) {
          var ctrl = this;
          ctrl.isSearchInProgress = SearchService.isSearchInProgress;
          ctrl.SEARCH_DROPDOWN_CATEGORIES = (
            SEARCH_DROPDOWN_CATEGORIES.map(
              function(categoryName) {
                return {
                  id: categoryName,
                  text: ConstructTranslationIdsService.getLibraryId(
                    'categories', categoryName)
                };
              }
            )
          );
          ctrl.ACTION_OPEN = NavigationService.ACTION_OPEN;
          ctrl.ACTION_CLOSE = NavigationService.ACTION_CLOSE;
          ctrl.KEYBOARD_EVENT_TO_KEY_CODES =
          NavigationService.KEYBOARD_EVENT_TO_KEY_CODES;
          /**
           * Opens the submenu.
           * @param {object} evt
           * @param {String} menuName - name of menu, on which
           * open/close action to be performed (category,language).
           */
          ctrl.openSubmenu = function(evt, menuName) {
            NavigationService.openSubmenu(evt, menuName);
          };
          /**
           * Handles keydown events on menus.
           * @param {object} evt
           * @param {String} menuName - name of menu to perform action
           * on(category/language)
           * @param {object} eventsTobeHandled - Map keyboard events('Enter') to
           * corresponding actions to be performed(open/close).
           *
           * @example
           *  onMenuKeypress($event, 'category', {enter: 'open'})
           */

          ctrl.onMenuKeypress = function(evt, menuName, eventsTobeHandled) {
            NavigationService.onMenuKeypress(evt, menuName, eventsTobeHandled);
            ctrl.activeMenuName = NavigationService.activeMenuName;
          };
          ctrl.ALL_LANGUAGE_CODES = (
            LanguageUtilService.getLanguageIdsAndTexts());

          ctrl.searchQuery = '';
          ctrl.selectionDetails = {
            categories: {
              description: '',
              itemsName: 'categories',
              masterList: ctrl.SEARCH_DROPDOWN_CATEGORIES,
              numSelections: 0,
              selections: {},
              summary: ''
            },
            languageCodes: {
              description: '',
              itemsName: 'languages',
              masterList: ctrl.ALL_LANGUAGE_CODES,
              numSelections: 0,
              selections: {},
              summary: ''
            }
          };

          // Non-translatable parts of the html strings, like numbers or user
          // names.
          ctrl.translationData = {};

          // Update the description, numSelections and summary fields of the
          // relevant entry of ctrl.selectionDetails.
          var updateSelectionDetails = function(itemsType) {
            var itemsName = ctrl.selectionDetails[itemsType].itemsName;
            var masterList = ctrl.selectionDetails[itemsType].masterList;

            var selectedItems = [];
            for (var i = 0; i < masterList.length; i++) {
              if (ctrl.selectionDetails[itemsType]
                .selections[masterList[i].id]) {
                selectedItems.push(masterList[i].text);
              }
            }

            var totalCount = selectedItems.length;
            ctrl.selectionDetails[itemsType].numSelections = totalCount;

            ctrl.selectionDetails[itemsType].summary = (
              totalCount === 0 ? 'I18N_LIBRARY_ALL_' + itemsName.toUpperCase() :
              totalCount === 1 ? selectedItems[0] :
              'I18N_LIBRARY_N_' + itemsName.toUpperCase());
            ctrl.translationData[itemsName + 'Count'] = totalCount;

            // TODO(milit): When the language changes, the translations won't
            // change until the user changes the selection and this function is
            // re-executed.
            if (selectedItems.length > 0) {
              var translatedItems = [];
              for (var i = 0; i < selectedItems.length; i++) {
                translatedItems.push($translate.instant(selectedItems[i]));
              }
              ctrl.selectionDetails[itemsType].description = (
                translatedItems.join(', '));
            } else {
              ctrl.selectionDetails[itemsType].description = (
                'I18N_LIBRARY_ALL_' + itemsName.toUpperCase() + '_SELECTED');
            }
          };

          ctrl.toggleSelection = function(itemsType, optionName) {
            var selections = ctrl.selectionDetails[itemsType].selections;
            if (!selections.hasOwnProperty(optionName)) {
              selections[optionName] = true;
            } else {
              selections[optionName] = !selections[optionName];
            }

            updateSelectionDetails(itemsType);
            onSearchQueryChangeExec();
          };

          ctrl.deselectAll = function(itemsType) {
            ctrl.selectionDetails[itemsType].selections = {};
            updateSelectionDetails(itemsType);
            onSearchQueryChangeExec();
          };

          $scope.$watch('$ctrl.searchQuery', function(
              newQuery, oldQuery) {
            // Run only if the query has changed.
            if (newQuery !== oldQuery) {
              onSearchQueryChangeExec();
            }
          });

          var onSearchQueryChangeExec = function() {
            SearchService.executeSearchQuery(
              ctrl.searchQuery, ctrl.selectionDetails.categories.selections,
              ctrl.selectionDetails.languageCodes.selections);

            var searchUrlQueryString = SearchService.getSearchUrlQueryString(
              ctrl.searchQuery, ctrl.selectionDetails.categories.selections,
              ctrl.selectionDetails.languageCodes.selections
            );
            if ($window.location.pathname === '/search/find') {
              $location.url('/find?q=' + searchUrlQueryString);
            } else {
              $window.location.href = '/search/find?q=' + searchUrlQueryString;
            }
          };

          // Initialize the selection descriptions and summaries.
          for (var itemsType in ctrl.selectionDetails) {
            updateSelectionDetails(itemsType);
          }

          var updateSearchFieldsBasedOnUrlQuery = function() {
            var oldQueryString = SearchService.getCurrentUrlQueryString();

            ctrl.selectionDetails.categories.selections = {};
            ctrl.selectionDetails.languageCodes.selections = {};

            ctrl.searchQuery =
             SearchService.updateSearchFieldsBasedOnUrlQuery(
               $window.location.search, ctrl.selectionDetails);

            updateSelectionDetails('categories');
            updateSelectionDetails('languageCodes');

            var newQueryString = SearchService.getCurrentUrlQueryString();

            if (oldQueryString !== newQueryString) {
              onSearchQueryChangeExec();
            }
          };

          $scope.$on('$locationChangeSuccess', function() {
            if (UrlService.getUrlParams().hasOwnProperty('q')) {
              updateSearchFieldsBasedOnUrlQuery();
            }
          });

          $scope.$on(
            'preferredLanguageCodesLoaded',
            function(evt, preferredLanguageCodesList) {
              preferredLanguageCodesList.forEach(function(languageCode) {
                var selections =
                 ctrl.selectionDetails.languageCodes.selections;
                if (!selections.hasOwnProperty(languageCode)) {
                  selections[languageCode] = true;
                } else {
                  selections[languageCode] = !selections[languageCode];
                }
              });

              updateSelectionDetails('languageCodes');

              if (UrlService.getUrlParams().hasOwnProperty('q')) {
                updateSearchFieldsBasedOnUrlQuery();
              }

              if ($window.location.pathname === '/search/find') {
                onSearchQueryChangeExec();
              }

              refreshSearchBarLabels();

              // Notify the function that handles overflow in case the search
              // elements load after it has already been run.
              $rootScope.$broadcast('searchBarLoaded', true);
            }
          );

          var refreshSearchBarLabels = function() {
            // If you translate these strings in the html, then you must use a
            // filter because only the first 14 characters are displayed. That
            // would generate FOUC for languages other than English. As an
            // exception, we translate them here and update the translation
            // every time the language is changed.
            ctrl.searchBarPlaceholder = $translate.instant(
              'I18N_LIBRARY_SEARCH_PLACEHOLDER');
            // 'messageformat' is the interpolation method for plural forms.
            // http://angular-translate.github.io/docs/#/guide/14_pluralization.
            ctrl.categoryButtonText = $translate.instant(
              ctrl.selectionDetails.categories.summary,
              ctrl.translationData, 'messageformat');
            ctrl.languageButtonText = $translate.instant(
              ctrl.selectionDetails.languageCodes.summary,
              ctrl.translationData, 'messageformat');
          };

          $rootScope.$on('$translateChangeSuccess', refreshSearchBarLabels);
        }
      ]
    };
  }]);


text:
local libos = require "libos"
local ejresource = require "ejresource"
local ejpackage = require "ejpackage"
local utils = require "utils"

local usage = [[
Usage: simplepacker inputdir [-o path] [-n name] [-ni] [-fmt ppm|png] [-np] [-ps packsize] [-na] [-raw] [-v]
  -o: specify output directory
  -n: specify output package name
  -ni: no image, ignore raw image files(png) from the input
  -fmt: specify image format, ppm and png is available. default value is ppm
  -np: no pack, do not pack images to large image sheet
  -ps: specify image sheet size, up to 2048. default value is 1024
  -na: no animation, ignore animation description files(.a.lua)
  -raw: write down all data instead of exporting a ejoy2d package
        output folder can used as the input to create ejoy2d package later
  -v: show verbose log
]]

-- configuration
local config = {
	proc_img = true,  -- whether to read raw image
	proc_anim = true,  -- whether to read anim
	pack_img = true,
	img_fmt = "ppm",
	output_path = false,
	output_name = false,
	pack_size = 1024,
	output_raw = false,  -- true for write down all data, false for export ejoy2d package
}

-- functions
local function _parse_args(args)
	if not args[2] then  -- check input path
		print("require input path")
		return false
	end

	local i = 3
	while i <= #args do
		local arg = args[i]
		if arg == "-o" then
			local op = args[i + 1]
			if op[1] == "-" then
				print("illegal output path")
				return false
			end
			config.output_path = op
			i = i + 1
		elseif arg == "-n" then
			local on = args[i + 1]
			if on[1] == "-" then
				print("illegal output name")
				return false
			end
			config.output_name = on
			i = i + 1
		elseif arg == "-ni" then
			config.proc_img = false
		elseif arg == "-fmt" then
			local fmt = args[i + 1]
			if fmt ~= "ppm" and fmt ~= "png" then
				print("illegal image format")
				return false
			end
			config.img_fmt = fmt
			i = i + 1
		elseif arg == "-np" then
			config.pack_img = false
		elseif arg == "-ps" then
			local ps = tonumber(args[i + 1])
			if ps <= 0 or ps > 2048 then
				print("illegal pack size")
				return false
			end
			config.pack_size = ps
			i = i + 1
		elseif arg == "-na" then
			config.proc_anim = false
		elseif arg == "-raw" then
			config.output_raw = true
		elseif arg == "-v" then
			utils:enable_log()
		else
			print("illegal argument", arg)
			return false
		end
		i = i + 1
	end

	return true
end

local function _check_anims(imgs)
	local anims = {}

	-- sort by image name
	table.sort(imgs, function (a, b) return a.name < b.name end)

	local i = 1
	while i <= #imgs do
		-- find image name like xxx1
		local _,_,name = string.find(imgs[i].name, "(%a+)1")
		if name then
			local idx = 2
			local found
			repeat  -- find the whole sequence
				found = false
				i = i + 1
				if i > #imgs then
					break
				end
				if imgs[i].name == name..tostring(idx) then
					found = true
					idx = idx + 1
				end
			until not found

			if idx > 2 then
				local anim = ejresource:new_anim(name)
				local frames = {}
				for j=1,idx-1 do
					local com = {name=name..tostring(j)}  -- name only, no other attributes
					table.insert(frames, {com})
				end
				anim:add_action(frames)
				table.insert(anims, anim)
				utils:logf("auto create anim <%s> frames=(%d)", name, idx-1)
			end
		else
			i = i + 1
		end
	end

	return anims
end

-- entry point
function run(args)
	-- init arguments
	if not _parse_args(args) then
		print(usage)
		return
	end

	-- init work path
	local input = utils:trim_slash(args[2])
	local output = input.."_out"
	if config.output_path then
		output = utils:trim_slash(config.output_path)
	end
	libos:makedir(output)

	-- walk input folder
	local file_list = libos.walkdir(input)
	if not file_list then
		utils:logf("error input path")
		print(usage)
		return
	end

	-- process input files
	local all_imgs = {}  -- raw images, only png supported
	local all_sheets = {}  -- iamge sheets
	local all_anims = {}  -- animation description

	for _,v in ipairs(file_list) do
		local full_name = input.."/"..v
		local name = string.sub(v, 1, string.find(v, ".", 1, true) - 1)  -- name is the filename without ext

		if config.proc_img and utils:check_ext(v, ".png") then
			local img = ejresource:load_img(full_name, name)
			if img then
				utils:logf("load img <%s> success size=(%d,%d) offset=(%d,%d)", name, img.w, img.h, img.ox, img.oy)
				table.insert(all_imgs, img)
			else
				utils:logf("load img <%s> failed", name)
			end
		end

		if utils:check_ext(v, ".p.lua") then
			local sheet = ejresource:load_sheet(full_name)
			if sheet then
				utils:logf("load sheet <%s> success", name)
				table.insert(all_sheets, sheet)
			else
				utils:logf("load sheet <%s> failed", name)
			end
		end

		if config.proc_anim and utils:check_ext(v, ".a.lua") then
			local anim = ejresource:load_anim(full_name, name)
			if anim then
				utils:logf("load anim <%s> success", name)
				table.insert(all_anims, anim)
			else
				utils:logf("load anim <%s> failed", name)
			end
		end
	end

	-- guess anim from image filename
	if config.proc_anim then
		local anims = _check_anims(all_imgs)
		for _,v in ipairs(anims) do
			table.insert(all_anims, v)
		end
	end

	-- pack raw images onto image sheet
	if config.pack_img then
		local sheet_map = {}
		local left_imgs = {}

		for _,v in ipairs(all_imgs) do
			local pixfmt = v.pixfmt
			local sheet = sheet_map[pixfmt]
			if not sheet then
				sheet = ejresource:new_sheet(config.pack_size, pixfmt)
				sheet_map[pixfmt] = sheet
				utils:logf("create a new image sheet with format %s", pixfmt)
			end
			if not sheet:pack_img(v) then
				table.insert(left_imgs, v)
				utils:logf("pack image <%s> failed", v.name)
			else
				utils:logf("pack image <%s> success", v.name)
			end
		end

		for _,v in pairs(sheet_map) do
			table.insert(all_sheets, v)
		end

		all_imgs = left_imgs  -- too big to pack
	end

	-- output
	if config.output_raw then
		utils:logf("export all data to a detailed format")

		for _,v in ipairs(all_imgs) do
			local path = string.format("%s/%s", output, v.name)
			v:save(path, true, config.img_fmt)  -- image save as image sheet
		end

		for i,v in ipairs(all_sheets) do
			local path = string.format("%s/imagesheet%d", output, i)
			v:save(path, true, config.img_fmt)
		end

		for _,v in ipairs(all_anims) do
			local path = string.format("%s/%s.a.lua", output, v.name)
			v:save(path)
		end
	else
		local _,_,name = string.find(input, ".-([^\\/]+)$")
		if config.output_name then
			name = config.output_name
		end
		local pkg = ejpackage:new_pkg(name, config.img_fmt)

		utils:logf("export ejoy2d package %s", name)

		-- raw images
		for _,v in ipairs(all_imgs) do
			pkg:add_img(v)
		end

		-- packed images
		for _,v in ipairs(all_sheets) do
			pkg:add_sheet(v)
		end

		-- anims
		for _,v in ipairs(all_anims) do
			pkg:add_anim(v)
		end

		-- save to disk
		pkg:save(output)
	end
end


text:
import React from 'react';
import { Form, Button, Dropdown } from 'semantic-ui-react';

export function UpdateProfile(profileid) {
  return (

Update Profile

  )
}

export function AddTransaction(profileid) {
  return (

Add Transaction

  )
}