text:
import os
import platform
import re
import string
import subprocess
import sys
import tempfile
import urllib2
import zipfile
import StringIO

# Project Settings
BASEDIR_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_PATH = BASEDIR_PATH + '/data'
DATA_FILENAMES = 'hosts'
UPDATE_URL_FILENAME = 'update.info'
SOURCES = os.listdir(DATA_PATH)
README_TEMPLATE = BASEDIR_PATH + '/readme_template.md'
README_FILE = BASEDIR_PATH + '/readme.md'
TARGET_HOST = '0.0.0.0'

# Exclusions
EXCLUSION_PATTERN = '([a-zA-Z\d-]+\.){0,}' #append domain the end

# Common domains to exclude
COMMON_EXCLUSIONS = ['hulu.com']

# Global vars
exclusionRegexs = []
numberOfRules = 0

def main():
	promptForUpdate()
	promptForExclusions()
	mergeFile = createInitialFile()
	finalFile = removeDups(mergeFile)
	finalizeFile(finalFile)
	updateReadme(numberOfRules)
	printSuccess('Success! Your shiny new hosts file has been prepared.\nIt contains ' + str(numberOfRules) + ' unique entries.')
	promptForMove(finalFile)

# Prompt the User
def promptForUpdate():
	response = query_yes_no("Do you want to update all data sources?")
	if (response == "yes"):
		updateAllSources()
	else:
		print 'OK, we\'ll stick with what we\'ve  got locally.'

def promptForExclusions():
	response = query_yes_no("Do you want to exclude any domains?\n" +
							"For example, hulu.com video streaming must be able to access " +
							"its tracking and ad servers in order to play video.")
	if (response == "yes"):
		displayExclusionOptions()
	else:
		print 'OK, we won\'t exclude any domains.'

def promptForMoreCustomExclusions():
	response = query_yes_no("Do you have more domains you want to enter?")
	if (response == "yes"):
		return True
	else:
		return False

def promptForMove(finalFile):
  response = query_yes_no("Do you want to replace your existing hosts file with the newly generated file?")
  if (response == "yes"):
    moveHostsFileIntoPlace(finalFile)
  else:
    return False
# End Prompt the User

# Exclusion logic
def displayExclusionOptions():
	for exclusionOption in COMMON_EXCLUSIONS:
		response = query_yes_no("Do you want to exclude the domain " + exclusionOption + " ?")
		if (response == "yes"):
			excludeDomain(exclusionOption)
		else:
			continue
	response = query_yes_no("Do you want to exclude any other domains?")
	if (response == "yes"):
		gatherCustomExclusions()

def gatherCustomExclusions():
	while True:
		domainFromUser = raw_input("Enter the domain you want to exclude (e.g. facebook.com): ")
		if (isValidDomainFormat(domainFromUser)):
			excludeDomain(domainFromUser)
		if (promptForMoreCustomExclusions() == False):
			return

def excludeDomain(domain):
	exclusionRegexs.append(re.compile(EXCLUSION_PATTERN + domain))

def matchesExclusions(strippedRule):
	strippedDomain = strippedRule.split()[1]
	for exclusionRegex in exclusionRegexs:
		if exclusionRegex.search(strippedDomain):
			return True
	return False
# End Exclusion Logic

# Update Logic
def updateAllSources():
	for source in SOURCES:
		updateURL = getUpdateURLFromFile(source)
		if (updateURL == None):
			continue;
		print 'Updating source ' + source + ' from ' + updateURL
		updatedFile = urllib2.urlopen(updateURL)

		updatedFile = updatedFile.read()

		if '.zip' in updateURL:
			updatedZippedFile = zipfile.ZipFile(StringIO.StringIO(updatedFile))
			for name in updatedZippedFile.namelist():
				if name in ('hosts', 'hosts.txt'):
					updatedFile = updatedZippedFile.open(name).read()
					break

		updatedFile = string.replace( updatedFile, '\r', '' ) #get rid of carriage-return symbols

		dataFile   = open(DATA_PATH + '/' + source + '/' + DATA_FILENAMES, 'w')
		dataFile.write(updatedFile)
		dataFile.close()

def getUpdateURLFromFile(source):
	pathToUpdateFile = DATA_PATH + '/' + source + '/' + UPDATE_URL_FILENAME
	if os.path.exists(pathToUpdateFile):
		updateFile = open(pathToUpdateFile, 'r')
		retURL = updateFile.readline().strip()
		updateFile.close()
	else:
		retURL = None
		printFailure('Warning: Can\'t find the update file for source ' + source + '\n' +
					 'Make sure that there\'s a file at ' + pathToUpdateFile)
	return retURL
# End Update Logic

# File Logic
def createInitialFile():
	mergeFile = tempfile.NamedTemporaryFile()
	for source in SOURCES:
		curFile = open(DATA_PATH + '/' + source +'/' + DATA_FILENAMES, 'r')
		mergeFile.write('\n# Begin ' + source + '\n')
		mergeFile.write(curFile.read())
		mergeFile.write('\n# End ' + source + '\n')
	return mergeFile

def removeDups(mergeFile):
	global numberOfRules

	finalFile = open(BASEDIR_PATH + '/hosts', 'w+b')
	mergeFile.seek(0) # reset file pointer

	hostnames = set()
	for line in mergeFile.readlines():
		if line[0].startswith("#") or re.match(r'^\s*$', line[0]):
			finalFile.write(line) #maintain the comments for readability
			continue
		strippedRule = stripRule(line) #strip comments
		if matchesExclusions(strippedRule):
			continue
		hostname, normalizedRule = normalizeRule(strippedRule) # normalize rule

		if normalizedRule and (hostname not in hostnames):
			finalFile.write(normalizedRule)
			hostnames.add(hostname)
			numberOfRules += 1

	mergeFile.close()

	return finalFile

def normalizeRule(rule):
	result = re.search(r'^[ \t]*(\d+\.\d+\.\d+\.\d+)\s+([\w\.-]+)(.*)',rule)
	if result:
		target, hostname, suffix = result.groups()
		return hostname, "%s %s %s\n" % (TARGET_HOST, hostname, suffix)
	print '==>%s<==' % rule
	return None, None

def finalizeFile(finalFile):
	writeOpeningHeader(finalFile)
	finalFile.close()

# Some sources put comments around their rules, for accuracy we need to strip them
# the comments are preserved in the output hosts file
def stripRule(line):
	splitLine = line.split()
	if (len(splitLine) < 2) :
		printFailure('A line in the hostfile is going to cause problems because it is nonstandard\n' +
					 'The line reads ' + line + ' please check your data files. Maybe you have a comment without a #?')
		sys.exit()
	return splitLine[0] + ' ' + splitLine[1]

def writeOpeningHeader(finalFile):
	global numberOfRules
	finalFile.seek(0) #reset file pointer
	fileContents = finalFile.read(); #save content
	finalFile.seek(0) #write at the top
	finalFile.write('# This file is a merged collection of hosts from reputable sources,\n')
	finalFile.write('# with a dash of crowd sourcing via Github\n#\n')
	finalFile.write('# Project home page: https://github.com/StevenBlack/hosts\n#\n')
	finalFile.write('# Current sources:\n')
	for source in SOURCES:
		finalFile.write('#    ' + source + '\n')
	finalFile.write('#\n')
	finalFile.write('# Merging these sources produced ' + str(numberOfRules) + ' unique entries\n')
	finalFile.write('# ===============================================================\n')
	finalFile.write(fileContents)

def updateReadme(numberOfRules):
	with open(README_FILE, "wt") as out:
		for line in open(README_TEMPLATE):
			out.write(line.replace('@NUM_ENTRIES@', str(numberOfRules)))

def moveHostsFileIntoPlace(finalFile):
	if (os.name == 'posix'):
		print 'Moving the file requires administrative privileges. You might need to enter your password.'
		if(subprocess.call(["/usr/bin/sudo", "cp", os.path.abspath(finalFile.name), "/etc/hosts"])):
			printFailure("Moving the file failed.")
		print 'Flushing the DNS Cache to utilize new hosts file...'
		if (platform.system() == 'Darwin'):
			if(subprocess.call(["/usr/bin/sudo", "killall", "-HUP", "mDNSResponder"])):
				printFailure("Flushing the DNS Cache failed.")
		else:
			if(subprocess.call(["/usr/bin/sudo", "/etc/rc.d/init.d/nscd", "restart"])):
				printFailure("Flushing the DNS Cache failed.")
	elif (os.name == 'nt'):
		print 'Automatically moving the hosts file in place is not yet supported.'
		print 'Please move the generated file to %SystemRoot%\system32\drivers\etc\hosts'

# End File Logic

# Helper Functions
## {{{ http://code.activestate.com/recipes/577058/ (r2)
def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The "answer" return value is one of "yes" or "no".
    """
    valid = {"yes":"yes",   "y":"yes",  "ye":"yes",
             "no":"no",     "n":"no"}
    if default == None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while 1:
        sys.stdout.write(colorize(question, colors.PROMPT) + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return default
        elif choice in valid.keys():
            return valid[choice]
        else:
            printFailure("Please respond with 'yes' or 'no' "\
                             "(or 'y' or 'n').\n")
## end of http://code.activestate.com/recipes/577058/ }}}

def isValidDomainFormat(domain):
	if (domain == ''):
		print "You didn\'t enter a domain. Try again."
		return False
	domainRegex = re.compile("www\d{0,3}[.]|https?")
	if (domainRegex.match(domain)):
		print "The domain " + domain + " is not valid. Do not include www.domain.com or http(s)://domain.com. Try again."
		return False
	else:
		return True

# Colors
class colors:
    PROMPT 	= '\033[94m'
    SUCCESS = '\033[92m'
    FAIL 	= '\033[91m'
    ENDC 	= '\033[0m'

def colorize(text, color):
	return color + text + colors.ENDC

def printSuccess(text):
	print colorize(text, colors.SUCCESS)

def printFailure(text):
	print colorize(text, colors.FAIL)
# End Helper Functions

if __name__ == "__main__":
	main()


text:
package com.android.app.function.retrofit.model;

public class JustinTvChannel {
	private String category;
	private String category_title;
	private String channel_url;
	private String embed_code;
	private boolean embed_enabled;
	private String id;
	private String image_url_huge;
	private String image_url_large;
	private String image_url_medium;
	private String image_url_small;
	private String image_url_tiny;
	private String language;
	private String login;
	private String mature;
	private String meta_game;
	private boolean producer;
	private String screen_cap_url_huge;
	private String screen_cap_url_large;
	private String screen_cap_url_medium;
	private String screen_cap_url_small;
	private String status;
	private String subcategory;
	private String subcategory_title;
	private String tags;
	private String timezone;
	private String title;
	private Number views_count;

	public String getCategory() {
		return this.category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getCategory_title() {
		return this.category_title;
	}

	public void setCategory_title(String category_title) {
		this.category_title = category_title;
	}

	public String getChannel_url() {
		return this.channel_url;
	}

	public void setChannel_url(String channel_url) {
		this.channel_url = channel_url;
	}

	public String getEmbed_code() {
		return this.embed_code;
	}

	public void setEmbed_code(String embed_code) {
		this.embed_code = embed_code;
	}

	public boolean getEmbed_enabled() {
		return this.embed_enabled;
	}

	public void setEmbed_enabled(boolean embed_enabled) {
		this.embed_enabled = embed_enabled;
	}

	public String getId() {
		return this.id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getImage_url_huge() {
		return this.image_url_huge;
	}

	public void setImage_url_huge(String image_url_huge) {
		this.image_url_huge = image_url_huge;
	}

	public String getImage_url_large() {
		return this.image_url_large;
	}

	public void setImage_url_large(String image_url_large) {
		this.image_url_large = image_url_large;
	}

	public String getImage_url_medium() {
		return this.image_url_medium;
	}

	public void setImage_url_medium(String image_url_medium) {
		this.image_url_medium = image_url_medium;
	}

	public String getImage_url_small() {
		return this.image_url_small;
	}

	public void setImage_url_small(String image_url_small) {
		this.image_url_small = image_url_small;
	}

	public String getImage_url_tiny() {
		return this.image_url_tiny;
	}

	public void setImage_url_tiny(String image_url_tiny) {
		this.image_url_tiny = image_url_tiny;
	}

	public String getLanguage() {
		return this.language;
	}

	public void setLanguage(String language) {
		this.language = language;
	}

	public String getLogin() {
		return this.login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getMature() {
		return this.mature;
	}

	public void setMature(String mature) {
		this.mature = mature;
	}

	public String getMeta_game() {
		return this.meta_game;
	}

	public void setMeta_game(String meta_game) {
		this.meta_game = meta_game;
	}

	public boolean getProducer() {
		return this.producer;
	}

	public void setProducer(boolean producer) {
		this.producer = producer;
	}

	public String getScreen_cap_url_huge() {
		return this.screen_cap_url_huge;
	}

	public void setScreen_cap_url_huge(String screen_cap_url_huge) {
		this.screen_cap_url_huge = screen_cap_url_huge;
	}

	public String getScreen_cap_url_large() {
		return this.screen_cap_url_large;
	}

	public void setScreen_cap_url_large(String screen_cap_url_large) {
		this.screen_cap_url_large = screen_cap_url_large;
	}

	public String getScreen_cap_url_medium() {
		return this.screen_cap_url_medium;
	}

	public void setScreen_cap_url_medium(String screen_cap_url_medium) {
		this.screen_cap_url_medium = screen_cap_url_medium;
	}

	public String getScreen_cap_url_small() {
		return this.screen_cap_url_small;
	}

	public void setScreen_cap_url_small(String screen_cap_url_small) {
		this.screen_cap_url_small = screen_cap_url_small;
	}

	public String getStatus() {
		return this.status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getSubcategory() {
		return this.subcategory;
	}

	public void setSubcategory(String subcategory) {
		this.subcategory = subcategory;
	}

	public String getSubcategory_title() {
		return this.subcategory_title;
	}

	public void setSubcategory_title(String subcategory_title) {
		this.subcategory_title = subcategory_title;
	}

	public String getTags() {
		return this.tags;
	}

	public void setTags(String tags) {
		this.tags = tags;
	}

	public String getTimezone() {
		return this.timezone;
	}

	public void setTimezone(String timezone) {
		this.timezone = timezone;
	}

	public String getTitle() {
		return this.title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Number getViews_count() {
		return this.views_count;
	}

	public void setViews_count(Number views_count) {
		this.views_count = views_count;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"time"

	"gopkg.in/gorp.v1"
)

type Character struct {
	Id   int    `db:"id"`
	Name string `db:"name"`
}

type Status struct {
	Id        int64     `db:"id"`
	CreatedAt time.Time `db:"created_at"`
	Source    string    `db:"source"`
}

type Ranking struct {
	Id        int       `db:"id"`
	Name      string    `db:"name"`
	StartedOn time.Time `db:"started_on"`
	EndedOn   time.Time `db:"ended_on"`
}

type Entry struct {
	RankingId   int `db:"ranking_id"`
	CharacterId int `db:"character_id"`
}

type Vote struct {
	RankingId   int   `db:"ranking_id"`
	CharacterId int   `db:"character_id"`
	StatusId    int64 `db:"status_id"`
}

type RankingItem struct {
	Rank  int
	Name  string
	Count int
}

func GetCurrentRanking(executor gorp.SqlExecutor, time time.Time) (*Ranking, error) {
	var ranking Ranking
	if err := executor.SelectOne(&ranking, `
		SELECT * FROM ranking
		WHERE $1 BETWEEN started_on AND ended_on
		ORDER BY id DESC
		LIMIT 1
	`, time); err != nil {
		return nil, err
	}
	return &ranking, nil
}

func GetLatestRanking(executor gorp.SqlExecutor, time time.Time) (*Ranking, error) {
	var ranking Ranking
	if err := executor.SelectOne(&ranking, `
		SELECT * FROM ranking
		WHERE $1 >= started_on
		ORDER BY id DESC
		LIMIT 1
	`, time); err != nil {
		return nil, err
	}
	return &ranking, nil
}

func FindCharacterByName(executor gorp.SqlExecutor, name string) (*Character, error) {
	var character Character
	if err := executor.SelectOne(&character,
		`SELECT * FROM character WHERE name = $1 LIMIT 1`); err != nil {
		return nil, err
	}
	return &character, nil
}

func FindEntryByName(executor gorp.SqlExecutor, rankingId int, name string) (*Entry, error) {
	var entry Entry
	if err := executor.SelectOne(&entry, `
		SELECT entry.* FROM entry
		JOIN character ON character.id = entry.character_id
		WHERE
			entry.ranking_id = $1
			AND character.name = $2
		LIMIT 1
	`, rankingId, name); err != nil {
		return nil, err
	}
	return &entry, nil
}

func GetEntryCharacters(executor gorp.SqlExecutor, rankingId int) ([]Character, error) {
	var characters []Character
	if _, err := executor.Select(&characters, `
		SELECT character.* FROM character
		JOIN entry ON
			entry.character_id = character.id
			AND entry.ranking_id = $1
	`, rankingId); err != nil {
		return nil, err
	}
	return characters, nil
}

func GetRankingItems(executor gorp.SqlExecutor, rankingId int) ([]RankingItem, error) {
	var rankingItems []RankingItem
	if _, err := executor.Select(&rankingItems, `
		SELECT
			RANK() OVER (ORDER BY x.count DESC) AS Rank,
			character.name AS Name,
			x.count AS Count
		FROM (
			SELECT
				vote.character_id, COUNT(*) AS count
			FROM vote
			JOIN entry ON
				entry.ranking_id = vote.ranking_id
				AND entry.character_id = vote.character_id
			WHERE vote.ranking_id = $1
			GROUP BY vote.character_id
		) x
		JOIN character ON character.id = x.character_id
		ORDER BY x.count DESC, character.name ASC
	`, rankingId); err != nil {
		return nil, err
	}
	return rankingItems, nil
}


text:
      チャンネル情報取得

      <input type="text" class="form-control" ng-model="channelInformation.idChannel">

        <button type="button" class="btn btn-default" ng-click="channelInformation.getChannel()"></button>

      取得結果

      Country: {{channelInformation.channelItem.country}}

      Description: {{channelInformation.channelItem.description}}

      PublishedAt: {{channelInformation.channelItem.publishedAt}}

      Title: {{channelInformation.channelItem.title}}


text:
package org.stringtemplate.v4;

import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.Token;
import org.stringtemplate.v4.compiler.CompiledST;
import org.stringtemplate.v4.compiler.Compiler;
import org.stringtemplate.v4.compiler.FormalArgument;
import org.stringtemplate.v4.compiler.GroupLexer;
import org.stringtemplate.v4.compiler.GroupParser;
import org.stringtemplate.v4.compiler.STException;
import org.stringtemplate.v4.gui.STViz;
import org.stringtemplate.v4.misc.Aggregate;
import org.stringtemplate.v4.misc.AggregateModelAdaptor;
import org.stringtemplate.v4.misc.ErrorManager;
import org.stringtemplate.v4.misc.ErrorType;
import org.stringtemplate.v4.misc.MapModelAdaptor;
import org.stringtemplate.v4.misc.Misc;
import org.stringtemplate.v4.misc.ObjectModelAdaptor;
import org.stringtemplate.v4.misc.STModelAdaptor;
import org.stringtemplate.v4.misc.TypeRegistry;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/** A directory or directory tree of {@code .st} template files and/or group files.
 *  Individual template files contain formal template definitions. In a sense,
 *  it's like a single group file broken into multiple files, one for each template.
 *  ST v3 had just the pure template inside, not the template name and header.
 *  Name inside must match filename (minus suffix).
 */

public class STGroup {
    public static final String GROUP_FILE_EXTENSION;
    public static final String TEMPLATE_FILE_EXTENSION;
    static {
        GROUP_FILE_EXTENSION = ".stg";
        TEMPLATE_FILE_EXTENSION = ".st";
    }

    /** When we use key as a value in a dictionary, this is how we signify. */

    public static final String DICT_KEY = "key";
    public static final String DEFAULT_KEY = "default";

    /** The encoding to use for loading files. Defaults to UTF-8. */
    public String encoding = "UTF-8";

    /** Every group can import templates/dictionaries from other groups.
     *  The list must be synchronized (see {@link STGroup#importTemplates}).
     */
    protected final List<STGroup> imports = Collections.synchronizedList(new ArrayList<STGroup>());
    protected final List<STGroup> importsToClearOnUnload = Collections.synchronizedList(new ArrayList<STGroup>());
    public char delimiterStartChar = '<'; // Use <expr> by default
    public char delimiterStopChar = '>';

    /** Maps template name to {@link CompiledST} object. This map is synchronized. */
    protected Map<String, CompiledST> templates = Collections.synchronizedMap(new LinkedHashMap<String, CompiledST>());

    /** Maps dictionary names to {@link Map} objects representing the dictionaries
     *  defined by the user like {@code typeInitMap ::= ["int":"0"]}.
     */
    protected Map<String, Map<String, Object>> dictionaries = Collections.synchronizedMap(new HashMap<String, Map<String, Object>>());

    /** A dictionary that allows people to register a renderer for
     *  a particular kind of object for any template evaluated relative to this
     *  group.  For example, a date should be formatted differently depending
     *  on the locale.  You can set {@code Date.class} to an object whose
     *  {@code toString(Object)} method properly formats a {@link Date} attribute
     *  according to locale.  Or you can have a different renderer object
     *  for each locale.
     *

     *  Order of addition is recorded and matters.  If more than one
     *  renderer works for an object, the first registered has priority.

     *

     *  Renderer associated with type {@code t} works for object {@code o} if

     *

     *  t.isAssignableFrom(o.getClass()) // would assignment t = o work?
     *

     *  So it works if {@code o} is subclass or implements {@code t}.
     *

     *  This structure is synchronized.

     */
    protected Map<Class<?>, AttributeRenderer> renderers;

    /** A dictionary that allows people to register a model adaptor for
     *  a particular kind of object (subclass or implementation). Applies
     *  for any template evaluated relative to this group.
     *

     *  ST initializes with model adaptors that know how to pull
     *  properties out of {@link Object}s, {@link Map}s, and {@link ST}s.

     *

     *  The last one you register gets priority; do least to most specific.

     */
    protected final Map<Class<?>, ModelAdaptor> adaptors;
    {
        TypeRegistry<ModelAdaptor> registry = new TypeRegistry<ModelAdaptor>();
        registry.put(Object.class, new ObjectModelAdaptor());
        registry.put(ST.class, new STModelAdaptor());
        registry.put(Map.class, new MapModelAdaptor());
        registry.put(Aggregate.class, new AggregateModelAdaptor());
        adaptors = Collections.synchronizedMap(registry);
    }

    /** Used to indicate that the template doesn't exist.
     *  Prevents duplicate group file loads and unnecessary file checks.
     */

    protected static final CompiledST NOT_FOUND_ST = new CompiledST();
    public static final ErrorManager DEFAULT_ERR_MGR = new ErrorManager();

    /** Watch loading of groups and templates. */
    public static boolean verbose = false;

    /**
     * For debugging with {@link STViz}. Records where in code an {@link ST} was
     * created and where code added attributes.
     */
    public static boolean trackCreationEvents = false;

    /** v3 compatibility; used to iterate across {@link Map#values()} instead of
     *  v4's default {@link Map#keySet()}.
     *  But to convert ANTLR templates, it's too hard to find without
     *  static typing in templates.
     */
    public boolean iterateAcrossValues = false;
    public static STGroup defaultGroup = new STGroup();

    /** The {@link ErrorManager} for entire group; all compilations and executions.
     *  This gets copied to parsers, walkers, and interpreters.
     */
    public ErrorManager errMgr = STGroup.DEFAULT_ERR_MGR;

    public STGroup() { }

    public STGroup(char delimiterStartChar, char delimiterStopChar) {
        this.delimiterStartChar = delimiterStartChar;
        this.delimiterStopChar = delimiterStopChar;
    }

    /** The primary means of getting an instance of a template from this
     *  group. Names must be absolute, fully-qualified names like {@code /a/b}.
     */

    public ST getInstanceOf(String name) {
        if ( name==null ) return null;
        if ( verbose ) System.out.println(getName()+".getInstanceOf("+name+")");
        if ( name.charAt(0) !='/' ) name = "/"+name;
        CompiledST c = lookupTemplate(name);
        if ( c!=null ) {
            return createStringTemplate(c);
        }
        return null;
    }

    protected ST getEmbeddedInstanceOf(Interpreter interp, InstanceScope scope, String name) {
        String fullyQualifiedName = name;
        if ( name.charAt(0) !='/' ) {
            fullyQualifiedName = scope.st.impl.prefix+name;
        }
        if ( verbose ) System.out.println("getEmbeddedInstanceOf("+fullyQualifiedName+")");
        ST st = getInstanceOf(fullyQualifiedName);
        if ( st==null ) {
            errMgr.runTimeError(interp, scope, ErrorType.NO_SUCH_TEMPLATE, fullyQualifiedName);
            return createStringTemplateInternally(new CompiledST());
        }
        // this is only called internally. wack any debug ST create events
        if ( trackCreationEvents ) {
            st.debugState.newSTEvent = null; // toss it out
        }
        return st;
    }

    /** Create singleton template for use with dictionary values. */

    public ST createSingleton(Token templateToken) {
        String template;
        if ( templateToken.getType()==GroupParser.BIGSTRING || templateToken.getType()==GroupParser.BIGSTRING_NO_NL ) {
            template = Misc.strip(templateToken.getText(), 2);
        }
        else {
            template = Misc.strip(templateToken.getText(), 1);
        }

        CompiledST impl = compile(getFileName(), null, null, template, templateToken);
        ST st = createStringTemplateInternally(impl);
        st.groupThatCreatedThisInstance = this;
        st.impl.hasFormalArgs = false;
        st.impl.name = ST.UNKNOWN_NAME;
        st.impl.defineImplicitlyDefinedTemplates(this);
        return st;
    }

    /** Is this template defined in this group or from this group below?
     *  Names must be absolute, fully-qualified names like {@code /a/b}.
     */

    public boolean isDefined(String name) {
        return lookupTemplate(name) !=null;
    }

    /** Look up a fully-qualified name. */

    public CompiledST lookupTemplate(String name) {
        if ( name.charAt(0) !='/' ) name = "/"+name;
        if ( verbose ) System.out.println(getName()+".lookupTemplate("+name+")");
        CompiledST code = rawGetTemplate(name);
        if ( code==NOT_FOUND_ST ) {
            if ( verbose ) System.out.println(name+" previously seen as not found");
            return null;
        }
        // try to load from disk and look up again
        if ( code==null ) code = load(name);
        if ( code==null ) code = lookupImportedTemplate(name);
        if ( code==null ) {
            if ( verbose ) System.out.println(name+" recorded not found");
            templates.put(name, NOT_FOUND_ST);
        }
        if ( verbose ) if ( code!=null ) System.out.println(getName()+".lookupTemplate("+name+") found");
        return code;
    }

    /**
     * Unload all templates, dictionaries and import relationships, but leave
     * renderers and adaptors. This essentially forces the next call to
     * {@link #getInstanceOf} to reload templates. Call {@code unload()} on each
     * group in the {@link #imports} list, and remove all elements in
     * {@link #importsToClearOnUnload} from {@link #imports}.
     */

    public synchronized void unload() {
        templates.clear();
        dictionaries.clear();
        for (STGroup imp : imports) {
            imp.unload();
        }

        for (STGroup imp : importsToClearOnUnload) {
            imports.remove(imp);
        }
        importsToClearOnUnload.clear();
    }

    /** Load st from disk if directory or load whole group file if .stg file (then
     *  return just one template). {@code name} is fully-qualified.
     */

    protected CompiledST load(String name) {
        return null;
    }

    /** Force a load if it makes sense for the group. */

    public void load() {
    }

    protected CompiledST lookupImportedTemplate(String name) {
        if ( imports.size()==0 ) return null;
        for (STGroup g : imports) {
            if ( verbose ) System.out.println("checking "+g.getName()+" for imported "+name);
            CompiledST code = g.lookupTemplate(name);
            if ( code!=null ) {
                if ( verbose ) System.out.println(g.getName()+".lookupImportedTemplate("+name+") found");
                return code;
            }
        }
        if ( verbose ) System.out.println(name+" not found in "+getName()+" imports");
        return null;
    }

    public CompiledST rawGetTemplate(String name) {
        return templates.get(name);
    }

    public Map<String, Object> rawGetDictionary(String name) {
        return dictionaries.get(name);
    }

    public boolean isDictionary(String name) {
        return dictionaries.get(name) !=null;
    }

    /** for testing */

    public CompiledST defineTemplate(String templateName, String template) {
        if ( templateName.charAt(0) !='/' ) templateName = "/"+templateName;
        try {
            CompiledST impl = defineTemplate(templateName,
                                             new CommonToken(GroupParser.ID, templateName),
                                             null,
                                             template,
                                             null);
            return impl;
        }
        catch (STException se) {
            // we have reported the error; the exception just blasts us
            // out of parsing this template
        }
        return null;
    }

    /** for testing */

    public CompiledST defineTemplate(String name, String argsS, String template) {
        if ( name.charAt(0) !='/' ) name = "/"+name;
        String[] args = argsS.split(",");
        List<FormalArgument> a = new ArrayList<FormalArgument>();
        for (String arg : args) {
            a.add(
                new FormalArgument(arg)
            );
        }
        return defineTemplate(name, new CommonToken(GroupParser.ID, name), a, template, null);
    }

    public CompiledST defineTemplate(String fullyQualifiedTemplateName,
                                     Token nameT,
                                     List<FormalArgument> args,
                                     String template, Token templateToken) {
        if ( verbose ) System.out.println("defineTemplate("+fullyQualifiedTemplateName+")");
        if ( fullyQualifiedTemplateName==null || fullyQualifiedTemplateName.length()==0 ) {
            throw new IllegalArgumentException("empty template name");
        }
        if ( fullyQualifiedTemplateName.indexOf('.')>=0 ) {
            throw new IllegalArgumentException("cannot have '.' in template names");
        }
        template = Misc.trimOneStartingNewline(template);
        template = Misc.trimOneTrailingNewline(template);
        // compile, passing in templateName as enclosing name for any embedded regions
        CompiledST code = compile(getFileName(),
                                  fullyQualifiedTemplateName,
                                  args,
                                  template,
                                  templateToken);
        code.name = fullyQualifiedTemplateName;
        rawDefineTemplate(fullyQualifiedTemplateName, code, nameT);
        code.defineArgDefaultValueTemplates(this);
        code.defineImplicitlyDefinedTemplates(this); // define any anonymous subtemplates
        return code;
    }

    /** Make name and alias for target.  Replace any previous definition of name. */

    public CompiledST defineTemplateAlias(Token aliasT, Token targetT) {
        String alias = aliasT.getText();
        String target = targetT.getText();
        CompiledST targetCode = rawGetTemplate("/"+target);
        if ( targetCode==null ) {
            errMgr.compileTimeError(ErrorType.ALIAS_TARGET_UNDEFINED, null, aliasT, alias, target);
            return null;
        }
        rawDefineTemplate("/"+alias, targetCode, aliasT);
        return targetCode;
    }

    public CompiledST defineRegion(String enclosingTemplateName, Token regionT, String template, Token templateToken) {
        String name = regionT.getText();
        template = Misc.trimOneStartingNewline(template);
        template = Misc.trimOneTrailingNewline(template);
        CompiledST code = compile(getFileName(), enclosingTemplateName, null, template, templateToken);
        String mangled = getMangledRegionName(enclosingTemplateName, name);
        if ( lookupTemplate(mangled)==null ) {
            errMgr.compileTimeError(ErrorType.NO_SUCH_REGION,
                                    templateToken,
                                    regionT,
                                    enclosingTemplateName,
                                    name);
            return new CompiledST();
        }
        code.name = mangled;
        code.isRegion = true;
        code.regionDefType = ST.RegionType.EXPLICIT;
        code.templateDefStartToken = regionT;
        rawDefineTemplate(mangled, code, regionT);
        code.defineArgDefaultValueTemplates(this);
        code.defineImplicitlyDefinedTemplates(this);
        return code;
    }

    public void defineTemplateOrRegion(String fullyQualifiedTemplateName, String regionSurroundingTemplateName, Token templateToken, String template, Token nameToken, List<FormalArgument> args) {
        try {
            if ( regionSurroundingTemplateName!=null ) {
                defineRegion(regionSurroundingTemplateName, nameToken, template, templateToken);
            }
            else {
                defineTemplate(fullyQualifiedTemplateName, nameToken, args, template, templateToken);
            }
        }
        catch (STException e) {
            // after getting syntax error in a template, we emit msg
            // and throw exception to blast all the way out to here.
        }
    }

    public void rawDefineTemplate(String name, CompiledST code, Token defT) {
        CompiledST prev = rawGetTemplate(name);
        if ( prev!=null ) {
            if ( !prev.isRegion ) {
                errMgr.compileTimeError(ErrorType.TEMPLATE_REDEFINITION, null, defT);
                return;
            }
            else {
                if ( code.regionDefType!= ST.RegionType.IMPLICIT && prev.regionDefType==ST.RegionType.EMBEDDED ) {
                    errMgr.compileTimeError(ErrorType.EMBEDDED_REGION_REDEFINITION, null, defT, getUnMangledTemplateName(name));
                    return;
                }
                else if ( code.regionDefType==ST.RegionType.IMPLICIT || prev.regionDefType==ST.RegionType.EXPLICIT ) {
                         errMgr.compileTimeError(ErrorType.REGION_REDEFINITION,
                                                 null,
                                                 defT,
                                                 getUnMangledTemplateName(name));
                         return;
                }
            }
        }
        code.nativeGroup = this;
        code.templateDefStartToken = defT;
        templates.put(name, code);
    }

    public void undefineTemplate(String name) {
        templates.remove(name);
    }

    /** Compile a template. */

    public CompiledST compile(String srcName, String name, List<FormalArgument> args, String template, Token templateToken) // for error location {
        //System.out.println("STGroup.compile: "+enclosingTemplateName);
        Compiler c = new Compiler(this);
        return c.compile(srcName, name, args, template, templateToken);
    }

    /** The {@code "foo"} of {@code t() ::= "<@foo()>"} is mangled to
     *  {@code "/region__/t__foo"}
     */

    public static String getMangledRegionName(String enclosingTemplateName, String name) {
        if ( enclosingTemplateName.charAt(0) !='/' ) {
            enclosingTemplateName = '/'+enclosingTemplateName;
        }
        return "/region__"+enclosingTemplateName+"__"+name;
    }

    /** Return {@code "t.foo"} from {@code "/region__/t__foo"} */

    public static String getUnMangledTemplateName(String mangledName) {
        String t = mangledName.substring("/region__".length(), mangledName.lastIndexOf("__"));
        String r = mangledName.substring(mangledName.lastIndexOf("__") +2, mangledName.length());
        return t+
               '.' +r;
    }

    /** Define a map for this group.
     *

     * Not thread safe...do not keep adding these while you reference them.

     */

    public void defineDictionary(String name, Map<String, Object> mapping) {
        dictionaries.put(name, mapping);
    }

    /**
     * Make this group import templates/dictionaries from {@code g}.
     *

     * On unload imported templates are unloaded but stay in the {@link #imports} list.

     */

    public void importTemplates(STGroup g) {
        importTemplates(g, false);
    }

    /** Import template files, directories, and group files.
     *  Priority is given to templates defined in the current group;
     *  this, in effect, provides inheritance. Polymorphism is in effect so
     *  that if an inherited template references template {@code t()} then we
     *  search for {@code t()} in the subgroup first.
     *

     *  Templates are loaded on-demand from import dirs.  Imported groups are
     *  loaded on-demand when searching for a template.

     *

     *  The listener of this group is passed to the import group so errors
     *  found while loading imported element are sent to listener of this group.

     *

     *  On unload imported templates are unloaded and removed from the imports
     *  list.

     *

     *  This method is called when processing import statements specified in
     *  group files. Use {@link #importTemplates(STGroup)} to import templates
     *  'programmatically'.

     */

    public void importTemplates(Token fileNameToken) {
        if ( verbose ) System.out.println("importTemplates("+fileNameToken.getText()+")");
        String fileName = fileNameToken.getText();
        // do nothing upon syntax error
        if ( fileName==null || fileName.equals("<missing STRING>") ) return;
        fileName = Misc.strip(fileName, 1);

        //System.out.println("import "+fileName);
        boolean isGroupFile = fileName.endsWith(GROUP_FILE_EXTENSION);
        boolean isTemplateFile = fileName.endsWith(TEMPLATE_FILE_EXTENSION);
        boolean isGroupDir = !(isGroupFile || isTemplateFile);
        STGroup g = null;

        // search path is: working dir, g.stg's dir, CLASSPATH
        URL thisRoot = getRootDirURL();
        URL fileUnderRoot;
//      System.out.println("thisRoot="+thisRoot);
        try {
            fileUnderRoot = new URL(thisRoot+"/"+fileName);
        }
        catch (MalformedURLException mfe) {
            errMgr.internalError(null, "can't build URL for "+thisRoot+"/"+fileName, mfe);
            return;
        }
        if ( isTemplateFile ) {
            g = new STGroup(delimiterStartChar, delimiterStopChar);
            g.setListener(this.getListener());
            URL fileURL;
            if ( Misc.urlExists(fileUnderRoot) ) fileURL = fileUnderRoot;
            else fileURL = getURL(fileName); // try CLASSPATH
            if ( fileURL!=null ) {
                try {
                    InputStream s = fileURL.openStream();
                    ANTLRInputStream templateStream = new ANTLRInputStream(s);
                    templateStream.name = fileName;
                    CompiledST code = g.loadTemplateFile("/", fileName, templateStream);
                    if ( code==null ) g = null;
                }
                catch (IOException ioe) {
                    errMgr.internalError(null, "can't read from "+fileURL, ioe);
                    g = null;
                }
            }
            else {
                g = null;
            }
        }
        else if ( isGroupFile ) {
            //System.out.println("look for fileUnderRoot: "+fileUnderRoot);
            if ( Misc.urlExists(fileUnderRoot) ) {
                g = new STGroupFile(fileUnderRoot, encoding, delimiterStartChar, delimiterStopChar);
                g.setListener(this.getListener());
            }
            else {
                g = new STGroupFile(fileName, delimiterStartChar, delimiterStopChar);
                g.setListener(this.getListener());
            }
        }
        else if ( isGroupDir ) {
//          System.out.println("try dir "+fileUnderRoot);
                 if ( Misc.urlExists(fileUnderRoot) ) {
                     g = new STGroupDir(fileUnderRoot, encoding, delimiterStartChar, delimiterStopChar);
                     g.setListener(this.getListener());
                 }
                 else {
                // try in CLASSPATH
//              System.out.println("try dir in CLASSPATH "+fileName);
                     g = new STGroupDir(fileName, delimiterStartChar, delimiterStopChar);
                     g.setListener(this.getListener());
                 }
             }
        if ( g==null ) {
            errMgr.compileTimeError(ErrorType.CANT_IMPORT, null, fileNameToken, fileName);
        }
        else {
            importTemplates(g, true);
        }
    }

    protected void importTemplates(STGroup g, boolean clearOnUnload) {
        if ( g==null ) return;
        imports.add(g);
        if ( clearOnUnload ) {
            importsToClearOnUnload.add(g);
        }
    }

    public List<STGroup> getImportedGroups() {
        return imports;
    }

    /** Load a group file with full path {@code fileName}; it's relative to root by {@code prefix}. */

    public void loadGroupFile(String prefix, String fileName) {
        if ( verbose ) System.out.println(this.getClass().getSimpleName()+".loadGroupFile(group-file-prefix="+prefix+", fileName="+fileName+")");
        GroupParser parser;
        try {
            URL f = new URL(fileName);
            ANTLRInputStream fs = new ANTLRInputStream(f.openStream(), encoding);
            GroupLexer lexer = new GroupLexer(fs);
            fs.name = fileName;
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            parser = new GroupParser(tokens);
            parser.group(this, prefix);
        }
        catch (Exception e) {
            errMgr.IOError(null, ErrorType.CANT_LOAD_GROUP_FILE, e, fileName);
        }
    }

    /** Load template file into this group using absolute {@code fileName}. */

    public CompiledST loadAbsoluteTemplateFile(String fileName) {
        ANTLRFileStream fs;
        try {
            fs = new ANTLRFileStream(fileName, encoding);
            fs.name = fileName;
        }
        catch (IOException ioe) {
            // doesn't exist
            //errMgr.IOError(null, ErrorType.NO_SUCH_TEMPLATE, ioe, fileName);
            return null;
        }
        return loadTemplateFile("", fileName, fs);
    }

    /** Load template stream into this group. {@code unqualifiedFileName} is
     *  {@code "a.st"}. The {@code prefix} is path from group root to
     *  {@code unqualifiedFileName} like {@code "/subdir"} if file is in
     *  {@code /subdir/a.st}.
     */

    public CompiledST loadTemplateFile(String prefix, String unqualifiedFileName, CharStream templateStream) {
        GroupLexer lexer = new GroupLexer(templateStream);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        GroupParser parser = new GroupParser(tokens);
        parser.group = this;
        lexer.group = this;
        try {
            parser.templateDef(prefix);
        }
        catch (RecognitionException re) {
            errMgr.groupSyntaxError(ErrorType.SYNTAX_ERROR, unqualifiedFileName, re, re.getMessage());
        }

        String templateName = Misc.getFileNameNoSuffix(unqualifiedFileName);
        if ( prefix!=null && prefix.length()>0 ) templateName = prefix+templateName;
        CompiledST impl = rawGetTemplate(templateName);
        impl.prefix = prefix;
        return impl;
    }

    /**
     * Add an adaptor for a kind of object so ST knows how to pull properties
     * from them. Add adaptors in increasing order of specificity. ST adds
     * {@link Object}, {@link Map}, {@link ST}, and {@link Aggregate} model
     * adaptors for you first. Adaptors you add have priority over default
     * adaptors.
     *

     * If an adaptor for type {@code T} already exists, it is replaced by the
     * {@code adaptor} argument.

     *

     * This must invalidate cache entries, so set your adaptors up before
     * calling {@link ST#render} for efficiency.

     */

    public void registerModelAdaptor(Class<?> attributeType, ModelAdaptor adaptor) {
        if ( attributeType.isPrimitive() ) {
            throw new IllegalArgumentException("can't register ModelAdaptor for primitive type "+attributeType.getSimpleName());
        }
        adaptors.put(attributeType, adaptor);
    }

    public ModelAdaptor getModelAdaptor(Class<?> attributeType) {
        return adaptors.get(attributeType);
    }

    /** Register a renderer for all objects of a particular "kind" for all
     *  templates evaluated relative to this group.  Use {@code r} to render if
     *  object in question is an instance of {@code attributeType}.  Recursively
     *  set renderer into all import groups.
     */

    public void registerRenderer(Class<?> attributeType, AttributeRenderer r) {
        registerRenderer(attributeType, r, true);
    }

    public void registerRenderer(Class<?> attributeType, AttributeRenderer r, boolean recursive) {
        if ( attributeType.isPrimitive() ) {
            throw new IllegalArgumentException("can't register renderer for primitive type "+attributeType.getSimpleName());
        }
        if ( renderers==null ) {
            renderers = Collections.synchronizedMap(new TypeRegistry<AttributeRenderer>());
        }
        renderers.put(attributeType, r);
        if ( recursive ) {
            load(); // make sure imports exist (recursively)
            for (STGroup g : imports) {
                g.registerRenderer(attributeType, r, true);
            }
        }
    }

    /** Get renderer for class {@code T} associated with this group.
     *

     *  For non-imported groups and object-to-render of class {@code T}, use renderer
     *  (if any) registered for {@code T}.  For imports, any renderer
     *  set on import group is ignored even when using an imported template.
     *  You should set the renderer on the main group
     *  you use (or all to be sure).  I look at import groups as
     *  "helpers" that should give me templates and nothing else. If you
     *  have multiple renderers for {@code String}, say, then just make uber combined
     *  renderer with more specific format names.

     */

    public AttributeRenderer getAttributeRenderer(Class<?> attributeType) {
        if ( renderers==null ) {
            return null;
        }
        return renderers.get(attributeType);
    }

    public ST createStringTemplate(CompiledST impl) {
        ST st = new ST();
        st.impl = impl;
        st.groupThatCreatedThisInstance = this;
        if ( impl.formalArguments!=null ) {
            st.locals = new Object[impl.formalArguments.size()];
            Arrays.fill(st.locals, ST.EMPTY_ATTR);
        }
        return st;
    }

    /** Differentiate so we can avoid having creation events for regions,
     *  map operations, and other implicit "new ST" events during rendering.
     */

    public ST createStringTemplateInternally(CompiledST impl) {
        ST st = createStringTemplate(impl);
        if ( trackCreationEvents && st.debugState!=null ) {
            st.debugState.newSTEvent = null; // toss it out
        }
        return st;
    }

    public ST createStringTemplateInternally(ST proto) {
        return new ST(proto); // no need to wack debugState; not set in ST(proto).
    }

    public String getName() {
        return "<no name>;";
    }

    public String getFileName() {
        return null;
    }

    /** Return root dir if this is group dir; return dir containing group file
     *  if this is group file.  This is derived from original incoming
     *  dir or filename.  If it was absolute, this should come back
     *  as full absolute path.  If only a URL is available, return URL of
     *  one dir up.
     */

    public URL getRootDirURL() {
        return null;
    }

    public URL getURL(String fileName) {
        URL url;
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        url = cl.getResource(fileName);
        if ( url==null ) {
            cl = this.getClass().getClassLoader();
            url = cl.getResource(fileName);
        }
        return url;
    }

    @Override
    public String toString() {
        return getName();
    }

    public String show() {
        StringBuilder buf = new StringBuilder();
        if ( imports.size() != 0 ) buf.append(" : "+imports);
        for (String name : templates.keySet()) {
            CompiledST c = rawGetTemplate(name);
            if ( c.isAnonSubtemplate || c==NOT_FOUND_ST ) continue;
            int slash = name.lastIndexOf('/');
            name = name.substring(slash+1, name.length());
            buf.append(name);
            buf.append('(');
            if ( c.formalArguments!=null ) buf.append(Misc.join(c.formalArguments.values().iterator(), ","));
            buf.append(')');
            buf.append(" ::= <<"+Misc.newline);
            buf.append(c.template+Misc.newline);
            buf.append(">>"+Misc.newline);
        }
        return buf.toString();
    }

    public STErrorListener getListener() {
        return errMgr.listener;
    }

    public void setListener(STErrorListener listener) {
        errMgr = new ErrorManager(listener);
    }

    public Set<String> getTemplateNames() {
        load();
        HashSet<String> result = new HashSet<String>();
        for (Map.Entry<String, CompiledST> e : templates.entrySet()) {
            if ( e.getValue() != NOT_FOUND_ST ) {
                result.add(e.getKey());
            }
        }
        return result;
    }
}


text:
from django.conf import settings
from django.conf.urls import url
from django.conf.urls import include
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns
from django.views.decorators.csrf import csrf_exempt

from rest_framework.schemas import get_schema_view
import api_v1
from .views import IndexPageView

app_name = getattr(settings, 'SITE_NAME')
admin.site.site_header = '{} Admin'.format(app_name)

urlpatterns = i18n_patterns(
    url(r'^admin/', admin.site.urls),
    prefix_default_language=True
)

i18n_aware_patterns = ([
    url(r'^$', IndexPageView.as_view(), name='index_page_view'),
], 'i18n_portal')

urlpatterns += i18n_patterns(
    url(r'^', include(i18n_aware_patterns, namespace='i18n_portal')),
    prefix_default_language=True
)

urlpatterns += [
    url(r'^api/v1/', include(('api_v1.urls', 'api_v1'), namespace='api_v1')),
]

if settings.DEBUG:
    if getattr(settings, 'DEBUG_ENABLE_TOOLBAR', False):
        import debug_toolbar
        urlpatterns += [
            url(r'^__debug__/', include(debug_toolbar.urls)),
        ]


text:
/**
 *

 * The {@link edu.teco.dnd.eclipse.deployEditor.DeployEditor} is responsible for generating
 * {@link edu.teco.dnd.deploy.Distribution}s as well as {@link edu.teco.dnd.deploy.Deploy}ing them. The editor handles
 * .blocks files which are created by the {@link edu.teco.dnd.graphiti.DiagramTypeProvider}.
 *

 */
package edu.teco.dnd.eclipse.deployEditor;


text:
using System;
using EFDemo.DAL;

namespace EFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new DemoContext())
            {
                var students = ctx.Students;

                // print students
                foreach (var student in students)
                {
                    Console.WriteLine(student);
                }
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}


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

<title>Uses of Class com.rallydev.rest.util.Fetch (Rally Rest API for Java 2.2)</title>
<meta name="date" content="2016-03-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.rallydev.rest.util.Fetch

Packages that use Fetch

Package
Description

com.rallydev.rest.request

Provides objects for encoding requests to the Rest API.

Uses of Fetch in com.rallydev.rest.request

Methods in com.rallydev.rest.request that return Fetch

Modifier and Type
Method and Description

Fetch
CollectionUpdateRequest.getFetch()

Get the current list of fields to be returned on the updated object.

Fetch
GetRequest.getFetch()

Get the current list of fields to be returned on the retrieved object.

Fetch
UpdateRequest.getFetch()

Get the current list of fields to be returned on the updated object.

Fetch
CreateRequest.getFetch()

Get the current list of fields to be returned on the created object.

Fetch
QueryRequest.getFetch()

Get the current list of fields to be returned on the matching objects.

Methods in com.rallydev.rest.request with parameters of type Fetch

Modifier and Type
Method and Description

void
CollectionUpdateRequest.setFetch(Fetch fetch)

Set the current list of fields to be returned on the updated object.

void
GetRequest.setFetch(Fetch fetch)

Set the current list of fields to be returned on the retrieved object.

void
UpdateRequest.setFetch(Fetch fetch)

Set the current list of fields to be returned on the updated object.

void
CreateRequest.setFetch(Fetch fetch)

Set the current list of fields to be returned on the created object.

void
QueryRequest.setFetch(Fetch fetch)

Set the current list of fields to be returned on the matching objects.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.jena.tdb.StoreConnection (Apache Jena TDB)</title>
<meta name="date" content="2015-12-08">
<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

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.jena.tdb.StoreConnection

Packages that use StoreConnection

Package
Description

org.apache.jena.tdb

Uses of StoreConnection in org.apache.jena.tdb

Methods in org.apache.jena.tdb that return StoreConnection

Modifier and Type
Method and Description

static StoreConnection
StoreConnection.createMemUncached()

Return a StoreConnection backed by in-memory
 datastructures (for testing).

static StoreConnection
StoreConnection.getExisting(org.apache.jena.tdb.base.file.Location location)

Return the StoreConnection if one already exists for this location, else
 return null

static StoreConnection
StoreConnection.make(org.apache.jena.tdb.base.file.Location location)

Make a StoreConnection based on any StoreParams at the location or the system defaults.

static StoreConnection
StoreConnection.make(org.apache.jena.tdb.base.file.Location location,
    org.apache.jena.tdb.setup.StoreParams params)

Return a StoreConnection for a particular connection.

static StoreConnection
StoreConnection.make(String location)

Obtain a StoreConnection for a particular location

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Licenced under the Apache License, Version 2.0


text: Filename sanitizer


text:
<!DOCTYPE html>
<html>
  <head>
    <title>R (The Roguelike Library) Demo</title>
    <link rel="stylesheet" type="text/css" href="css/r.css">
  </head>
  <body>
    <canvas id="terminal"></canvas>
  </body>
  <script data-main="app" type="text/javascript" src="node_modules/requirejs/require.js"></script>
</html>


text:
"""
Presence analyzer unit tests.
"""
import os.path
import json
import datetime
import unittest

from presence_analyzer import main, views, utils

TEST_DATA_CSV = os.path.join(
    os.path.dirname(__file__), '..', '..', 'runtime', 'data', 'test_data.csv'
)
TEST_DATA_XML = os.path.join(
    os.path.dirname(__file__), '..', '..', 'runtime', 'data', 'test_users.xml'
)

# pylint: disable=E1103
class PresenceAnalyzerViewsTestCase(unittest.TestCase):
    """
    Views tests.
    """

    def setUp(self):
        """
        Before each test, set up a environment.
        """
        main.app.config.update({'DATA_CSV': TEST_DATA_CSV})
        main.app.config.update({'DATA_XML': TEST_DATA_XML})
        self.client = main.app.test_client()

    def tearDown(self):
        """
        Get rid of unused objects after each test.
        """
        pass

    def test_mainpage(self):
        """
        Test main page redirect.
        """
        resp = self.client.get('/')
        self.assertEqual(resp.status_code, 302)
        assert resp.headers['Location'].endswith('/presenceweekday')

    def test_presenceweekday(self):
        """
        Test presence weekday page.
        """
        resp = self.client.get('/chart/presenceweekday')
        self.assertEqual(resp.status_code, 200)

    def test_meantime(self):
        """
        Test meantime page.
        """
        resp = self.client.get('/chart/meantime')
        self.assertEqual(resp.status_code, 200)

    def test_presencestartend(self):
        """
        Test presence start end page.
        """
        resp = self.client.get('/chart/presencestartend')
        self.assertEqual(resp.status_code, 200)

    def test_api_users(self):
        """
        Test users listing.
        """
        resp = self.client.get('/api/v1/users')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.content_type, 'application/json')
        data = json.loads(resp.data)
        details = utils.get_details()
        self.assertEqual(len(data), len(details))
        self.assertDictEqual(data[0], {
            'user_id': 10,
            'name': 'Adam P.',
            'avatar': '/api/images/users/10'
        })
        self.assertDictEqual(data[1], {
            'user_id': 11,
            'name': 'Adrian K.',
            'avatar': '/api/images/users/11'
        })
        self.assertDictEqual(data[2], {
            'user_id': 12,
            'name': 'Agata J.',
            'avatar': '/api/images/users/12'
        })

    def test_api_view(self):
        """
        Test avatar path.
        """
        resp = self.client.get('/api/v1/get_avatar/0')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.content_type, 'application/json')
        path = json.loads(resp.data)
        self.assertEqual(path, None)
        resp = self.client.get('/api/v1/get_avatar/10')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.content_type, 'application/json')
        path = json.loads(resp.data)
        self.assertEqual(path, '/api/images/users/10')

    def test_api_mean_time_weekday(self):
        """
        Test mean time weeklday listing.
        """
        resp = self.client.get('/api/v1/mean_time_weekday/1')
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.data)
        self.assertEqual(len(data), 0)
        resp = self.client.get('/api/v1/mean_time_weekday/10')
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.data)
        self.assertEqual(len(data), 7)
        self.assertIn('Mon', data[0])
        self.assertIn('Sun', data[-1])

    def test_api_presence_weekday(self):
        """
        Test presence weekday listing.
        """
        resp = self.client.get('/api/v1/presence_weekday/1')
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.data)
        self.assertEqual(len(data), 0)
        resp = self.client.get('/api/v1/presence_weekday/10')
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.data)
        self.assertEqual(len(data), 8)
        self.assertIn('Mon', data[1])
        self.assertIn('Sun', data[-1])

    def test_api_presence_start_end(self):
        """
        Test presence start end listing.
        """
        resp = self.client.get('/api/v1/presence_start_end/1')
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.data)
        self.assertEqual(len(data), 0)
        resp = self.client.get('/api/v1/presence_start_end/10')
        self.assertEqual(resp.status_code, 200)
        data = json.loads(resp.data)
        self.assertEqual(len(data), 7)
        self.assertIn('Mon', data[0])
        self.assertIn('Sun', data[-1])

class PresenceAnalyzerUtilsTestCase(unittest.TestCase):
    """
    Utility functions tests.
    """

    def setUp(self):
        """
        Before each test, set up a environment.
        """
        main.app.config.update({'DATA_CSV': TEST_DATA_CSV})
        main.app.config.update({'DATA_XML': TEST_DATA_XML})

    def tearDown(self):
        """
        Get rid of unused objects after each test.
        """
        pass

    def test_get_data(self):
        """
        Test parsing of CSV file.
        """
        data = utils.get_data()
        self.assertIsInstance(data, dict)
        self.assertItemsEqual(data.keys(), [10, 11])
        sample_date = datetime.date(2013, 9, 10)
        self.assertIn(sample_date, data[10])
        self.assertItemsEqual(data[10][sample_date].keys(), ['start', 'end'])
        self.assertEqual(data[10][sample_date]['start'],
                         datetime.time(9, 39, 5))

    def test_get_details(self):
        details = utils.get_details()
        self.assertIsInstance(details, dict)
        self.assertIsInstance(details[10], dict)
        self.assertItemsEqual(details.keys(), [10, 11, 12])
        self.assertItemsEqual(details[10].keys(), ['name', 'avatar'])
        self.assertEqual(details[11]['name'], 'Adrian K.')
        self.assertEqual(details[11]['avatar'], '/api/images/users/11')

    def test_group_by_weekday(self):
        """
        Test weekly grouped.
        """
        data = utils.get_data()
        sample_gbw = utils.group_by_weekday(data[10])
        expected_gbw = {
            0: [],
            1: [30047],
            2: [24465],
            3: [23705],
            4: [],
            5: [],
            6: [],
        }
        self.assertDictEqual(sample_gbw, expected_gbw)

    def test_group_by_weekday_with_points(self):
        """
        Test weekly grouped with points.
        """
        data = utils.get_data()
        sample_gbwp = utils.group_by_weekday_with_points(data[10])
        expected_gbwp = {
            0: [[], []],
            1: [[34745], [64792]],
            2: [[33592], [58057]],
            3: [[38926], [62631]],
            4: [[], []],
            5: [[], []],
            6: [[], []],
        }
        self.assertDictEqual(sample_gbwp, expected_gbwp)

    def test_seconds_since_midnight(self):
        """
        Test calculating seconds since midnight.
        """
        sample_time = datetime.time(0, 0, 0)
        sample_ssm = utils.seconds_since_midnight(sample_time)
        self.assertEqual(sample_ssm, 0)
        self.assertIsInstance(sample_ssm, int)
        sample_time = datetime.time(15, 9, 50)
        sample_ssm = utils.seconds_since_midnight(sample_time)
        self.assertEqual(sample_ssm, 54590)
        self.assertIsInstance(sample_ssm, int)

    def test_interval(self):
        """
        Test interval of time from two points.
        """
        sample_start = datetime.time(5, 0, 0)
        sample_end = datetime.time(15, 0, 0)
        sample_interval = utils.interval(sample_start, sample_end)
        self.assertEqual(sample_interval, 36000)
        self.assertIsInstance(sample_interval, int)
        sample_start = datetime.time(2, 15, 50)
        sample_end = datetime.time(22, 0, 0)
        sample_interval = utils.interval(sample_start, sample_end)
        self.assertEqual(sample_interval, 71050)
        self.assertIsInstance(sample_interval, int)

    def test_mean(self):
        """
        Test mean of list elements.
        """
        sample_mean = utils.mean([])
        self.assertEqual(sample_mean, 0)
        sample_mean = utils.mean([6, 3, 0])
        self.assertEqual(sample_mean, 3.0)
        self.assertIsInstance(sample_mean, float)
        sample_mean = utils.mean([5432.1, 1234.42, 876.23])
        self.assertEqual(sample_mean, 2514.25)
        self.assertIsInstance(sample_mean, float)
        sample_mean = utils.mean([5432.1, 1234.42, 876.23])
        self.assertNotEqual(sample_mean, 7542.75)

def suite():
    """
    Default test suite.
    """
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(PresenceAnalyzerViewsTestCase))
    suite.addTest(unittest.makeSuite(PresenceAnalyzerUtilsTestCase))
    return suite

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


text:
[![XML](https://cdn.rawgit.com/crystal/xml/master/.autocode/icon.svg)](https://hub.crystal.sh/crystal/xml)

convert XML objects into XML strings

## Install

First install [Autocode](https://crystal.sh):

```sh
# Choose one:
npm install autocode-cli -g
brew install autocode # mac users
git clone https://github.com/crystal/autocode-cli
```

Then use Autocode to install [crystal/xml](https://hub.crystal.sh/crystal/xml):

```sh
autocode install crystal/xml
```

## Exports

## Help & Support

- [crystal/xml on Crystal Hub](https://hub.crystal.sh/crystal/xml)
- [Report Issues](https://github.com/crystal/xml/issues)
- [Crystal Website](https://crystal.sh)
- [Gitter](https://gitter.im/crystal/autocode)
- [Twitter](https://twitter.com/crystalcodegen)
- [Facebook](https://facebook.com/crystalcodegen)


text:
Simple component for phone-call link on mobile devices. Demo [http://aleksmiller.github.io/puph/](http://aleksmiller.github.io/puph/)

##Usage
* Download [css](https://raw.github.com/aleksmiller/puph/master/puph.css) and [js](https://raw.github.com/aleksmiller/puph/master/puph.js)
* Use stylesheet `<link rel="stylesheet" href="/path/to/css/puph.css">` and JS `<script src="/path/to/js/puph.js"></script>`. Make sure to use correct paths /path/to/css/ and /path/to/js/
* Create link `<a href="tel:+380000000000" class="puph">CALL</a>`
* Create new instance in your JavaScript code `var puph = new Puph();`. Or directly in HTML `<script>var puph = new Puph();</script>`, in that case it's important to init Puph script **after** puph.js file is used
* Show only on mobile devices `<a href="tel:+380000000000" class="puph" data-mobile="true">CALL</a>`

##License
Puph is released under the [MIT License](https://raw.github.com/aleksmiller/puph/master/LICENSE)


text:
namespace ceres {

class Problem;

// Interface for non-linear least squares solvers.
class Solver {
 public:
  virtual ~Solver();

  // The options structure contains, not surprisingly, options that control how
  // the solver operates. The defaults should be suitable for a wide range of
  // problems; however, better performance is often obtainable with tweaking.
  //
  // The constants are defined inside types.h
  struct Options {
    // Default constructor that sets up a generic sparse problem.
    Options() {
      trust_region_strategy_type = LEVENBERG_MARQUARDT;
      max_num_iterations = 50;
      max_solver_time_in_seconds = 1e9;
      num_threads = 1;
      initial_trust_region_radius = 1e4;
      max_trust_region_radius = 1e16;
      min_trust_region_radius = 1e-32;
      min_relative_decrease = 1e-3;
      lm_min_diagonal = 1e-6;
      lm_max_diagonal = 1e32;
      max_num_consecutive_invalid_steps = 5;
      function_tolerance = 1e-6;
      gradient_tolerance = 1e-10;
      parameter_tolerance = 1e-8;

#if defined(CERES_NO_SUITESPARSE) && defined(CERES_NO_CXSPARSE)
      linear_solver_type = DENSE_QR;
#else
      linear_solver_type = SPARSE_NORMAL_CHOLESKY;
#endif

      preconditioner_type = JACOBI;

      sparse_linear_algebra_library = SUITE_SPARSE;
#if defined(CERES_NO_SUITESPARSE) && !defined(CERES_NO_CXSPARSE)
      sparse_linear_algebra_library = CX_SPARSE;
#endif

      num_linear_solver_threads = 1;
      num_eliminate_blocks = 0;
      ordering_type = NATURAL;

#if defined(CERES_NO_SUITESPARSE)
      use_block_amd = false;
#else
      use_block_amd = true;
#endif

      linear_solver_min_num_iterations = 1;
      linear_solver_max_num_iterations = 500;
      eta = 1e-1;
      jacobi_scaling = true;
      logging_type = PER_MINIMIZER_ITERATION;
      minimizer_progress_to_stdout = false;
      return_initial_residuals = false;
      return_initial_gradient = false;
      return_initial_jacobian = false;
      return_final_residuals = false;
      return_final_gradient = false;
      return_final_jacobian = false;
      lsqp_dump_directory = "/tmp";
      lsqp_dump_format_type = TEXTFILE;
      check_gradients = false;
      gradient_check_relative_precision = 1e-8;
      numeric_derivative_relative_step_size = 1e-6;
      update_state_every_iteration = false;
    }

    // Minimizer options ----------------------------------------

    TrustRegionStrategyType trust_region_strategy_type;

    // Maximum number of iterations for the minimizer to run for.
    int max_num_iterations;

    // Maximum time for which the minimizer should run for.
    double max_solver_time_in_seconds;

    // Number of threads used by Ceres for evaluating the cost and
    // jacobians.
    int num_threads;

    // Trust region minimizer settings.
    double initial_trust_region_radius;
    double max_trust_region_radius;

    // Minimizer terminates when the trust region radius becomes
    // smaller than this value.
    double min_trust_region_radius;

    // Lower bound for the relative decrease before a step is
    // accepted.
    double min_relative_decrease;

    // For the Levenberg-Marquadt algorithm, the scaled diagonal of
    // the normal equations J'J is used to control the size of the
    // trust region. Extremely small and large values along the
    // diagonal can make this regularization scheme
    // fail. lm_max_diagonal and lm_min_diagonal, clamp the values of
    // diag(J'J) from above and below. In the normal course of
    // operation, the user should not have to modify these parameters.
    double lm_min_diagonal;
    double lm_max_diagonal;

    // Sometimes due to numerical conditioning problems or linear
    // solver flakiness, the trust region strategy may return a
    // numerically invalid step that can be fixed by reducing the
    // trust region size. So the TrustRegionMinimizer allows for a few
    // successive invalid steps before it declares NUMERICAL_FAILURE.
    int max_num_consecutive_invalid_steps;

    // Minimizer terminates when
    //
    //   (new_cost - old_cost) < function_tolerance * old_cost;
    //
    double function_tolerance;

    // Minimizer terminates when
    //
    //   max_i |gradient_i| < gradient_tolerance * max_i|initial_gradient_i|
    //
    // This value should typically be 1e-4 * function_tolerance.
    double gradient_tolerance;

    // Minimizer terminates when
    //
    //   |step|_2 <= parameter_tolerance * ( |x|_2 +  parameter_tolerance)
    //
    double parameter_tolerance;

    // Linear least squares solver options -------------------------------------

    LinearSolverType linear_solver_type;

    // Type of preconditioner to use with the iterative linear solvers.
    PreconditionerType preconditioner_type;

    // Ceres supports using multiple sparse linear algebra libraries
    // for sparse matrix ordering and factorizations. Currently,
    // SUITE_SPARSE and CX_SPARSE are the valid choices, depending on
    // whether they are linked into Ceres at build time.
    SparseLinearAlgebraLibraryType sparse_linear_algebra_library;

    // Number of threads used by Ceres to solve the Newton
    // step. Currently only the SPARSE_SCHUR solver is capable of
    // using this setting.
    int num_linear_solver_threads;

    // For Schur reduction based methods, the first 0 to num blocks are
    // eliminated using the Schur reduction. For example, when solving
    // traditional structure from motion problems where the parameters are in
    // two classes (cameras and points) then num_eliminate_blocks would be the
    // number of points.
    //
    // This parameter is used in conjunction with the ordering.
    // Applies to: Preprocessor and linear least squares solver.
    int num_eliminate_blocks;

    // Internally Ceres reorders the parameter blocks to help the
    // various linear solvers. This parameter allows the user to
    // influence the re-ordering strategy used. For structure from
    // motion problems use SCHUR, for other problems NATURAL (default)
    // is a good choice. In case you wish to specify your own ordering
    // scheme, for example in conjunction with num_eliminate_blocks,
    // use USER.
    OrderingType ordering_type;

    // The ordering of the parameter blocks. The solver pays attention
    // to it if the ordering_type is set to USER and the vector is
    // non-empty.
    vector<double*> ordering;

    // By virtue of the modeling layer in Ceres being block oriented,
    // all the matrices used by Ceres are also block oriented. When
    // doing sparse direct factorization of these matrices (for
    // SPARSE_NORMAL_CHOLESKY, SPARSE_SCHUR and ITERATIVE in
    // conjunction with CLUSTER_TRIDIAGONAL AND CLUSTER_JACOBI
    // preconditioners), the fill-reducing ordering algorithms can
    // either be run on the block or the scalar form of these matrices.
    // Running it on the block form exposes more of the super-nodal
    // structure of the matrix to the factorization routines. Setting
    // this parameter to true runs the ordering algorithms in block
    // form. Currently this option only makes sense with
    // sparse_linear_algebra_library = SUITE_SPARSE.
    bool use_block_amd;

    // Minimum number of iterations for which the linear solver should
    // run, even if the convergence criterion is satisfied.
    int linear_solver_min_num_iterations;

    // Maximum number of iterations for which the linear solver should
    // run. If the solver does not converge in less than
    // linear_solver_max_num_iterations, then it returns
    // MAX_ITERATIONS, as its termination type.
    int linear_solver_max_num_iterations;

    // Forcing sequence parameter. The truncated Newton solver uses
    // this number to control the relative accuracy with which the
    // Newton step is computed.
    //
    // This constant is passed to ConjugateGradientsSolver which uses
    // it to terminate the iterations when
    //
    //  (Q_i - Q_{i-1})/Q_i < eta/i
    double eta;

    // Normalize the jacobian using Jacobi scaling before calling
    // the linear least squares solver.
    bool jacobi_scaling;

    // Logging options ---------------------------------------------------------

    LoggingType logging_type;

    // By default the Minimizer progress is logged to VLOG(1), which
    // is sent to STDERR depending on the vlog level. If this flag is
    // set to true, and logging_type is not SILENT, the logging output
    // is sent to STDOUT.
    bool minimizer_progress_to_stdout;

    bool return_initial_residuals;
    bool return_initial_gradient;
    bool return_initial_jacobian;

    bool return_final_residuals;
    bool return_final_gradient;
    bool return_final_jacobian;

    // List of iterations at which the optimizer should dump the
    // linear least squares problem to disk. Useful for testing and
    // benchmarking. If empty (default), no problems are dumped.
    //
    // This is ignored if protocol buffers are disabled.
    vector<int> lsqp_iterations_to_dump;
    string lsqp_dump_directory;
    DumpFormatType lsqp_dump_format_type;

    // Finite differences options ----------------------------------------------

    // Check all jacobians computed by each residual block with finite
    // differences. This is expensive since it involves computing the
    // derivative by normal means (e.g. user specified, autodiff,
    // etc), then also computing it using finite differences. The
    // results are compared, and if they differ substantially, details
    // are printed to the log.
    bool check_gradients;

    // Relative precision to check for in the gradient checker. If the
    // relative difference between an element in a jacobian exceeds
    // this number, then the jacobian for that cost term is dumped.
    double gradient_check_relative_precision;

    // Relative shift used for taking numeric derivatives. For finite
    // differencing, each dimension is evaluated at slightly shifted
    // values; for the case of central difference, this is what gets
    // evaluated:
    //
    //   delta = numeric_derivative_relative_step_size;
    //   f_initial  = f(x)
    //   f_forward  = f((1 + delta) * x)
    //   f_backward = f((1 - delta) * x)
    //
    // The finite differencing is done along each dimension. The
    // reason to use a relative (rather than absolute) step size is
    // that this way, numeric differentation works for functions where
    // the arguments are typically large (e.g. 1e9) and when the
    // values are small (e.g. 1e-5). It is possible to construct
    // "torture cases" which break this finite difference heuristic,
    // but they do not come up often in practice.
    //
    // TODO(keir): Pick a smarter number than the default above! In
    // theory a good choice is sqrt(eps) * x, which for doubles means
    // about 1e-8 * x. However, I have found this number too
    // optimistic. This number should be exposed for users to change.
    double numeric_derivative_relative_step_size;

    // If true, the user's parameter blocks are updated at the end of
    // every Minimizer iteration, otherwise they are updated when the
    // Minimizer terminates. This is useful if, for example, the user
    // wishes to visualize the state of the optimization every
    // iteration.
    bool update_state_every_iteration;

    // Callbacks that are executed at the end of each iteration of the
    // Minimizer. An iteration may terminate midway, either due to
    // numerical failures or because one of the convergence tests has
    // been satisfied. In this case none of the callbacks are
    // executed.

    // Callbacks are executed in the order that they are specified in
    // this vector. By default, parameter blocks are updated only at
    // the end of the optimization, i.e when the Minimizer
    // terminates. This behaviour is controlled by
    // update_state_every_variable. If the user wishes to have access
    // to the update parameter blocks when his/her callbacks are
    // executed, then set update_state_every_iteration to true.
    //
    // The solver does NOT take ownership of these pointers.
    vector<IterationCallback*> callbacks;
  };

  struct Summary {
    Summary();

    // A brief one line description of the state of the solver after
    // termination.
    string BriefReport() const;

    // A full multiline description of the state of the solver after
    // termination.
    string FullReport() const;

    // Minimizer summary -------------------------------------------------
    SolverTerminationType termination_type;

    // If the solver did not run, or there was a failure, a
    // description of the error.
    string error;

    // Cost of the problem before and after the optimization. See
    // problem.h for definition of the cost of a problem.
    double initial_cost;
    double final_cost;

    // The part of the total cost that comes from residual blocks that
    // were held fixed by the preprocessor because all the parameter
    // blocks that they depend on were fixed.
    double fixed_cost;

    // Vectors of residuals before and after the optimization. The
    // entries of these vectors are in the order in which
    // ResidualBlocks were added to the Problem object.
    //
    // Whether the residual vectors are populated with values is
    // controlled by Solver::Options::return_initial_residuals and
    // Solver::Options::return_final_residuals respectively.
    vector<double> initial_residuals;
    vector<double> final_residuals;

    // Gradient vectors, before and after the optimization.  The rows
    // are in the same order in which the ParameterBlocks were added
    // to the Problem object.
    //
    // NOTE: Since AddResidualBlock adds ParameterBlocks to the
    // Problem automatically if they do not already exist, if you wish
    // to have explicit control over the ordering of the vectors, then
    // use Problem::AddParameterBlock to explicitly add the
    // ParameterBlocks in the order desired.
    //
    // Whether the vectors are populated with values is controlled by
    // Solver::Options::return_initial_gradient and
    // Solver::Options::return_final_gradient respectively.
    vector<double> initial_gradient;
    vector<double> final_gradient;

    // Jacobian matrices before and after the optimization. The rows
    // of these matrices are in the same order in which the
    // ResidualBlocks were added to the Problem object. The columns
    // are in the same order in which the ParameterBlocks were added
    // to the Problem object.
    //
    // NOTE: Since AddResidualBlock adds ParameterBlocks to the
    // Problem automatically if they do not already exist, if you wish
    // to have explicit control over the column ordering of the
    // matrix, then use Problem::AddParameterBlock to explicitly add
    // the ParameterBlocks in the order desired.
    //
    // The Jacobian matrices are stored as compressed row sparse
    // matrices. Please see ceres/crs_matrix.h for more details of the
    // format.
    //
    // Whether the Jacboan matrices are populated with values is
    // controlled by Solver::Options::return_initial_jacobian and
    // Solver::Options::return_final_jacobian respectively.
    CRSMatrix initial_jacobian;
    CRSMatrix final_jacobian;

    vector<IterationSummary> iterations;

    int num_successful_steps;
    int num_unsuccessful_steps;

    // When the user calls Solve, before the actual optimization
    // occurs, Ceres performs a number of preprocessing steps. These
    // include error checks, memory allocations, and reorderings. This
    // time is accounted for as preprocessing time.
    double preprocessor_time_in_seconds;

    // Time spent in the TrustRegionMinimizer.
    double minimizer_time_in_seconds;

    // After the Minimizer is finished, some time is spent in
    // re-evaluating residuals etc. This time is accounted for in the
    // postprocessor time.
    double postprocessor_time_in_seconds;

    // Some total of all time spent inside Ceres when Solve is called.
    double total_time_in_seconds;

    // Preprocessor summary.
    int num_parameter_blocks;
    int num_parameters;
    int num_residual_blocks;
    int num_residuals;

    int num_parameter_blocks_reduced;
    int num_parameters_reduced;
    int num_residual_blocks_reduced;
    int num_residuals_reduced;

    int num_eliminate_blocks_given;
    int num_eliminate_blocks_used;

    int num_threads_given;
    int num_threads_used;

    int num_linear_solver_threads_given;
    int num_linear_solver_threads_used;

    LinearSolverType linear_solver_type_given;
    LinearSolverType linear_solver_type_used;

    PreconditionerType preconditioner_type;
    OrderingType ordering_type;

    TrustRegionStrategyType trust_region_strategy_type;
    SparseLinearAlgebraLibraryType sparse_linear_algebra_library;
  };

  // Once a least squares problem has been built, this function takes
  // the problem and optimizes it based on the values of the options
  // parameters. Upon return, a detailed summary of the work performed
  // by the preprocessor, the non-linear minmizer and the linear
  // solver are reported in the summary object.
  virtual void Solve(const Options& options,
                     Problem* problem,
                     Solver::Summary* summary);
};

// Helper function which avoids going through the interface.
void Solve(const Solver::Options& options,
           Problem* problem,
           Solver::Summary* summary);

}  // namespace ceres

#endif  // CERES_PUBLIC_SOLVER_H_


text:
package body

import constraint.Constraint
import scala.scalajs.js
import scala.scalajs.js.annotation.JSGlobal
import scala.scalajs.js.|
import geometry.{Bounds, Vector}
import org.querki.jsext.{JSOptionBuilder, OptMap, noOpts}

/**
  * Created by Dan on 3/24/2017.
  */

@js.native
trait WorldDefinition extends CompositeDefinition {
  var gravity: Vector = js.native
  var bounds: Bounds = js.native
}
object WorldDefinition extends WorldDefinitionBuilder(noOpts)
class WorldDefinitionBuilder(val dict:OptMap) extends JSOptionBuilder[WorldDefinition, WorldDefinitionBuilder](new WorldDefinitionBuilder(_)) {
  def gravity(v:Vector) = jsOpt("gravity", v)
  def bounds(v:Bounds) = jsOpt("bounds", v)
}

@js.native
@JSGlobal("Matter.World")
class World extends Composite {
  var gravity: Vector = js.native
  var bounds: Bounds = js.native
}

@js.native
@JSGlobal("Matter.World")
object World extends js.Object {
  def add(world: World, body: Body | js.Array[Body] | Composite | js.Array[Composite] | Constraint | js.Array[Constraint]): World = js.native
  def addBody(world: World, body: Body): World = js.native
  def addComposite(world: World, composite: Composite): World = js.native
  def addConstraint(world: World, constraint: Constraint): World = js.native
  def clear(world: World, keepStatic: Boolean): Unit = js.native
  def create(options: WorldDefinition): World = js.native
  def create(): World = js.native
}


text:
A Javascript library for getting random colors, a random color of a specific family, or just an enumeration of "known colors."

## Usage
Huey contains 143 different named colors. It also maintains an internal closed list of used colors incase you don't want to repeat any.

The "unused" parameter is a boolean to determine whether or not to allow the generated color to be used again.

* Huey.colors: is an enumeration of known color names and their hex values
* Huey.GetRandomColorName(unused): returns a random color name string
* Huey.GetRandomColorHex(unused): returns a random color's hex value
* Huey.GetRandomColor(unused): returns an object containing the name and hex value of a random color
* Huey.GetRandomRed(unused): returns an object containing the name and hex value of a random red
* Huey.GetRandomPink(unused): returns an object containing the name and hex value of a random pink
* Huey.GetRandomOrange(unused): returns an object containing the name and hex value of a random orange
* Huey.GetRandomYellow(unused): returns an object containing the name and hex value of a random yellow
* Huey.GetRandomPurple(unused): returns an object containing the name and hex value of a random purple
* Huey.GetRandomGreen(unused): returns an object containing the name and hex value of a random green
* Huey.GetRandomBlue(unused): returns an object containing the name and hex value of a random blue
* Huey.GetRandomBrown(unused): returns an object containing the name and hex value of a random brown
* Huey.GetRandomWhite(unused): returns an object containing the name and hex value of a random white
* Huey.GetRandomGrey(unused): returns an object containing the name and hex value of a random grey
* Huey.ClearUsedList(): clears the used colors list, necessary when the functions start returning null


text:
package org.wso2.carbon.identity.application.common.model;

import org.apache.axiom.om.OMElement;
import org.apache.commons.collections.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Application/Identity Provider permission and role configuration.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "PermissionsAndRoleConfig")
public class PermissionsAndRoleConfig implements Serializable {

    private static final long serialVersionUID = 784509684062361809L;

    @XmlElementWrapper(name = "Permissions")
    @XmlElement(name = "ApplicationPermission")
    private ApplicationPermission[] permissions = new ApplicationPermission[0];

    @XmlElementWrapper(name = "RoleMappings")
    @XmlElement(name = "RoleMapping")
    private RoleMapping[] roleMappings = new RoleMapping[0];

    @XmlElementWrapper(name = "IdpRoles")
    @XmlElement(name = "IdpRole")
    private String[] idpRoles = new String[0];

    /*
     * <PermissionsAndRoleConfig> <Permissions></Permissions> <RoleMappings></RoleMappings>
     * <IdpRoles></IdpRoles> </PermissionsAndRoleConfig>
     */
    public static PermissionsAndRoleConfig build(OMElement permissionsAndRoleConfigOM) {
        PermissionsAndRoleConfig permissionsAndRoleConfig = new PermissionsAndRoleConfig();

        if (permissionsAndRoleConfigOM == null) {
            return permissionsAndRoleConfig;
        }

        Iterator<?> iter = permissionsAndRoleConfigOM.getChildElements();

        while (iter.hasNext()) {

            OMElement element = (OMElement) (iter.next());
            String elementName = element.getLocalName();

            if ("Permissions".equals(elementName)) {
                Iterator<?> permissionsIter = element.getChildElements();
                List<ApplicationPermission> permissionsArrList = new ArrayList<ApplicationPermission>();

                if (permissionsIter != null) {
                    while (permissionsIter.hasNext()) {
                        OMElement permissionsElement = (OMElement) (permissionsIter.next());
                        ApplicationPermission appPermission = ApplicationPermission
                                .build(permissionsElement);
                        if (appPermission != null) {
                            permissionsArrList.add(appPermission);
                        }
                    }
                }

                if (CollectionUtils.isNotEmpty(permissionsArrList)) {
                    ApplicationPermission[] permissionsArr = permissionsArrList
                            .toArray(new ApplicationPermission[0]);
                    permissionsAndRoleConfig.setPermissions(permissionsArr);
                }
            }

            if ("RoleMappings".equals(elementName)) {
                Iterator<?> roleMappingsIter = element.getChildElements();
                ArrayList<RoleMapping> roleMappingsArrList = new ArrayList<RoleMapping>();

                if (roleMappingsIter != null) {
                    while (roleMappingsIter.hasNext()) {
                        OMElement roleMappingsElement = (OMElement) (roleMappingsIter.next());
                        RoleMapping roleMapping = RoleMapping.build(roleMappingsElement);
                        if (roleMapping != null) {
                            roleMappingsArrList.add(roleMapping);
                        }
                    }
                }

                if (CollectionUtils.isNotEmpty(roleMappingsArrList)) {
                    RoleMapping[] roleMappingsArr = roleMappingsArrList.toArray(new RoleMapping[0]);
                    permissionsAndRoleConfig.setRoleMappings(roleMappingsArr);
                }

            }

            if ("IdpRoles".equals(elementName)) {
                Iterator<?> idpRolesIter = element.getChildElements();
                List<String> roleMappingsArrList = new ArrayList<String>();

                while (idpRolesIter.hasNext()) {
                    OMElement idpRolesElement = (OMElement) (idpRolesIter.next());
                    if (idpRolesElement.getText() != null) {
                        roleMappingsArrList.add(idpRolesElement.getText());
                    }
                }

                if (CollectionUtils.isNotEmpty(roleMappingsArrList)) {
                    String[] idpRolesArr = roleMappingsArrList.toArray(new String[0]);
                    permissionsAndRoleConfig.setIdpRoles(idpRolesArr);
                }
            }
        }

        return permissionsAndRoleConfig;
    }

    /**
     * @return
     */
    public ApplicationPermission[] getPermissions() {
        return permissions;
    }

    /**
     * @param permissions
     */
    public void setPermissions(ApplicationPermission[] permissions) {
        this.permissions = permissions;
    }

    /**
     * @return
     */
    public RoleMapping[] getRoleMappings() {
        return roleMappings;
    }

    /**
     * @param roleMappings
     */
    public void setRoleMappings(RoleMapping[] roleMappings) {
        this.roleMappings = roleMappings;
    }

    public String[] getIdpRoles() {
        return idpRoles;
    }

    public void setIdpRoles(String[] idpRoles) {
        this.idpRoles = idpRoles;
    }
}


text:
layout: page
title: Orange Inc. Seminar
date: 2016-05-24
author: Noah Boyle
tags: weekly links, java
status: published
summary: Donec rutrum, arcu a varius viverra.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 11/02/2016
  endDate: 11/05/2016
  ctyhocn: BUFWVHX
  groupCode: OIS
published: true
---
Etiam convallis odio eget odio interdum efficitur. Pellentesque magna felis, fringilla ut volutpat auctor, feugiat nec neque. Etiam in blandit quam, et ornare felis. Vestibulum lorem tellus, sagittis ut placerat eu, rhoncus ac turpis. Donec volutpat semper orci, vitae semper sem viverra in. Cras dapibus porttitor nisl, eu tincidunt lorem consequat a. Donec justo ex, suscipit id nulla non, rhoncus fringilla diam. Morbi rhoncus orci lacus, pellentesque tristique enim finibus non. Mauris finibus orci a est rhoncus tincidunt. Phasellus aliquam malesuada nibh, eu imperdiet turpis ultrices at. Integer a vulputate enim. Vestibulum pellentesque posuere lorem at finibus. Praesent commodo turpis eget nibh gravida tristique. Sed sem risus, ullamcorper id pharetra eget, faucibus quis ante.

* Cras nec felis vehicula, volutpat tortor ut, convallis leo
* Sed a ipsum consequat, bibendum enim eget, vestibulum mi
* Sed eu arcu et elit vehicula malesuada sit amet at turpis
* Pellentesque lacinia mi placerat metus molestie finibus.

Integer odio ex, malesuada vel lacinia at, laoreet id lacus. In condimentum massa nec nunc accumsan cursus. Phasellus hendrerit diam vel faucibus consequat. Vivamus vestibulum tempor ligula, quis sollicitudin odio tincidunt ut. In vel tincidunt eros, in imperdiet diam. Nullam libero lectus, condimentum finibus libero et, commodo sollicitudin velit. Donec tincidunt arcu ut magna laoreet aliquet. Aenean ac lectus iaculis, consequat neque tempus, egestas justo. Vivamus hendrerit fermentum imperdiet. Nulla pretium odio a nibh auctor iaculis.


text:
package validator

import (
	"errors"
	"strconv"
	"strings"
)

func strSplit(text string, sep string) (string, string) {
	length := len(text)
	if index := strings.Index(text, sep); index == -1 {
		return text, ""
	} else {
		return text[0:index], text[index+1 : length]
	}
}

func strReplace(text string, replace string, value string) string {
	return strings.Replace(text, replace, value, 1)
}

func strToInt(value string) (int64, error) {
	number, err := strconv.ParseInt(value, 0, 64)
	if err != nil {
		return 0, err
	}
	return number, nil
}

func strToFloat(value string) (float64, error) {
	number, err := strconv.ParseFloat(value, 64)
	if err != nil {
		return 0.0, err
	}
	return number, nil
}

func strToUint(value string) (uint64, error) {
	number, err := strconv.ParseUint(value, 0, 64)
	if err != nil {
		return 0, err
	}
	return number, nil
}

func splitAtt(value string) (string, string) {
	val := strings.Split(value, ",")
	return val[0], val[1]
}

func addProperties(p *Property) {
	if properties == nil {
		properties = []*Property{p}
	} else {
		properties = append(properties, p)
	}
}

func isValid() bool {
	return errMsg == nil
}

func addErrMsg(property string, message string) {
	if errMsg == nil {
		errMsg = map[string][]string{}
	}

	if errMsg[property] == nil {
		errMsg[property] = []string{message}
	} else {
		errMsg[property] = append(errMsg[property], message)
	}
}

func propertyNamesToJson() {
	if errMsg == nil {
		return
	}

	for _, p := range properties {
		if errMsg[p.Name] != nil && p.NameJson != "" {
			errMsg[p.NameJson] = errMsg[p.Name]
			delete(errMsg, p.Name)
		}
	}
}

func getProperty(name string) (*Property, error) {
	for _, p := range properties {
		if p.Name == name {
			return p, nil
		}
	}

	return nil, errors.New("No property " + name + "found")
}

func getPropertyJsonName(p *Property) string {
	if p.NameJson == "" {
		return p.Name
	}
	return p.NameJson
}


text:
layout: post
title: "Трек недели: Malang Party - Dil Jalay"
category: "Linker"
---

В Пакистане живет и развивается активная рок и инди-тусовка. Открыл для себя группу Malang Party из Исламабада, у которой буквально несколько песен. Dil Jalay — самая классная.