text:
<!--- Licensed to the Apache Software Foundation (ASF) under one -->
<!--- or more contributor license agreements.  See the NOTICE file -->
<!--- distributed with this work for additional information -->
<!--- regarding copyright ownership.  The ASF licenses this file -->
<!--- to you under the Apache License, Version 2.0 (the -->
<!--- "License"); you may not use this file except in compliance -->
<!--- with the License.  You may obtain a copy of the License at -->

<!---   http://www.apache.org/licenses/LICENSE-2.0 -->

<!--- Unless required by applicable law or agreed to in writing, -->
<!--- software distributed under the License is distributed on an -->
<!--- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -->
<!--- KIND, either express or implied.  See the License for the -->
<!--- specific language governing permissions and limitations -->
<!--- under the License. -->

# Spectral Normalization GAN

This example implements [Spectral Normalization for Generative Adversarial Networks](https://arxiv.org/abs/1802.05957) based on [CIFAR10](https://www.cs.toronto.edu/~kriz/cifar.html) dataset.

## Usage

Example runs and the results:

```python
python train.py --use-gpu --data-path=data
```

* Note that the program would download the CIFAR10 for you

`python train.py --help` gives the following arguments:

```bash
optional arguments:
  -h, --help            show this help message and exit
  --data-path DATA_PATH
                        path of data.
  --batch-size BATCH_SIZE
                        training batch size. default is 64.
  --epochs EPOCHS       number of training epochs. default is 100.
  --lr LR               learning rate. default is 0.0001.
  --lr-beta LR_BETA     learning rate for the beta in margin based loss.
                        default is 0.5.
  --use-gpu             use gpu for training.
  --clip_gr CLIP_GR     Clip the gradient by projecting onto the box. default
                        is 10.0.
  --z-dim Z_DIM         dimension of the latent z vector. default is 100.
```

## Result

![SN-GAN](sn_gan_output.png)

## Learned Spectral Normalization

![alt text](https://github.com/taki0112/Spectral_Normalization-Tensorflow/blob/master/assests/sn.png)

## Reference

[Simple Tensorflow Implementation](https://github.com/taki0112/Spectral_Normalization-Tensorflow)


text:
function 	Spawn( entityKeyValues )

	faceless_ability = thisEntity:FindAbilityByName("faceless_void_time_walk")
	thisEntity:SetContextThink( "SteamtankThink", SteamtankThink , 1)
	thisEntity:SetContextThink( "AIOther", AIOther , 0.5)
	print("Starting AI for "..thisEntity:GetUnitName().." "..thisEntity:GetEntityIndex())

end
-------

function AIOther()

    if thisEntity:IsNull() or not thisEntity:IsAlive() then
        return nil
    end

    local point = Vector(-2752, -1280, 129.354)

    if (point - thisEntity:GetOrigin()):Length() > 1200 then
        thisEntity:MoveToPosition(point)
    end

    return 0.5;
end

function SteamtankThink()

	if faceless_ability:IsFullyCastable() then
		local units = FindUnitsInRadius( thisEntity:GetTeamNumber(), thisEntity:GetAbsOrigin(), nil, 1000, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE, FIND_CLOSEST, false)

		if units ~= nil then
			if #units >= 1 then

				local index = RandomInt( 1, #units )
				local target = units[index]

				thisEntity:CastAbilityOnPosition(target:GetAbsOrigin(),faceless_ability, -1)
				print("Elder Titan wants to cast call earth_splitter, ".. #units .." enemy near.")
			else
				--print("No units found to cast the spell on")
			end
		end
	end
	return 1
end

redpajama_set_name: RedPajamaGithub


text:
package model

type Karte struct {
	Code string `json:"cardCode"`

	Categories []string `json:"cardCategories"`

	NameGer string `json:"cardNameGer"`
	NameJa  string `json:"cardNameJa"`
	NameEn  string `json:"cardNameEn"`

	Description string `json:"cardDescription"`
	EffectType  string `json:"effectType"`

	MonsterAttr    string `json:"monsterAttribute"`
	MonsterRank    string `json:"monsterRank"`
	MonsterAttack  string `json:"monsterAttack"`
	MonsterDefense string `json:"monsterDefense"`

	PictureUrl string `json:"pictureUrl"`
	WikiUrl    string `json:"wikiUrl"`
}


text:
package me.innectic.permissify.spigot.utils;

import org.bukkit.permissions.PermissionAttachment;

import java.util.*;

/**
 * @author Innectic
 * @since 07/21/2018
 */
public class AttachmentManager {

    private static Map<UUID, Map<String, PermissionAttachment>> attachments = new HashMap<>();

    public Optional<PermissionAttachment> getAttachment(UUID uuid, Optional<String> groupName) {
        return Optional.ofNullable(attachments.getOrDefault(uuid, new HashMap<>()).getOrDefault(groupName.orElse(""), null));
    }

    public void setAttachment(UUID uuid, PermissionAttachment attachment, Optional<String> groupName) {
        Map<String, PermissionAttachment> attachments = new HashMap<>();
        attachments.put(groupName.orElse(""), attachment);
        AttachmentManager.attachments.put(uuid, attachments);
    }

    public void removeAttachment(UUID uuid) {
        attachments.remove(uuid);
    }

    public Collection<PermissionAttachment> getAllAttachmentsForPlayer(UUID uuid) {
        return attachments.get(uuid).values();
    }

    public void resetAllPermissibles(UUID uuid) {
        attachments.get(uuid).values().forEach(attachment -> attachment.getPermissions().keySet().forEach(attachment::unsetPermission));
        attachments.remove(uuid);
    }
}


text:
import { map, omit } from 'lodash';
import Partner from '../partner';
import AggregationCount from './aggregation_count';
import {
  GraphQLObjectType,
  GraphQLEnumType,
  GraphQLList,
  GraphQLInt,
} from 'graphql';

export const PartnersAggregation = new GraphQLEnumType({
  name: 'PartnersAggregation',
  values: {
    LOCATION: {
      value: '',
    },
    CATEGORY: {
      value: 'partner_category',
    },
    TOTAL: {
      value: 'total',
    },
  },
});

export const PartnersAggregationResultsType = new GraphQLObjectType({
  name: 'PartnersAggregationResults',
  description: 'The results for one of the requested aggregations',
  fields: () => ({
    slice: {
      type: PartnersAggregation,
    },
    counts: {
      type: new GraphQLList(AggregationCount.type),
      resolve: ({ counts }) => map(counts, AggregationCount.resolve),
    },
  }),
});

export const FilterPartnersType = new GraphQLObjectType({
  name: 'FilterPartners',
  fields: () => ({
    hits: {
      type: new GraphQLList(Partner.type),
    },
    total: {
      type: GraphQLInt,
      resolve: ({ aggregations }) => aggregations.total.value,
    },
    aggregations: {
      type: new GraphQLList(PartnersAggregationResultsType),
      resolve: ({ aggregations }) =>
        map(omit(aggregations, ['total']), (counts, slice) => ({ slice, counts })),
    },
  }),
});


text:
/*
 * Command line parser for tar.
 */

#include "bsdtar_platform.h"
__FBSDID("$FreeBSD$");

#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif

#include "bsdtar.h"
#include "err.h"

/*
 * Short options for tar.  Please keep this sorted.
 */
static const char *short_options
	= "aBb:C:cf:HhI:JjkLlmnOoPpqrSs:T:tUuvW:wX:xyZz";

/*
 * Long options for tar.  Please keep this list sorted.
 *
 * The symbolic names for options that lack a short equivalent are
 * defined in bsdtar.h.  Also note that so far I've found no need
 * to support optional arguments to long options.  That would be
 * a small change to the code below.
 */

static const struct bsdtar_option {
	const char *name;
	int required;      /* 1 if this option requires an argument. */
	int equivalent;    /* Equivalent short option. */
} tar_longopts[] = {
	{ "absolute-paths",       0, 'P' },
	{ "append",               0, 'r' },
	{ "auto-compress",        0, 'a' },
	{ "b64encode",            0, OPTION_B64ENCODE },
	{ "block-size",           1, 'b' },
	{ "bunzip2",              0, 'j' },
	{ "bzip",                 0, 'j' },
	{ "bzip2",                0, 'j' },
	{ "cd",                   1, 'C' },
	{ "check-links",          0, OPTION_CHECK_LINKS },
	{ "chroot",               0, OPTION_CHROOT },
	{ "compress",             0, 'Z' },
	{ "confirmation",         0, 'w' },
	{ "create",               0, 'c' },
	{ "dereference",	  0, 'L' },
	{ "directory",            1, 'C' },
	{ "disable-copyfile",	  0, OPTION_DISABLE_COPYFILE },
	{ "exclude",              1, OPTION_EXCLUDE },
	{ "exclude-from",         1, 'X' },
	{ "extract",              0, 'x' },
	{ "fast-read",            0, 'q' },
	{ "file",                 1, 'f' },
	{ "files-from",           1, 'T' },
	{ "format",               1, OPTION_FORMAT },
	{ "gid",		  1, OPTION_GID },
	{ "gname",		  1, OPTION_GNAME },
	{ "grzip",                0, OPTION_GRZIP },
	{ "gunzip",               0, 'z' },
	{ "gzip",                 0, 'z' },
	{ "help",                 0, OPTION_HELP },
	{ "hfsCompression",       0, OPTION_HFS_COMPRESSION },
	{ "include",              1, OPTION_INCLUDE },
	{ "insecure",             0, 'P' },
	{ "interactive",          0, 'w' },
	{ "keep-newer-files",     0, OPTION_KEEP_NEWER_FILES },
	{ "keep-old-files",       0, 'k' },
	{ "list",                 0, 't' },
	{ "lrzip",                0, OPTION_LRZIP },
	{ "lzip",                 0, OPTION_LZIP },
	{ "lzma",                 0, OPTION_LZMA },
	{ "lzop",                 0, OPTION_LZOP },
	{ "modification-time",    0, 'm' },
	{ "newer",		  1, OPTION_NEWER_CTIME },
	{ "newer-ctime",	  1, OPTION_NEWER_CTIME },
	{ "newer-ctime-than",	  1, OPTION_NEWER_CTIME_THAN },
	{ "newer-mtime",	  1, OPTION_NEWER_MTIME },
	{ "newer-mtime-than",	  1, OPTION_NEWER_MTIME_THAN },
	{ "newer-than",		  1, OPTION_NEWER_CTIME_THAN },
	{ "no-recursion",         0, 'n' },
	{ "no-same-owner",	  0, OPTION_NO_SAME_OWNER },
	{ "no-same-permissions",  0, OPTION_NO_SAME_PERMISSIONS },
	{ "nodump",               0, OPTION_NODUMP },
	{ "nopreserveHFSCompression",0, OPTION_NOPRESERVE_HFS_COMPRESSION },
	{ "norecurse",            0, 'n' },
	{ "null",		  0, OPTION_NULL },
	{ "numeric-owner",	  0, OPTION_NUMERIC_OWNER },
	{ "older",		  1, OPTION_OLDER_CTIME },
	{ "older-ctime",	  1, OPTION_OLDER_CTIME },
	{ "older-ctime-than",	  1, OPTION_OLDER_CTIME_THAN },
	{ "older-mtime",	  1, OPTION_OLDER_MTIME },
	{ "older-mtime-than",	  1, OPTION_OLDER_MTIME_THAN },
	{ "older-than",		  1, OPTION_OLDER_CTIME_THAN },
	{ "one-file-system",	  0, OPTION_ONE_FILE_SYSTEM },
	{ "options",              1, OPTION_OPTIONS },
	{ "posix",		  0, OPTION_POSIX },
	{ "preserve-permissions", 0, 'p' },
	{ "read-full-blocks",	  0, 'B' },
	{ "same-owner",	          0, OPTION_SAME_OWNER },
	{ "same-permissions",     0, 'p' },
	{ "strip-components",	  1, OPTION_STRIP_COMPONENTS },
	{ "to-stdout",            0, 'O' },
	{ "totals",		  0, OPTION_TOTALS },
	{ "uid",		  1, OPTION_UID },
	{ "uname",		  1, OPTION_UNAME },
	{ "uncompress",           0, 'Z' },
	{ "unlink",		  0, 'U' },
	{ "unlink-first",	  0, 'U' },
	{ "update",               0, 'u' },
	{ "use-compress-program", 1, OPTION_USE_COMPRESS_PROGRAM },
	{ "uuencode",             0, OPTION_UUENCODE },
	{ "verbose",              0, 'v' },
	{ "version",              0, OPTION_VERSION },
	{ "xz",                   0, 'J' },
	{ NULL, 0, 0 }
};

/*
 * This getopt implementation has two key features that common
 * getopt_long() implementations lack.  Apart from those, it's a
 * straightforward option parser, considerably simplified by not
 * needing to support the wealth of exotic getopt_long() features.  It
 * has, of course, been shamelessly tailored for bsdtar.  (If you're
 * looking for a generic getopt_long() implementation for your
 * project, I recommend Gregory Pietsch's public domain getopt_long()
 * implementation.)  The two additional features are:
 *
 * Old-style tar arguments: The original tar implementation treated
 * the first argument word as a list of single-character option
 * letters.  All arguments follow as separate words.  For example,
 *    tar xbf 32 /dev/tape
 * Here, the "xbf" is three option letters, "32" is the argument for
 * "b" and "/dev/tape" is the argument for "f".  We support this usage
 * if the first command-line argument does not begin with '-'.  We
 * also allow regular short and long options to follow, e.g.,
 *    tar xbf 32 /dev/tape -P --format=pax
 *
 * -W long options: There's an obscure GNU convention (only rarely
 * supported even there) that allows "-W option=argument" as an
 * alternative way to support long options.  This was supported in
 * early bsdtar as a way to access long options on platforms that did
 * not support getopt_long() and is preserved here for backwards
 * compatibility.  (Of course, if I'd started with a custom
 * command-line parser from the beginning, I would have had normal
 * long option support on every platform so that hack wouldn't have
 * been necessary.  Oh, well.  Some mistakes you just have to live
 * with.)
 *
 * TODO: We should be able to use this to pull files and intermingled
 * options (such as -C) from the command line in write mode.  That
 * will require a little rethinking of the argument handling in
 * bsdtar.c.
 *
 * TODO: If we want to support arbitrary command-line options from -T
 * input (as GNU tar does), we may need to extend this to handle option
 * words from sources other than argv/argc.  I'm not really sure if I
 * like that feature of GNU tar, so it's certainly not a priority.
 */

int
bsdtar_getopt(struct bsdtar *bsdtar)
{
	enum { state_start = 0, state_old_tar, state_next_word,
	       state_short, state_long };

	const struct bsdtar_option *popt, *match = NULL, *match2 = NULL;
	const char *p, *long_prefix = "--";
	size_t optlength;
	int opt = '?';
	int required = 0;

	bsdtar->argument = NULL;

	/* First time through, initialize everything. */
	if (bsdtar->getopt_state == state_start) {
		/* Skip program name. */
		++bsdtar->argv;
		--bsdtar->argc;
		if (*bsdtar->argv == NULL)
			return (-1);
		/* Decide between "new style" and "old style" arguments. */
		if (bsdtar->argv[0][0] == '-') {
			bsdtar->getopt_state = state_next_word;
		} else {
			bsdtar->getopt_state = state_old_tar;
			bsdtar->getopt_word = *bsdtar->argv++;
			--bsdtar->argc;
		}
	}

	/*
	 * We're parsing old-style tar arguments
	 */
	if (bsdtar->getopt_state == state_old_tar) {
		/* Get the next option character. */
		opt = *bsdtar->getopt_word++;
		if (opt == '\0') {
			/* New-style args can follow old-style. */
			bsdtar->getopt_state = state_next_word;
		} else {
			/* See if it takes an argument. */
			p = strchr(short_options, opt);
			if (p == NULL)
				return ('?');
			if (p[1] == ':') {
				bsdtar->argument = *bsdtar->argv;
				if (bsdtar->argument == NULL) {
					lafe_warnc(0,
					    "Option %c requires an argument",
					    opt);
					return ('?');
				}
				++bsdtar->argv;
				--bsdtar->argc;
			}
		}
	}

	/*
	 * We're ready to look at the next word in argv.
	 */
	if (bsdtar->getopt_state == state_next_word) {
		/* No more arguments, so no more options. */
		if (bsdtar->argv[0] == NULL)
			return (-1);
		/* Doesn't start with '-', so no more options. */
		if (bsdtar->argv[0][0] != '-')
			return (-1);
		/* "--" marks end of options; consume it and return. */
		if (strcmp(bsdtar->argv[0], "--") == 0) {
			++bsdtar->argv;
			--bsdtar->argc;
			return (-1);
		}
		/* Get next word for parsing. */
		bsdtar->getopt_word = *bsdtar->argv++;
		--bsdtar->argc;
		if (bsdtar->getopt_word[1] == '-') {
			/* Set up long option parser. */
			bsdtar->getopt_state = state_long;
			bsdtar->getopt_word += 2; /* Skip leading '--' */
		} else {
			/* Set up short option parser. */
			bsdtar->getopt_state = state_short;
			++bsdtar->getopt_word;  /* Skip leading '-' */
		}
	}

	/*
	 * We're parsing a group of POSIX-style single-character options.
	 */
	if (bsdtar->getopt_state == state_short) {
		/* Peel next option off of a group of short options. */
		opt = *bsdtar->getopt_word++;
		if (opt == '\0') {
			/* End of this group; recurse to get next option. */
			bsdtar->getopt_state = state_next_word;
			return bsdtar_getopt(bsdtar);
		}

		/* Does this option take an argument? */
		p = strchr(short_options, opt);
		if (p == NULL)
			return ('?');
		if (p[1] == ':')
			required = 1;

		/* If it takes an argument, parse that. */
		if (required) {
			/* If arg is run-in, bsdtar->getopt_word already points to it. */
			if (bsdtar->getopt_word[0] == '\0') {
				/* Otherwise, pick up the next word. */
				bsdtar->getopt_word = *bsdtar->argv;
				if (bsdtar->getopt_word == NULL) {
					lafe_warnc(0,
					    "Option -%c requires an argument",
					    opt);
					return ('?');
				}
				++bsdtar->argv;
				--bsdtar->argc;
			}
			if (opt == 'W') {
				bsdtar->getopt_state = state_long;
				long_prefix = "-W "; /* For clearer errors. */
			} else {
				bsdtar->getopt_state = state_next_word;
				bsdtar->argument = bsdtar->getopt_word;
			}
		}
	}

	/* We're reading a long option, including -W long=arg convention. */
	if (bsdtar->getopt_state == state_long) {
		/* After this long option, we'll be starting a new word. */
		bsdtar->getopt_state = state_next_word;

		/* Option name ends at '=' if there is one. */
		p = strchr(bsdtar->getopt_word, '=');
		if (p != NULL) {
			optlength = (size_t)(p - bsdtar->getopt_word);
			bsdtar->argument = (char *)(uintptr_t)(p + 1);
		} else {
			optlength = strlen(bsdtar->getopt_word);
		}

		/* Search the table for an unambiguous match. */
		for (popt = tar_longopts; popt->name != NULL; popt++) {
			/* Short-circuit if first chars don't match. */
			if (popt->name[0] != bsdtar->getopt_word[0])
				continue;
			/* If option is a prefix of name in table, record it.*/
			if (strncmp(bsdtar->getopt_word, popt->name, optlength) == 0) {
				match2 = match; /* Record up to two matches. */
				match = popt;
				/* If it's an exact match, we're done. */
				if (strlen(popt->name) == optlength) {
					match2 = NULL; /* Forget the others. */
					break;
				}
			}
		}

		/* Fail if there wasn't a unique match. */
		if (match == NULL) {
			lafe_warnc(0,
			    "Option %s%s is not supported",
			    long_prefix, bsdtar->getopt_word);
			return ('?');
		}
		if (match2 != NULL) {
			lafe_warnc(0,
			    "Ambiguous option %s%s (matches --%s and --%s)",
			    long_prefix, bsdtar->getopt_word, match->name, match2->name);
			return ('?');
		}

		/* We've found a unique match; does it need an argument? */
		if (match->required) {
			/* Argument required: get next word if necessary. */
			if (bsdtar->argument == NULL) {
				bsdtar->argument = *bsdtar->argv;
				if (bsdtar->argument == NULL) {
					lafe_warnc(0,
					    "Option %s%s requires an argument",
					    long_prefix, match->name);
					return ('?');
				}
				++bsdtar->argv;
				--bsdtar->argc;
			}
		} else {
			/* Argument forbidden: fail if there is one. */
			if (bsdtar->argument != NULL) {
				lafe_warnc(0,
				    "Option %s%s does not allow an argument",
				    long_prefix, match->name);
				return ('?');
			}
		}
		return (match->equivalent);
	}

	return (opt);
}


text:
<?php
namespace Concrete\Core\Block;

use Concrete\Core\Area\Area;
use Concrete\Core\Backup\ContentExporter;
use Concrete\Core\Backup\ContentImporter;
use Concrete\Core\Entity\Block\BlockType\BlockType;
use Concrete\Core\Block\View\BlockViewTemplate;
use Concrete\Core\File\Tracker\FileTrackableInterface;
use Concrete\Core\Legacy\BlockRecord;
use Concrete\Core\Page\Controller\PageController;
use Concrete\Core\Page\Type\Type;
use Concrete\Core\Permission\Checker;
use Concrete\Core\Statistics\UsageTracker\AggregateTracker;
use Concrete\Core\StyleCustomizer\Inline\StyleSet;
use Config;
use Database;
use Events;
use Package;
use Page;
use Concrete\Core\Error\ErrorList\ErrorList;

class BlockController extends \Concrete\Core\Controller\AbstractController
{
    public $headerItems = []; // blockrecord
    public $blockViewRenderOverride;
    protected $record;
    protected $helpers = ['form'];
    protected $block;
    protected $bID;
    protected $btDescription = "";
    protected $btName = "";
    protected $btHandle = "";
    protected $btIsInternal = 0;
    protected $btSupportsInlineAdd = false;
    protected $btIgnorePageThemeGridFrameworkContainer = false;
    protected $btSupportsInlineEdit = false;
    protected $btCopyWhenPropagate = 0;
    protected $btIncludeAll = 0;
    /** @var string | int  */
    protected $btInterfaceWidth = "400";
    /** @var string | int  */
    protected $btInterfaceHeight = "400";
    protected $btHasRendered = false;
    protected $btCacheBlockRecord = true;
    protected $btCacheBlockOutput = false;
    protected $btCacheBlockOutputLifetime = 0;
    protected $btCacheBlockOutputOnPost = false;
    protected $btCacheBlockOutputForRegisteredUsers = false;
    protected $bActionCID;
    protected $btExportPageColumns = [];
    protected $btExportFileColumns = [];
    protected $btExportPageTypeColumns = [];
    protected $btExportPageFeedColumns = [];
    protected $btExportFileFolderColumns = [];
    protected $btWrapperClass = '';
    protected $btDefaultSet;
    protected $identifier;
    /** @var null|string  */
    protected $btTable = null;
    protected $btID;

    /**
     * @internal
     * Note: do not rely on these being here. These are going to be moved.
     */
    public static $btTitleFormats = ['h1' => 'H1', 'h2' => 'H2', 'h3' => 'H3', 'h4' => 'H4', 'h5' => 'H5', 'h6' => 'H6', 'p' => 'Normal'];

    /**
     * Set this to true if the data sent to the save/performSave methods can contain NULL values that should be persisted.
     *
     * @var bool
     */
    protected $supportSavingNullValues = false;

    public function getBlockTypeInSetName()
    {
        return $this->getBlockTypeName();
    }

    public function getBlockTypeExportPageColumns()
    {
        return $this->btExportPageColumns;
    }

    public function getIdentifier()
    {
        return $this->identifier;
    }

    public function getBlockTypeWrapperClass()
    {
        return $this->btWrapperClass;
    }

    /**
     * Installs the current block's DB xml file. If a block needs to do more than this, this should be overridden.
     *
     * public function install($path) {
     *     $this->doMySpecialInstallMethod();
     *     $this->doSecondSpecialInstallMethod();
     *     parent::install($path);
     * }
     * .
     *
     * There are several different possible return values:
     *  Returns FALSE if $btTable is set but no db.xml file exists.
     *  Otherwise returns object with two properties: ->result (a boolean), and ->message (a string).
     *  If ->result is true, the installation was successful
     *  (although the db.xml file might only have one field declared which will cause C5 to have problems later on, so you you will want to check for that separately).
     *  If ->result is false, the installation failed and you can check ->message for the explanation
     *  (usually -- sometimes ->message will be blank, in which case there's either a malformed db.xml file or an "unknown database error").
     * See concrete/models/block_types.php::doInstallBlockType() for usage example.
     *
     * @param string $path
     *
     * @return mixed boolean or object having ->result (boolean) and ->message (string) properties
     */
    public function install($path)
    {
        // passed path is the path to this block (try saying that ten times fast)
        // create the necessary table

        if (!$this->btTable) {
            $r = new \stdClass();
            $r->result = true;

            return $r;
        }
        $ret = Package::installDB($path . '/' . FILENAME_BLOCK_DB);

        return $ret;
    }

    /**
     * Renders a view in the block's folder.
     *
     * public function view() { // The view() method is automatically run when a block is viewed
     *     $this->render("other_special_view"); // don't use .php
     * }
     * .
     *
     * @param string $view
     */
    public function render($view)
    {
        $this->blockViewRenderOverride = $view;
    }

    /**
     * Used to validate a blocks data before saving to the database
     * Generally should return an empty ErrorList if valid
     * Custom Packages may return a boolean value
     *
     * @param $args array|string|null
     * @version <= 8.4.3 Method returns ErrorList|boolean
     * @version 8.5.0a3 Method returns ErrorList
     * @return ErrorList|boolean
     */
    public function validate($args)
    {
        $e = $this->app->make(ErrorList::class);
        return $e;
    }

    public function getBlockControllerData()
    {
        return $this->record;
    }

    /**
     * Persist the block options.
     *
     * @param array $args An array that contains the block options
     * @param bool $loadExisting Shall we initialize the record to be saved with the current data?
     */
    protected function performSave($args, $loadExisting = false)
    {
        //$argsMerged = array_merge($_POST, $args);
        if ($this->btTable) {
            $db = Database::connection();
            $columns = $db->MetaColumnNames($this->btTable);
            $this->record = new BlockRecord($this->btTable);
            $this->record->bID = $this->bID;
            if ($loadExisting) {
                $this->record->Load('bID=' . $this->bID);
            }

            if ($this->supportSavingNullValues) {
                foreach ($columns as $key) {
                    if (array_key_exists($key, $args)) {
                        $this->record->{$key} = $args[$key];
                    }
                }
            } else {
                foreach ($columns as $key) {
                    if (isset($args[$key])) {
                        $this->record->{$key} = $args[$key];
                    }
                }
            }

            $this->record->Replace();
            if ($this->cacheBlockRecord() && Config::get('concrete.cache.blocks')) {
                $record = base64_encode(serialize($this->record));
                $db = Database::connection();
                $db->Execute('update Blocks set btCachedBlockRecord = ? where bID = ?', [$record, $this->bID]);
            }
        }

        if ($this instanceof FileTrackableInterface) {
            $this->app->make(AggregateTracker::class)->track($this);
        }
    }

    /**
     * Run when a block is added or edited. Automatically saves block data against the block's database table. If a block needs to do more than this (save to multiple tables, upload files, etc... it should override this.
     *
     * @param array<string,mixed> $args
     * @return void
     */
    public function save($args)
    {
        $this->performSave($args);
    }

    public function cacheBlockRecord()
    {
        return $this->btCacheBlockRecord;
    }

    /**
     * @deprecated
     */
    public function getPermissionsObject()
    {
        return $this->getPermissionObject();
    }

    public function getBlockTypeDefaultSet()
    {
        return $this->btDefaultSet;
    }

    /**
     * Gets the permissions object for this controller's block.
     */
    public function getPermissionObject()
    {
        $bp = new Permissions(Block::getByID($this->bID));

        return $bp;
    }

    /**
     * Automatically run when a block is duplicated. This most likely happens when a block is edited: a block is first duplicated, and then presented to the user to make changes.
     *
     * @param int $newBlockID
     *
     * @return BlockRecord | null $newInstance
     */
    public function duplicate($newBID)
    {
        if ($this->btTable) {
            $ni = new BlockRecord($this->btTable);
            $ni->bID = $this->bID;
            $ni->Load('bID=' . $this->bID);
            $newInstance = clone $ni;
            $newInstance->bID = $newBID;
            $newInstance->Insert();

            return $newInstance;
        }
    }

    public function __wakeup()
    {
        $this->__construct();
    }

    /**
     * Instantiates the block controller.
     *
     * @param BlockType $obj |Block $obj
     */
    public function __construct($obj = null)
    {
        parent::__construct();
        if ($obj instanceof BlockType) {
            $this->btID = $obj->getBlockTypeID();
            $this->identifier = 'BLOCKTYPE_' . $obj->getBlockTypeID();
            $this->btHandle = $obj->getBlockTypeHandle();
        } else {
            if ($obj instanceof Block) {
                $b = $obj;
                $this->btID = $b->getBlockTypeID();
                $this->identifier = 'BLOCK_' . $obj->getBlockID();
                $this->bID = $b->getBlockID();
                $this->btHandle = $obj->getBlockTypeHandle();
                $this->btCachedBlockRecord = $obj->getBlockCachedRecord();
                $this->setBlockObject($b);
                $this->load();
            }
        }
        $this->set('controller', $this);
    }

    /**
     * Sets the block object for this controller.
     */
    public function setBlockObject($b)
    {
        $this->block = $b;
    }

    /**
     * Loads the BlockRecord class based on its attribute names.
     */
    protected function load()
    {
        if ($this->btTable) {
            if ($this->btCacheBlockRecord && $this->btCachedBlockRecord && Config::get('concrete.cache.blocks')) {
                $this->record = unserialize(base64_decode($this->btCachedBlockRecord));
            } else {
                $this->record = new BlockRecord($this->btTable);
                $this->record->bID = $this->bID;
                $this->record->Load('bID=' . $this->bID);
                if ($this->btCacheBlockRecord && Config::get('concrete.cache.blocks')) {
                    // this is the first time we're loading
                    $record = base64_encode(serialize($this->record));
                    $db = Database::connection();
                    $db->Execute('update Blocks set btCachedBlockRecord = ? where bID = ?', [$record, $this->bID]);
                }
            }
        }

        $event = new \Symfony\Component\EventDispatcher\GenericEvent();
        $event->setArgument('record', $this->record);
        $event->setArgument('btHandle', $this->btHandle);
        $event->setArgument('bID', $this->bID);
        $ret = Events::dispatch('on_block_load', $event);
        $this->record = $ret->getArgument('record');

        if (is_object($this->record)) {
            foreach ($this->record as $key => $value) {
                $this->{$key} = $value;
                $this->set($key, $value);
            }
        }
    }

    public function export(\SimpleXMLElement $blockNode)
    {
        $tables[] = $this->getBlockTypeDatabaseTable();
        if (isset($this->btExportTables)) {
            $tables = $this->btExportTables;
        }
        $db = Database::connection();

        foreach ($tables as $tbl) {
            if (!$tbl) {
                continue;
            }
            $data = $blockNode->addChild('data');
            $data->addAttribute('table', $tbl);
            $columns = $db->MetaColumns($tbl);
            // remove columns we don't want
            unset($columns['bid']);
            $r = $db->Execute('select * from ' . $tbl . ' where bID = ?', [$this->bID]);
            while ($record = $r->fetch()) {
                $tableRecord = $data->addChild('record');
                foreach ($record as $key => $value) {
                    if (isset($columns[strtolower($key)])) {
                        if (in_array($key, $this->btExportPageColumns)) {
                            $tableRecord->addChild($key, ContentExporter::replacePageWithPlaceHolder($value));
                        } elseif (in_array($key, $this->btExportFileColumns)) {
                            $tableRecord->addChild($key, ContentExporter::replaceFileWithPlaceHolder($value));
                        } elseif (in_array($key, $this->btExportPageTypeColumns)) {
                            $tableRecord->addChild($key, ContentExporter::replacePageTypeWithPlaceHolder($value));
                        } elseif (in_array($key, $this->btExportPageFeedColumns)) {
                            $tableRecord->addChild($key, ContentExporter::replacePageFeedWithPlaceHolder($value));
                        } elseif (in_array($key, $this->btExportFileFolderColumns)) {
                            $tableRecord->addChild($key, ContentExporter::replaceFileFolderWithPlaceHolder($value));
                        } else {
                            $cnode = $tableRecord->addChild($key);
                            $node = dom_import_simplexml($cnode);
                            $no = $node->ownerDocument;
                            $node->appendChild($no->createCDataSection($value));
                        }
                    }
                }
            }
        }
    }

    public function getBlockTypeDatabaseTable()
    {
        return $this->btTable;
    }

    public function import($page, $arHandle, \SimpleXMLElement $blockNode)
    {
        // handle the adodb stuff
        $args = $this->getImportData($blockNode, $page);
        $blockData = [];

        $bt = \Concrete\Core\Block\BlockType\BlockType::getByHandle($this->btHandle);
        $b = $page->addBlock($bt, $arHandle, $args);
        $bName = (string) $blockNode['name'];
        $bFilename = (string) $blockNode['custom-template'];
        if ($bName) {
            $blockData['bName'] = $bName;
        }
        if ($bFilename) {
            $blockData['bFilename'] = $bFilename;
        }
        if (count($blockData)) {
            $b->updateBlockInformation($blockData);
        }

        if ($page->isMasterCollection() && $blockNode['mc-block-id'] != '') {
            ContentImporter::addMasterCollectionBlockID($b, (string) $blockNode['mc-block-id']);
        }

        // now we insert stuff that isn't part of the btTable
        // we have to do this this way because we need a bID
        $this->importAdditionalData($b, $blockNode);

        // now we handle container settings
        $bCustomContainerSettings = (string) $blockNode['custom-container-settings'];
        if ($bCustomContainerSettings === '0' || $bCustomContainerSettings === '1') {
            $b->setCustomContainerSettings($bCustomContainerSettings);
        }

        // now we handle the styles
        if (isset($blockNode->style)) {
            $set = StyleSet::import($blockNode->style);
            $b->setCustomStyleSet($set);
        }

        // now we handle block caching
        $cache = (int) $blockNode['cache-output'];
        if ($cache) {
            $b->setCustomCacheSettings(true, $blockNode['cache-output-on-post'], $blockNode['cache-output-for-registered-users'],
                $blockNode['cache-output-lifetime']);
        }

        if ($this instanceof FileTrackableInterface) {
            $blockController = $b->getController(); // We have to do this because we need it loaded with the right block object, data.
            $this->app->make(AggregateTracker::class)->track($blockController);
        }
    }

    /**
     * @param \SimpleXMLElement $blockNode
     * @param \Concrete\Core\Page\Page $page
     * @return array<string,mixed>
     */
    protected function getImportData($blockNode, $page)
    {
        $args = [];
        $inspector = \Core::make('import/value_inspector');
        if (isset($blockNode->data)) {
            foreach ($blockNode->data as $data) {
                if ($data['table'] == $this->getBlockTypeDatabaseTable()) {
                    if (isset($data->record)) {
                        foreach ($data->record->children() as $node) {
                            $result = $inspector->inspect((string) $node);
                            $args[$node->getName()] = $result->getReplacedValue();
                        }
                    }
                }
            }
        }

        return $args;
    }

    protected function importAdditionalData($b, $blockNode)
    {
        $inspector = \Core::make('import/value_inspector');
        if (isset($blockNode->data)) {
            foreach ($blockNode->data as $data) {
                if (strtoupper((string) $data['table']) != strtoupper((string) $this->getBlockTypeDatabaseTable())) {
                    $table = (string) $data['table'];
                    if (isset($data->record)) {
                        foreach ($data->record as $record) {
                            $aar = new \Concrete\Core\Legacy\BlockRecord($table);
                            $aar->bID = $b->getBlockID();
                            foreach ($record->children() as $node) {
                                $nodeName = $node->getName();
                                $result = $inspector->inspect((string) $node);
                                $aar->{$nodeName} = $result->getReplacedValue();
                            }
                            $aar->Save();
                        }
                    }
                }
            }
        }
    }

    public function setPassThruBlockController(PageController $controller)
    {
        $controller->setPassThruBlockController($this->block, $this);
    }

    public function validateAddBlockPassThruAction(Checker $ap, BlockType $bt)
    {
        return $ap->canAddBlock($bt);
    }

    public function validateEditBlockPassThruAction(Block $b)
    {
        $bp = new \Permissions($b);

        return $bp->canEditBlock();
    }

    public function validateComposerAddBlockPassThruAction(Type $type)
    {
        $pp = new \Permissions($type);

        return $pp->canAddPageType();
    }

    /**
     * @return int|null
     */
    public function getBlockTypeID()
    {
        return $this->btID;
    }

    public function validateComposerEditBlockPassThruAction(Block $b)
    {
        return $this->validateEditBlockPassThruAction($b);
    }

    public function getPassThruActionAndParameters($parameters)
    {
        $method = 'action_' . $parameters[0];
        $parameters = array_slice($parameters, 1);
        return [$method, $parameters];
    }

    /**
     * Creates a URL that can be posted or navigated to that, when done so, will automatically run the corresponding method inside the block's controller.
     * It can also be used to perform system operations, accordingly to the current action.
     *
     * @param mixed $task,... The arguments to build the URL (variable number of arguments).
     *
     * @return \Concrete\Core\Url\UrlImmutable|null Return NULL in case of problems
     */
    public function getActionURL($task)
    {
        try {

            if (is_object($this->block)) {
                if (is_object($this->block->getProxyBlock())) {
                    $b = $this->block->getProxyBlock();
                } else {
                    $b = $this->block;
                }

                $action = $this->getAction();
                if ($action === 'view' || strpos($action, 'action_') === 0) {
                    $c = Page::getCurrentPage();
                    if (is_object($b) && is_object($c)) {
                        $arguments = func_get_args();
                        $arguments[] = $b->getBlockID();
                        array_unshift($arguments, $c);

                        return call_user_func_array(array('\URL', 'page'), $arguments);
                    }
                } else {
                    $c = $this->getCollectionObject();
                    $arguments = array_merge(array('/ccm/system/block/action/edit',
                        $c->getCollectionID(),
                        urlencode($this->getAreaObject()->getAreaHandle()),
                        $this->block->getBlockID(),
                    ), func_get_args());

                    return call_user_func_array(array('\URL', 'to'), $arguments);

                }
            } else {
                $c = \Page::getCurrentPage();
                $arguments = array_merge(array('/ccm/system/block/action/add',
                    $c->getCollectionID(),
                    urlencode($this->getAreaObject()->getAreaHandle()),
                    $this->getBlockTypeID(),
                ), func_get_args());

                return call_user_func_array(array('\URL', 'to'), $arguments);

            }
        } catch (\Exception $e) {
        }

    }

    public function isValidControllerTask($method, $parameters = [])
    {
        if (strpos($method, 'action_') !== 0) { // gotta start with action_
            return false;
        }
        if (is_callable([$this, $method])) {
            $r = new \ReflectionMethod(get_class($this), $method);
            if (count($parameters) - $r->getNumberOfParameters() <= 1) {
                // how do we get <= 1? If it's 1, that means that the method has one fewer param. That's ok because
                // certain older blocks don't know that the last param ought to be a $bID. If they're equal it's zero
                // which is best. and if they're greater that's ok too.
                return true;
            }
        }

        return false;
    }

    public function cacheBlockOutput()
    {
        return $this->btCacheBlockOutput;
    }

    public function cacheBlockOutputForRegisteredUsers()
    {
        return $this->btCacheBlockOutputForRegisteredUsers;
    }

    public function cacheBlockOutputOnPost()
    {
        return $this->btCacheBlockOutputOnPost;
    }

    public function getBlockTypeCacheOutputLifetime()
    {
        return $this->btCacheBlockOutputLifetime;
    }

    public function getCollectionObject()
    {
        if (!$this->block) {
            return false;
        }

        // This block is new for 9.0.2 – we need this because we're passing around blocks with page objects in them
        // for file trackability, but without this code we lose the reference to the proper collection + collection version
        $blockPage = $this->block->getBlockCollectionObject();
        if ($blockPage) {
            return $blockPage;
        }

        if (!isset($this->bActionCID)) {
            $this->bActionCID = $this->block->getBlockActionCollectionID();
        }

        if ($this->bActionCID > 0) {
            return Page::getByID($this->bActionCID);
        }

        return Page::getCurrentPage();
    }

    public function field($fieldName)
    {
        $field = '_bf[' . $this->identifier;
        $b = $this->getBlockObject();
        if (is_object($b)) {
            $xc = $b->getBlockCollectionObject();
            if (is_object($xc)) {
                $field .= '_' . $xc->getCollectionID();
            }
        }
        $field .= '][' . $fieldName . ']';

        return $field;
    }

    /**
     * Gets the generic Block object attached to this controller's instance.
     *
     * @return Block $b
     */
    public function getBlockObject()
    {
        if (is_object($this->block)) {
            return $this->block;
        }

        return Block::getByID($this->bID);
    }

    public function post($field = false, $defaultValue = null)
    {
        // the only post that matters is the one for this attribute's name space
        $req = ($this->requestArray == false) ? $_POST : $this->requestArray;
        if (is_array($req['_bf'])) {
            $identifier = $this->identifier;
            $b = $this->getBlockObject();
            if (is_object($b)) {
                $xc = $b->getBlockCollectionObject();
                if (is_object($xc)) {
                    $identifier .= '_' . $xc->getCollectionID();
                }
            }

            $p = $req['_bf'][$identifier];
            if ($field) {
                return $p[$field];
            }

            return $p;
        }

        return parent::post($field, $defaultValue);
    }

    /**
     * Automatically run when a block is deleted. This removes the special data from the block's specific database table. If a block needs to do more than this this method should be overridden.
     *
     * @return void
     */
    public function delete()
    {
        if ($this->bID > 0) {
            if ($this->btTable) {
                $ni = new BlockRecord($this->btTable);
                $ni->bID = $this->bID;
                $ni->Load('bID=' . $this->bID);
                $ni->delete();
            }
        }
        if ($this instanceof FileTrackableInterface) {
            $this->app->make(AggregateTracker::class)->forget($this);
        }
    }

    public function outputAutoHeaderItems()
    {
        $b = $this->getBlockObject();
        if (is_object($b)) {
            $bvt = new BlockViewTemplate($b);
            $bvt->registerTemplateAssets();
        }
    }

    public function registerViewAssets($outputContent = '')
    {
    }

    public function setupAndRun($method)
    {
        if ($method) {
            $this->task = $method;
        }

        if (method_exists($this, 'on_start')) {
            $this->on_start($method);
        }
        if ($method) {
            $this->runTask($method, []);
        }

        if (method_exists($this, 'on_before_render')) {
            $this->on_before_render($method);
        }
    }

    /**
     * Gets the Area object attached to this controller's instance.
     *
     * @return Area $a
     */
    public function getAreaObject()
    {
        return $this->area;
    }

    public function setAreaObject($a)
    {
        $this->area = $a;
    }

    /**
     * @todo   Make block's uninstallable
     */
    public function uninstall()
    {
        // currently blocks cannot be uninstalled
    }

    /**
     * Returns the name of the block type.
     *
     * @return string $btName
     */
    public function getBlockTypeName()
    {
        return t($this->btName);
    }

    /**
     * Returns the width of the block type's interface when presented in page.
     *
     * @return int
     */
    public function getInterfaceWidth()
    {
        return $this->btInterfaceWidth;
    }

    /**
     * Returns the height of the block type's interface when presented in page.
     *
     * @return int
     */
    public function getInterfaceHeight()
    {
        return $this->btInterfaceHeight;
    }

    /**
     * Returns the description of the block type.
     *
     * @return string
     */
    public function getBlockTypeDescription()
    {
        return t($this->btDescription);
    }

    /**
     * Returns HTML that will be shown when a user wants help for a given block type.
     */
    public function getBlockTypeHelp()
    {
        return isset($this->btHelpContent) ? $this->btHelpContent : null;
    }

    public function isCopiedWhenPropagated()
    {
        return $this->btCopyWhenPropagate;
    }

    /**
     * Returns whether this block type is included in all versions. Default is false - block types are typically versioned but sometimes it makes sense not to do so.
     *
     * @return bool
     */
    public function includeAll()
    {
        return $this->btIncludeAll;
    }

    /**
     * Returns whether this block type is internal to Concrete. If it's internal it's not displayed in the front end interface. Examples include the LibraryFile block.
     *
     * @return bool
     */
    public function isBlockTypeInternal()
    {
        return $this->btIsInternal;
    }

    /**
     * if a the current BlockType supports inline edit or not.
     *
     * @return bool
     */
    public function supportsInlineEdit()
    {
        return $this->btSupportsInlineEdit;
    }

    /**
     * if a the current BlockType supports inline add or not.
     *
     * @return bool
     */
    public function supportsInlineAdd()
    {
        return $this->btSupportsInlineAdd;
    }

    /**
     * If true, container classes will not be wrapped around this block type in edit mode (if the
     * theme in question supports a grid framework.
     *
     * @return bool
     */
    public function ignorePageThemeGridFrameworkContainer()
    {
        return $this->btIgnorePageThemeGridFrameworkContainer;
    }

    /**
     * Returns a key/value array of strings that is used to translate items when used in javascript.
     */
    public function getJavaScriptStrings()
    {
        return [];
    }
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "opts.h"

/* Type and Function Declarations
 *****************************************************************************/
typedef struct {
    char* name;
    char* tag;
    char* value;
} option_t;

typedef struct entry_t {
    void* value;
    struct entry_t* next;
} entry_t;

typedef enum { LONG, SHORT } opt_type_t;

typedef struct {
    unsigned int line_idx;
    unsigned int col_idx;
    unsigned int arg_count;
    char** arg_vect;
    int current;
    opts_cfg_t* options;
} stream_ctx_t;

static void opts_parse_short_option( stream_ctx_t* ctx );
static void opts_parse_long_option( stream_ctx_t* ctx );
static char* opts_parse_optarg(stream_ctx_t* ctx, char* opt_name);
static void opts_parse_argument( stream_ctx_t* ctx );
static void opts_parse_error(const char* msg, char* opt_name);
static opts_cfg_t* opts_get_option_config( opts_cfg_t* opts, opt_type_t typ, char* name );
static char* opts_next_token( stream_ctx_t* ctx );
static void opts_consume_ws( stream_ctx_t* ctx );
static char opts_next_char( stream_ctx_t* ctx );
static char* opts_append_char( char* str, char ch );
static char* strclone(const char* p_old);
static void opts_add_option(char* name, char* tag, char* arg);
static void opts_add_argument(char* arg);

/* Global State
 *****************************************************************************/
static const char* Program_Name = NULL;
static entry_t* Options   = NULL;
static entry_t* Arguments = NULL;
static opts_err_cbfn_t Error_Callback = &opts_parse_error;

/* The Options Parser
 *****************************************************************************/
void opts_parse(opts_cfg_t* opts, opts_err_cbfn_t err_cb, int argc, char** argv) {
    /* Setup the stream */
    stream_ctx_t ctx;
    ctx.line_idx  = 0;
    ctx.col_idx   = -1;
    ctx.arg_count = argc-1;
    ctx.arg_vect  = &argv[1];
    ctx.options   = opts;
    (void)opts_next_char( &ctx ); /* Loads up the first char */

    /* Record the error handler if one was provided */
    if (NULL != err_cb)
        Error_Callback = err_cb;

    /* Record the program name */
    Program_Name = argv[0];

    /* Until we run out of characters */
    while (ctx.current != EOF) {
        opts_consume_ws( &ctx );
        /* If we have an option */
        if ('-' == ctx.current) {
            /* And it's a long one */
            if ('-' == opts_next_char( &ctx )) {
                /* Consume the second '-' */
                opts_next_char( &ctx );
                /* Parse the option */
                opts_parse_long_option( &ctx );
            } else {
                /* Parse the option */
                opts_parse_short_option( &ctx );
            }
        } else {
            /* It's not an option so add it to the "extra" bucket */
            opts_parse_argument( &ctx );
        }
    }
}

static void opts_parse_short_option( stream_ctx_t* ctx ) {
    char opt[2] = { ctx->current, '\0' };
    char* opt_name = strclone(opt);
    opts_cfg_t* config = opts_get_option_config( ctx->options, SHORT, opt_name );
    if (config != NULL) {
        char* opt_arg = NULL;
        (void)opts_next_char( ctx );
        /* Check if the flag has an argument */
        if (config->has_arg)
            opt_arg = opts_parse_optarg( ctx, opt_name );
        /* If there are more flags in the flag group */
        else if ((' ' != ctx->current) && (EOF != ctx->current))
            opts_parse_short_option( ctx );
        opts_add_option( opt_name, config->tag, opt_arg );
    } else {
        Error_Callback("Unknown Option", opt_name);
    }
}

static void opts_parse_long_option( stream_ctx_t* ctx ) {
    char* opt_name = opts_next_token( ctx );
    opts_cfg_t* config = opts_get_option_config( ctx->options, LONG, opt_name );
    if (config != NULL) {
        char* opt_arg = NULL;
        /* Parse the argument if one is expected */
        if (config->has_arg)
            opt_arg = opts_parse_optarg( ctx, opt_name );
        /* Store off the option value */
        opts_add_option( opt_name, config->tag, opt_arg );
    } else {
        Error_Callback("Unknown Option", opt_name);
    }
}

static char* opts_parse_optarg(stream_ctx_t* ctx, char* opt_name) {
    opts_consume_ws( ctx );
    if (('-' == ctx->current) || (EOF == ctx->current))
        Error_Callback("Expected an argument, none received", opt_name);
    return opts_next_token( ctx );
}

static void opts_parse_error(const char* msg, char* opt_name) {
    fprintf(stderr, "Option '%s' : %s\n", opt_name, msg);
    free(opt_name);
    opts_reset();
    exit(1);
}

static void opts_parse_argument( stream_ctx_t* ctx ) {
    char* arg_val = opts_next_token( ctx );
    if (NULL != arg_val)
        opts_add_argument(arg_val);
}

static opts_cfg_t* opts_get_option_config( opts_cfg_t* opts, opt_type_t type, char* name ) {
    opts_cfg_t* cfg = NULL;
    int i = 0;
    while( opts[i].name != NULL ) {
        opt_type_t curr_type = (strlen(opts[i].name) > 1) ? LONG : SHORT;
        if ((curr_type == type) && (0 == strcmp(opts[i].name, name))) {
            cfg = &(opts[i]);
            break;
        }
        i++;
    }
    return cfg;
}

static char* opts_next_token( stream_ctx_t* ctx ) {
    char* tok = NULL;

    opts_consume_ws( ctx );
    if (EOF != ctx->current) {
        // Setup the string
        tok = (char*)malloc(2);
        tok[0] = ctx->current;
        tok[1] = '\0';

        (void)opts_next_char( ctx );
        while ((EOF != ctx->current) && (' ' != ctx->current)) {
            tok = opts_append_char( tok, ctx->current );
            (void)opts_next_char( ctx );
        }
    }
    return tok;
}

static void opts_consume_ws( stream_ctx_t* ctx ) {
    while (' ' == ctx->current)
        (void)opts_next_char( ctx );
}

static char opts_next_char( stream_ctx_t* ctx ) {
    char current = EOF;
    ctx->current = EOF;

    if (ctx->line_idx < ctx->arg_count) {
        ctx->col_idx++;
        if (ctx->line_idx < ctx->arg_count) {
            char temp = ctx->arg_vect[ ctx->line_idx ][ ctx->col_idx ];
            if (temp == '\0') {
                ctx->col_idx = -1;
                ctx->line_idx++;
                current = ' ';
                ctx->current = current;
            } else {
                temp = (temp == '=') ? ' ' : temp;
                current = temp;
                ctx->current = current;
            }
        }
    }

    return current;
}

static char* opts_append_char( char* str, char ch ) {
    unsigned int new_size = strlen( str ) + 2;
    str = (char*)realloc( str, new_size );
    str[ new_size - 2 ] = ch;
    str[ new_size - 1 ] = '\0';
    return str;
}

static void opts_add_option(char* name, char* tag, char* arg) {
    option_t* option = (option_t*)malloc(sizeof(option_t));
    option->name     = name;
    option->tag      = strclone(tag);
    option->value    = (NULL == arg) ? name : arg;
    entry_t* entry   = (entry_t*)malloc(sizeof(entry_t));
    entry->value     = (void*)option;
    entry->next      = Options;
    Options          = entry;
}

static void opts_add_argument(char* arg_val) {
    entry_t* entry = (entry_t*)malloc(sizeof(entry_t));
    entry->value   = (void*)arg_val;
    entry->next    = Arguments;
    Arguments      = entry;
}

/* Parser Cleanup
 *****************************************************************************/
void opts_reset(void) {
    while (Options != NULL) {
        entry_t* entry = Options;
        option_t* opt  = (option_t*)entry->value;
        Options = entry->next;
        free(opt->name);
        free(opt->tag);
        if(opt->name != opt->value)
            free(opt->value);
        free(opt);
        free(entry);
    }

    while (Arguments != NULL) {
        entry_t* entry = Arguments;
        char* arg  = (char*)entry->value;
        Arguments = entry->next;
        free(arg);
        free(entry);
    }
}

/* Utility Functions
 *****************************************************************************/
static char* strclone(const char* p_old) {
    size_t length = strlen(p_old);
    char* p_str = (char*)malloc(length+1);
    memcpy(p_str, p_old, length);
    p_str[length] = '\0';
    return p_str;
}

/* Query Functions
 *****************************************************************************/
static option_t* find_option(const char* name, const char* tag) {
    option_t* p_opt = NULL;
    entry_t* current = Options;
    while (current != NULL) {
        option_t* curr_opt = (option_t*)current->value;
        if (((NULL == name) || (0 == strcmp(name, curr_opt->name))) &&
            ((NULL == tag)  || (0 == strcmp(tag,  curr_opt->tag)))) {
            p_opt = curr_opt;
            break;
        }
        current = current->next;
    }
    return p_opt;
}

bool opts_is_set(const char* name, const char* tag) {
    return (NULL != find_option(name,tag));
}

const char* opts_get_value(const char* name, const char* tag) {
    option_t* p_opt = find_option(name,tag);
    return (NULL == p_opt) ? NULL : p_opt->value;
}

bool opts_equal(const char* name, const char* tag, const char* value) {
    return (0 == strcmp(value, opts_get_value(name,tag)));
}

const char** opts_select(const char* name, const char* tag) {
    size_t index = 0;
    const char** ret = (const char**)malloc(sizeof(const char*));
    ret[index] = NULL;

    entry_t* current = Options;
    while (current != NULL) {
        option_t* curr_opt = (option_t*)current->value;
        if (((NULL == name) || (0 == strcmp(name, curr_opt->name))) &&
            ((NULL == tag)  || (0 == strcmp(tag,  curr_opt->tag)))) {
            ret = (const char**)realloc(ret, (index+2)*sizeof(const char*));
            ret[index++] = curr_opt->value;
            ret[index]   = NULL;
        }
        current = current->next;
    }

    return ret;
}

const char** opts_arguments(void) {
    size_t index = 0;
    const char** ret = (const char**)malloc(sizeof(const char*));
    ret[0] = NULL;
    entry_t* entry = Arguments;
    while (NULL != entry) {
        ret = (const char**)realloc(ret, (index+2)*sizeof(const char*));
        ret[index++] = (const char*)entry->value;
        ret[index]   = NULL;
        entry = entry->next;
    }
    return ret;
}

const char* opts_prog_name(void) {
    return Program_Name;
}

/* Help Message Printing
 *****************************************************************************/
static int opts_calc_padding(opts_cfg_t* opts) {
    bool opts_have_args = false;
    size_t sz = 0;
    /* Figure out the longest option name */
    while (NULL != opts->name) {
        size_t name_sz = strlen(opts->name);
        if (name_sz > sz) {
            sz = name_sz;
        }
        if (opts->has_arg) {
            opts_have_args = true;
        }
        opts++;
    }
    return sz + 4 + ((opts_have_args) ? 4 : 0);
}

void opts_print_help(FILE* ofile, opts_cfg_t* opts) {
    int padding = opts_calc_padding(opts);
    char*  buffer  = (char*)malloc(padding+1);
    while (NULL != opts->name) {
        if (1 == strlen(opts->name))
            sprintf(buffer, " -%s", opts->name);
        else
            sprintf(buffer, " --%s", opts->name);
        if (opts->has_arg) sprintf(&buffer[strlen(buffer)], "=ARG ");
        fprintf(ofile, "%-*s%s\n", padding, buffer, opts->desc);
        opts++;
    }
    free(buffer);
}


text:
package org.fest.swing.driver;

import static javax.swing.JSplitPane.VERTICAL_SPLIT;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.swing.edt.GuiActionRunner.execute;

import java.awt.Dimension;

import javax.swing.JList;
import javax.swing.JSplitPane;

import org.fest.swing.annotation.RunsInEDT;
import org.fest.swing.edt.GuiQuery;
import org.fest.swing.test.core.RobotBasedTestCase;
import org.fest.swing.test.swing.TestWindow;
import org.junit.Test;

/**
 * Tests for {@link JSplitPaneSetDividerLocationTask#setDividerLocation(JSplitPane, int)}.
 *
 * @author Alex Ruiz
 * @author Yvonne Wang
 */
public class JSplitPaneSetDividerLocationTask_setDividerLocation_Test extends RobotBasedTestCase {
  private JSplitPane splitPane;
  private int location;

  @Override
  protected void onSetUp() {
    MyWindow window = MyWindow.createNew();
    splitPane = window.splitPane;
    location = 200;
  }

  @Test
  public void should_move_divider_to_given_location() {
    assertThat(dividerLocation()).isNotEqualTo(location);
    JSplitPaneSetDividerLocationTask.setDividerLocation(splitPane, location);
    robot.waitForIdle();
    assertThat(dividerLocation()).isEqualTo(location);
  }

  @RunsInEDT
  private int dividerLocation() {
    return dividerLocationOf(splitPane);
  }

  @RunsInEDT
  private static int dividerLocationOf(final JSplitPane splitPane) {
    return execute(new GuiQuery<Integer>() {
      @Override
      protected Integer executeInEDT() {
        return splitPane.getDividerLocation();
      }
    });
  }

  private static class MyWindow extends TestWindow {
    final JSplitPane splitPane;

    @RunsInEDT
    static MyWindow createNew() {
      return execute(new GuiQuery<MyWindow>() {
        @Override
        protected MyWindow executeInEDT() {
          return new MyWindow();
        }
      });
    }

    private MyWindow() {
      super(JSplitPaneSetDividerLocationTask_setDividerLocation_Test.class);
      splitPane = new JSplitPane(VERTICAL_SPLIT, new JList(), new JList());
      splitPane.setDividerLocation(150);
      splitPane.setPreferredSize(new Dimension(300, 300));
      add(splitPane);
    }
  }
}


text:
package org.apache.asterix.lang.aql.parser;

import java.util.ArrayList;
import java.util.List;

import org.apache.asterix.common.exceptions.CompilationException;
import org.apache.asterix.common.exceptions.ErrorCode;
import org.apache.asterix.lang.common.base.IParser;
import org.apache.asterix.lang.common.base.IParserFactory;
import org.apache.asterix.lang.common.base.Statement;
import org.apache.asterix.lang.common.statement.FunctionDecl;
import org.apache.asterix.lang.common.struct.VarIdentifier;
import org.apache.asterix.metadata.entities.Function;
import org.apache.commons.io.input.CharSequenceReader;

public class FunctionParser {

    private final IParserFactory parserFactory;

    public FunctionParser(IParserFactory parserFactory) {
        this.parserFactory = parserFactory;
    }

    public FunctionDecl getFunctionDecl(Function function) throws CompilationException {
        if (!function.getLanguage().equals(Function.LANGUAGE_AQL)) {
            throw new CompilationException(ErrorCode.COMPILATION_INCOMPATIBLE_FUNCTION_LANGUAGE,
                    Function.LANGUAGE_AQL, function.getLanguage());
        }
        String functionBody = function.getFunctionBody();
        List<String> params = function.getParams();
        List<VarIdentifier> varIdentifiers = new ArrayList<VarIdentifier>();

        StringBuilder builder = new StringBuilder();
        builder.append(" use dataverse " + function.getDataverseName() + ";");
        builder.append(" declare function " + function.getName().split("@")[0]);
        builder.append("(");
        boolean first = true;
        for (String param : params) {
            VarIdentifier varId = new VarIdentifier(param);
            varIdentifiers.add(varId);
            if (first) {
                first = false;
            } else {
                builder.append(",");
            }
            builder.append(param);
        }
        builder.append("){\n").append(functionBody).append("\n}");

        IParser parser = parserFactory.createParser(new CharSequenceReader(builder));
        List<Statement> statements = parser.parse();
        FunctionDecl decl = (FunctionDecl) statements.get(1);
        return decl;
    }

}


text:
import functools

from pyramid.config.views import DefaultViewMapper
from pyramid.interfaces import IViewMapperFactory

from pyramid_csrf.backends.cookie import CookieCSRFFactory
from pyramid_csrf.csrf import check_csrf
from pyramid_csrf.interfaces import ICSRFFactory

def set_csrf_factory(config, factory):
    factory = config.maybe_dotted(factory)

    def register():
        config.registry.registerUtility(factory, ICSRFFactory)

    config.action(ICSRFFactory, register)

def csrf(request):
    factory = request.registry.queryUtility(ICSRFFactory)
    if factory is not None:
        factory = factory(request)
    return factory

def _add_vary_cookie(request, response):
    vary = set(response.vary if response.vary is not None else [])
    vary |= set(["Cookie"])
    response.vary = vary

def csrf_mapper_factory(mapper):
    class CSRFMapper(mapper):

        def __call__(self, view):
            view = super().__call__(view)

            @functools.wraps(view)
            def wrapped(context, request):
                # Assign our view to an innerview function so that we can
                # modify it inside of the wrapped function.
                innerview = view

                # Check to see if we have an ICSRFFactory registered, if we do
                # not then we'll assume that CSRF checking has been disabled.
                factory = request.registry.queryUtility(ICSRFFactory)
                if factory is None:
                    return innerview(context, request)

                # Check if we're processing CSRF for this request at all or
                # if it has been exempted from CSRF.
                if not getattr(request, "_process_csrf", True):
                    return innerview(context, request)

                # If we're processing CSRF for this request, then we want to
                # set a Vary: Cookie header on every response to ensure that
                # we don't cache the result of a CSRF check or a form with a
                # CSRF token in it.
                if getattr(request, "_process_csrf", False):
                    request.add_response_callback(_add_vary_cookie)

                # Actually check our CSRF
                check_csrf(request)

                return innerview(context, request)

            return wrapped
    return CSRFMapper

def includeme(config):
    # We need to commit what's happened so far so that we can get the current
    # default ViewMapper
    config.commit()

    # Register our directives and request methods.
    config.add_directive("set_csrf_factory", set_csrf_factory)
    config.add_request_method(csrf, name="csrf", reify=True)

    # We want to default to using the CookieCSRF
    config.set_csrf_factory(CookieCSRFFactory())

    # Get the current default ViewMapper, and create a subclass of it that
    # will wrap our view with CSRF checking.
    mapper = config.registry.queryUtility(IViewMapperFactory)
    if mapper is None:
        mapper = DefaultViewMapper
    config.set_view_mapper(csrf_mapper_factory(mapper))


text:
package com.infoDiscover.adminCenter.ui.component.infoDiscoverSpaceManagement.dimensionManagement;

import at.downdrown.vaadinaddons.highchartsapi.Colors;
import at.downdrown.vaadinaddons.highchartsapi.HighChart;
import at.downdrown.vaadinaddons.highchartsapi.HighChartFactory;
import at.downdrown.vaadinaddons.highchartsapi.exceptions.HighChartsException;
import at.downdrown.vaadinaddons.highchartsapi.model.ChartConfiguration;
import at.downdrown.vaadinaddons.highchartsapi.model.ChartType;
import at.downdrown.vaadinaddons.highchartsapi.model.data.base.*;
import at.downdrown.vaadinaddons.highchartsapi.model.series.BarChartSeries;
import com.infoDiscover.adminCenter.ui.util.UserClientInfo;
import com.infoDiscover.infoDiscoverEngine.util.InfoDiscoverEngineConstant;
import com.infoDiscover.infoDiscoverEngine.util.helper.DataTypeStatisticMetrics;
import com.infoDiscover.infoDiscoverEngine.util.helper.DiscoverSpaceStatisticMetrics;
import com.vaadin.server.Sizeable;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.VerticalLayout;

import java.util.List;

/**
 * Created by wangychu on 10/4/16.
 */
public class InfoDiscoverSpaceDimensionsInfoChart extends VerticalLayout {

    private UserClientInfo currentUserClientInfo;
    private ChartConfiguration barConfiguration;
    private HighChart barChart;

    public InfoDiscoverSpaceDimensionsInfoChart(UserClientInfo currentUserClientInfo) {
        this.currentUserClientInfo = currentUserClientInfo;
        this.barConfiguration = new ChartConfiguration();
        this.barConfiguration.setTitle("维度类型数据分布");
        this.barConfiguration.setChartType(ChartType.BAR);
        this.barConfiguration.setBackgroundColor(Colors.WHITE);
    }

    public void renderDimensionsInfoChart(DiscoverSpaceStatisticMetrics discoverSpaceStatisticMetrics){
        this.removeAllComponents();
        BarChartSeries barChartSeries = new BarChartSeries("维度类型数据总量");
        List<DataTypeStatisticMetrics> dimensionsStatisticMetricsList=discoverSpaceStatisticMetrics.getDimensionsStatisticMetrics();
        for(DataTypeStatisticMetrics currentMetrics:dimensionsStatisticMetricsList){
            String dimensionTypeName=currentMetrics.getDataTypeName().replaceFirst(InfoDiscoverEngineConstant.CLASSPERFIX_DIMENSION,"");
            barChartSeries.addData(new StringIntData(dimensionTypeName, (int) currentMetrics.getTypeDataCount()));
        }
        this.barConfiguration.getSeriesList().clear();
        this.barConfiguration.getSeriesList().add(barChartSeries);
        try {
            this.barChart = HighChartFactory.renderChart(this.barConfiguration);
            barChart.setHeight(500, Sizeable.Unit.PIXELS);
            barChart.setWidth(600, Sizeable.Unit.PIXELS);
            this.addComponent(this.barChart);
            this.setComponentAlignment(barChart, Alignment.MIDDLE_LEFT);
        } catch (HighChartsException e) {
            e.printStackTrace();
        }
    }
}


text:
package helios.samples.helios;

import static org.junit.Assert.assertEquals;

import static helios.Helios.validate;
import static helios.Validators.inRange;
import static helios.Validators.required;
import static helios.Validators.inRangeOfString;

import java.util.List;
import org.junit.Test;

import helios.ValidatorError;

public class HeliosNestedTest {

    static class Person {

        public final String name;
        public final Integer age;
        public final String city;

        public Person(String name, Integer age, String city) {
            this.name = name;
            this.age = age;
            this.city = city;
        }
    }

    // tag::test[]
    @Test public void testPerson() {
        Person john = new Person("John", 35, "Paris");
        List<ValidatorError> errors = validate("person", john,
            (Person p) -> validate("name", p.name, required()),
            (Person p) -> validate("age", p.age, required(), inRange(0,100)),
            (Person p) -> validate("city", p.city, inRangeOfString(4,4))); // this will fail

        assertEquals(errors.get(0).key, "string.max.notmet");
        assertEquals(errors.get(0).property, "city");
        assertEquals(errors.get(0).keyI18n, "person.city.string.max.notmet");
    }
    // end::test[]
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="hibernateWebServiceClientDefinitionDao"
          class="egovframework.rte.itl.webservice.data.dao.hibernate.HibernateWebServiceClientDefinitionDao">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="hibernateWebServiceServerDefinitionDao"
          class="egovframework.rte.itl.webservice.data.dao.hibernate.HibernateWebServiceServerDefinitionDao">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem:test/test;showdown=true"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource"/>
        <property name="mappingResources">
            <list>
                <value>/egovframework/rte/itl/integration/metadata/dao/hibernate/OrganizationDefinition.hbm.xml</value>
                <value>/egovframework/rte/itl/integration/metadata/dao/hibernate/SystemDefinition.hbm.xml</value>
                <value>/egovframework/rte/itl/integration/metadata/dao/hibernate/ServiceDefinition.hbm.xml</value>
                <value>/egovframework/rte/itl/integration/metadata/dao/hibernate/RecordTypeDefinition.hbm.xml</value>
                <value>/egovframework/rte/itl/integration/metadata/dao/hibernate/IntegrationDefinition.hbm.xml</value>
                <value>/egovframework/rte/itl/webservice/data/dao/hibernate/WebServiceClientDefinition.hbm.xml</value>
                <value>/egovframework/rte/itl/webservice/data/dao/hibernate/WebServiceServerDefinition.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.HSQLDialect
                hibernate.show_sql=false
                hibernate.hbm2ddl.auto=create-drop
            </value>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
</beans>


text:
package com.report.common.repository.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.report.common.dal.admin.dao.GroupDao;
import com.report.common.dal.admin.entity.dto.Group;
import com.report.common.dal.admin.entity.vo.GroupModel;
import com.report.common.dal.admin.util.PageUtil;
import com.report.common.model.PageHelper;
import com.report.common.model.SessionUtil;
import com.report.common.repository.GroupRepository;

@Repository
public class GroupRepositoryImpl implements GroupRepository {
	@Resource
    private GroupDao groupDao;

	@Override
	public String getGroupCodeByMemberId(Long memberId) {
		return groupDao.getGroupCodeByMemberId(memberId);
	}

    @Override
    public Long count(GroupModel groupModel) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("groupCode", groupModel.getGroupCode());
        params.put("groupName", groupModel.getGroupName());
        params.put("status", groupModel.getStatus());
        params.put("currentMemberGroupCode", groupModel.getCurrentMemberGroupCode());

        return groupDao.countForGroupList(params);
    }

    @Override
    public List<GroupModel> fingGroupsByPage(PageHelper pageHelper, GroupModel groupModel) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sort", pageHelper.getSort());
        params.put("order", pageHelper.getOrder());
        params.put("groupCode", groupModel.getGroupCode());
        params.put("groupName", groupModel.getGroupName());
        params.put("status", groupModel.getStatus());
        params.put("currentMemberGroupCode", groupModel.getCurrentMemberGroupCode());
        return groupDao.findGroupdByPage4SysAdmin(params, PageUtil.paged(pageHelper.getPage() - 1, pageHelper.getRows()));
    }

    @Override
    public void updateGroupCodeByMemberId(Long memberId, String groupCode) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("groupCode", groupCode);
        params.put("memberId", memberId);
        groupDao.updateGroupCodeByMemberId(params);
    }

    @Override
    public List<Group> findAllGroups() {
    	return groupDao.findAllGroups();
    }

    @Override
    public List<Map<String, String>> findGroupNamesByCurrentMemberId(Long currentMemberId) {
        if (SessionUtil.getUserInfo().isAdmin()) {
        	return groupDao.findGroupNames4SysAdmin();
        }
        return Collections.emptyList();
    }

    @Override
    public boolean isGroupCodeExists(GroupModel groupModel) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("groupCode", groupModel.getGroupCode());
        if (groupModel.getId() != null) {
            params.put("groupId", groupModel.getId());
        }
        return groupDao.countGroupByGroupCode(params) > 0;
    }

    @Override
    public boolean isAssociatedWithGroup(Long memberId) {
        return groupDao.countGroupByMemberId(memberId) > 0;
    }

    @Override
    public void associatedWithGroup(Long memberId, String groupCode) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("memberId", memberId);
        params.put("groupCode", groupCode);
        groupDao.addMappingGroup2Member(params);

    }

	@Override
	public void deleteAssociateWithMember(Long memberId) {
		groupDao.deleteAssociateWithMember(memberId);
	}
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>ConversionNotSupportedException Methods</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Documentation - Microsoft .NET Framework 4.0

ConversionNotSupportedException Methods

The methods of the ConversionNotSupportedException class are listed below. For a complete list of ConversionNotSupportedException class members, see the ConversionNotSupportedException Members topic.

Public Static (Shared) Methods

Create	Overloaded.  Creates a new instance of the ConversionNotSupportedException class.

Public Instance Methods

Equals (inherited from Object)	 Determines whether the specified Object is equal to the current Object.

GetBaseException (inherited from Exception)	 When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

GetHashCode (inherited from Object)	 Serves as a hash function for a particular type.

GetObjectData (inherited from Exception)	 When overridden in a derived class, sets the SerializationInfo with information about the exception.

GetType (inherited from Exception)	 Gets the runtime type of the current instance.

ToString (inherited from Exception)	 Creates and returns a string representation of the current exception.

Protected Instance Methods

Finalize (inherited from Object)	 Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.

MemberwiseClone (inherited from Object)	 Creates a shallow copy of the current Object.

See Also

        ConversionNotSupportedException Class | log4net.Util.TypeConverters Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="ConversionNotSupportedException class, methods">
        </param>
      </object>

          Copyright 2004-2011 The Apache Software Foundation.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Asterina nodulosa Speg., 1889

### Remarks
null


text:
import {
  prepareHTTPInterceptor,
  mockCredentials,
  generateInvalidPayloadTests,
} from '../helpers';
import CoinpaymentsClient from '../../src';

import { CMDS } from '../../src/constants';

describe('Create transaction e2e test', () => {
  let client: CoinpaymentsClient;
  const VALID_API_PAYLOAD = {
    currency1: 'x',
    currency2: 'y',
    amount: 1,
    buyer_email: 'buyer@email.com',
  };
  beforeAll(() => {
    client = new CoinpaymentsClient(mockCredentials);
  });
  it('Should not throw error on valid payload', async () => {
    const VALID_PAYLOAD_MOCK = {
      cmd: CMDS.CREATE_TRANSACTION,
      ...VALID_API_PAYLOAD,
    };
    const scope = prepareHTTPInterceptor(mockCredentials, VALID_PAYLOAD_MOCK);
    await client.createTransaction(VALID_API_PAYLOAD);
    expect(scope.isDone()).toBeTruthy();
  });

  generateInvalidPayloadTests('createTransaction', VALID_API_PAYLOAD);
});


text:
/* @flow */
import type { Request, Response } from 'transport'
import compressible from 'compressible'
import { gzip } from 'middleware'

export default async function(
  request: Request,
  response: Response
): Promise<Response> {
  if (
    'Accept-Encoding' in request.headers &&
    request.headers['Accept-Encoding'].includes('gzip') &&
    compressible(response.headers['Content-Type'])
  ) {
    return {
      ...response,
      headers: {
        ...response.headers,
        'Content-Encoding': 'gzip'
      },
      body: await gzip(response.body)
    }
  } else {
    return response
  }
}


text:
from __future__ import division, unicode_literals

"""
#TODO: Write module doc.
"""

__author__ = 'Shyue Ping Ong'
__copyright__ = 'Copyright 2013, The Materials Virtual Lab'
__version__ = '0.1'
__maintainer__ = 'Shyue Ping Ong'
__email__ = 'ongsp@ucsd.edu'
__date__ = '8/1/15'

import warnings
warnings.warn("pymatgen.io.vaspio_set has been moved pymatgen.io.vasp.sets. "
              "This stub will be removed in pymatgen 4.0.")
from .vasp.sets import *


text:
package com.bq.corbel.oauth.api;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bq.corbel.lib.token.TokenGrant;
import com.bq.corbel.lib.token.TokenInfo;
import com.bq.corbel.lib.token.exception.TokenVerificationException;
import com.bq.corbel.lib.token.factory.TokenFactory;
import com.bq.corbel.lib.token.model.TokenType;
import com.bq.corbel.lib.token.parser.TokenParser;
import com.bq.corbel.lib.token.reader.TokenReader;
import com.bq.corbel.lib.ws.api.error.ErrorResponseFactory;
import com.bq.corbel.lib.ws.model.Error;
import com.bq.corbel.oauth.model.Client;
import com.bq.corbel.oauth.model.User;
import com.bq.corbel.oauth.repository.UserRepository;
import com.bq.corbel.oauth.service.ClientService;
import com.bq.corbel.oauth.token.TokenExpireTime;

@Path(ApiVersion.CURRENT + "/oauth/token") public class TokenResource {

    private static final String AUTHORIZATION_CODE_GRANT_TYPE = "authorization_code";
    private static final Logger LOG = LoggerFactory.getLogger(TokenResource.class);
    private final TokenParser tokenParser;
    private final TokenFactory tokenFactory;
    private final ClientService clientService;
    private final UserRepository userRepository;
    private final TokenExpireTime tokenExpireTime;

    public TokenResource(TokenParser tokenParser, TokenFactory tokenFactory, ClientService clientService, UserRepository userRepository,
            TokenExpireTime tokenExpireTime) {
        this.tokenParser = tokenParser;
        this.tokenFactory = tokenFactory;
        this.clientService = clientService;
        this.userRepository = userRepository;
        this.tokenExpireTime = tokenExpireTime;
    }

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response accessToken(@FormParam("grant_type") String grantType, @FormParam("code") String code,
            @FormParam("client_id") String clientId, @FormParam("client_secret") String clientSecret,
            @FormParam("validated_mail_required") Boolean validatedMailRequired) {

        if (StringUtils.isBlank(grantType)) {
            return ErrorResponseFactory.getInstance().missingParameter("grant_type");
        }
        if (StringUtils.isBlank(clientId)) {
            return ErrorResponseFactory.getInstance().missingParameter("client_id");
        }
        if (StringUtils.isBlank(clientSecret)) {
            return ErrorResponseFactory.getInstance().missingParameter("client_secret");
        }
        if (isNotSupportedGrantType(grantType)) {
            return ErrorResponseFactory.getInstance().badRequest(new Error("invalid_grant", grantType));
        }
        if (StringUtils.isBlank(code)) {
            return ErrorResponseFactory.getInstance().missingParameter("code");
        }

        Client client = clientService.findByName(clientId)
                .orElseThrow(() -> new WebApplicationException(ErrorResponseFactory.getInstance().unauthorized()));

        try {
            TokenReader tokenReader = tokenParser.parseAndVerify(code);

            if (TokenType.CODE != tokenReader.getInfo().getTokenType()) {
                LOG.debug("Invalid token type: " + tokenReader.getInfo().getTokenType());
                return ErrorResponseFactory.getInstance().unauthorized();
            }

            if (!tokenHasClientIdAndValidSecret(tokenReader, client, clientSecret)) {
                LOG.debug("Invalid clientId and/or secret");
                return ErrorResponseFactory.getInstance().unauthorized();
            }

            if (BooleanUtils.isTrue(validatedMailRequired) && !userHasValidatedEmail(tokenReader)) {
                return ErrorResponseFactory.getInstance().unauthorized("User need validate e-mail");
            }

            TokenInfo tokenInfo = TokenInfo.newBuilder().setType(TokenType.TOKEN).setUserId(tokenReader.getInfo().getUserId())
                    .setClientId(tokenReader.getInfo().getClientId()).setDomainId(client.getDomain()).build();

            TokenGrant token = tokenFactory.createToken(tokenInfo, tokenExpireTime.getTokenExpireTimeFromResponseType(TokenType.TOKEN));
            return Response.ok().entity(token).type(MediaType.APPLICATION_JSON_TYPE).build();

        } catch (TokenVerificationException e) {
            LOG.debug("Token verification failed", e);
        }
        return ErrorResponseFactory.getInstance().unauthorized();
    }

    private boolean userHasValidatedEmail(TokenReader tokenReader) {
        User user = userRepository.findOne(tokenReader.getInfo().getUserId());
        if (user != null) {
            return user.isEmailValidated();
        }
        return false;
    }

    private boolean tokenHasClientIdAndValidSecret(TokenReader tokenReader, Client client, String clientSecret) {
        return StringUtils.equals(tokenReader.getInfo().getClientId(), client.getName())
                && clientService.verifyClientSecret(clientSecret, client);
    }

    private boolean isNotSupportedGrantType(String grantType) {
        return !AUTHORIZATION_CODE_GRANT_TYPE.equals(grantType);
    }
}


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>StandardEditDistance</title>
<meta name="date" content="2018-07-03">
<meta name="keywords" content="edu.umn.biomedicus.common.collect.StandardEditDistance class">
<meta name="keywords" content="levenstein()">
<meta name="keywords" content="compute()">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

edu.umn.biomedicus.common.collect

Class StandardEditDistance<T extends CharSequence>

edu.umn.biomedicus.common.collect.StandardEditDistance<T>

All Implemented Interfaces:

Metric<T>

public class StandardEditDistance<T extends CharSequence>
implements Metric<T>

Class for computing the edit distance between two words.

Constructor Summary

Constructors

Constructor and Description

StandardEditDistance()

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

int
compute()

static <T extends CharSequence>
StandardEditDistance<T>
levenstein()

Methods inherited from interface edu.umn.biomedicus.common.collect.Metric

compute

Constructor Detail

StandardEditDistance

public StandardEditDistance()

Method Detail

levenstein

public static <T extends CharSequence> StandardEditDistance<T> levenstein()

compute

public int compute()

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
namespace DataSpec::DNAMP1 {
struct IceZoomer : IScriptObject {
  AT_DECL_DNA_YAMLV
  String<-1> name;
  Value<atVec3f> location;
  Value<atVec3f> orientation;
  Value<atVec3f> scale;
  PatternedInfo patternedInfo;
  ActorParameters actorParameters;
  Value<float> advanceWpRadius;
  Value<float> unknown2;
  Value<float> alignAngleVel;
  Value<float> unknown4;
  Value<float> playerObstructionMinDist;
  Value<float> moveForwardWeight;
  UniqueID32 modelRes;
  UniqueID32 skinRes;
  DamageVulnerability damageVulnerabilty;
  Value<float> unknown9;

  void addCMDLRigPairs(PAKRouter<PAKBridge>& pakRouter, CharacterAssociations<UniqueID32>& charAssoc) const override {
    actorParameters.addCMDLRigPairs(pakRouter, charAssoc, patternedInfo.animationParameters);
  }

  void nameIDs(PAKRouter<PAKBridge>& pakRouter) const override {
    patternedInfo.nameIDs(pakRouter, name + "_patterned");
    actorParameters.nameIDs(pakRouter, name + "_actp");
  }

  void gatherDependencies(std::vector<hecl::ProjectPath>& pathsOut,
                          std::vector<hecl::ProjectPath>& lazyOut) const override {
    patternedInfo.depIDs(pathsOut);
    actorParameters.depIDs(pathsOut, lazyOut);
    g_curSpec->flattenDependencies(modelRes, pathsOut);
    g_curSpec->flattenDependencies(skinRes, pathsOut);
  }

  void gatherScans(std::vector<Scan>& scansOut) const override { actorParameters.scanIDs(scansOut); }
};
} // namespace DataSpec::DNAMP1


text:
namespace PokerTell.DatabaseSetup
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;

    using Infrastructure;

    using NHibernate.Tool.hbm2ddl;

    using PokerTell.DatabaseSetup.Properties;
    using PokerTell.Infrastructure.Interfaces.DatabaseSetup;

    public class ExternalManagedDatabase : IExternalManagedDatabase
    {
        public IDataProvider DataProvider { get;  protected set; }

        IDataProviderInfo _dataProviderInfo;

        /// <summary>
        /// Initializes a new instance of the <see cref="ExternalManagedDatabase"/> class.
        /// Creates a database that will be managed by the Database Manager.
        /// Make sure to set up the dependencies as explained for each parameter.
        /// </summary>
        /// <param name="dataProvider">
        /// Needs to be connected to a server
        /// ParameterPlaceHolder needs to be set
        /// </param>
        /// <param name="dataProviderInfo">
        /// External: MySql, Postgres etc.
        /// </param>
        public IManagedDatabase InitializeWith(IDataProvider dataProvider, IDataProviderInfo dataProviderInfo)
        {
            _dataProviderInfo = dataProviderInfo;
            DataProvider = dataProvider;

            return this;
        }

        public string ConnectionString { get; private set; }

        public IDataProviderInfo DataProviderInfo
        {
            get { return _dataProviderInfo; }
        }

        public IManagedDatabase ChooseDatabase(string databaseName)
        {
            var connectionInfo = new DatabaseConnectionInfo(DataProvider.Connection.ConnectionString);
            ConnectionString = string.Format("{0} Database = {1};", connectionInfo.ServerConnectString, databaseName);

            DataProvider.Connect(ConnectionString, _dataProviderInfo);

            return this;
        }

        public IManagedDatabase CreateDatabase(string databaseName)
        {
            string nonQuery = string.Format(Resources.Sql_Queries_CreateDatabase, databaseName);
            DataProvider.ExecuteNonQuery(nonQuery);

            ChooseDatabase(databaseName);

            return this;
        }

        public IManagedDatabase CreateTables()
        {
            DataProvider.BuildSessionFactory();

            new SchemaExport(DataProvider.NHibernateConfiguration)
                .Execute(false, true, false, DataProvider.Connection, null);

            return this;
        }

        public IManagedDatabase VersionDatabase(string databaseName)
        {
            DataProvider.ExecuteNonQuery(string.Format(Resources.Sql_Queries_External_InsertVersionNumber, databaseName, ApplicationProperties.VersionNumber));
            return this;
        }

        public bool DatabaseExists(string databaseName)
        {
            string query = Resources.Sql_Queries_ShowDatabases;

            using (IDataReader dr = DataProvider.ExecuteQuery(query))
            {
                while (dr.Read())
                {
                    if (dr.GetString(0).Equals(databaseName))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public IManagedDatabase DeleteDatabase(string databaseName)
        {
            string nonQuery = string.Format(Resources.Sql_Queries_DropDatabase, databaseName);
            DataProvider.ExecuteNonQuery(nonQuery);
            return this;
        }

        /// <summary>
        /// Examines all tables in all databases.
        /// If the convertedpokerhands table is contained, the database name is included
        /// </summary>
        /// <returns></returns>
        public IEnumerable<string> GetAllPokerTellDatabaseNames()
        {
            return GetNamesOfAllDatabasesWhoseFirstTableIs("convertedpokerhands");
        }

        public IEnumerable<string> GetAllPokerOfficeDatabaseNames()
        {
            return GetAllDatabaseNames()
                .Where(name => name.Equals("pokeroffice") || name.EndsWith("_podb"));
        }

        public IEnumerable<string> GetAllPokerTrackerDatabaseNames()
        {
            throw new NotImplementedException();
        }

        public string GetNameFor(string databaseInUse)
        {
            return databaseInUse;
        }

        IEnumerable<string> GetNamesOfAllDatabasesWhoseFirstTableIs(string firstTableName)
        {
            var allDatabaseNames = GetAllDatabaseNames();

            foreach (string databaseName in allDatabaseNames)
            {
                string query = string.Format("USE `{0}`; SHOW TABLES;", databaseName);

                using (IDataReader dr = DataProvider.ExecuteQuery(query))
                {
                    while (dr.Read())
                    {
                        string tableName = dr[0].ToString();
                        if (tableName.Equals(firstTableName))
                        {
                            yield return databaseName;
                        }
                    }
                }
            }
        }

        IEnumerable<string> GetAllDatabaseNames()
        {
            var allDatabases = new List<string>();
            const string query = "SHOW DATABASES;";

            using (IDataReader dr = DataProvider.ExecuteQuery(query))
            {
                while (dr.Read())
                {
                    allDatabases.Add(dr[0].ToString());
                }
            }

            return allDatabases;
        }
    }
}